-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
74 lines (62 loc) · 1.31 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package main
import (
"fmt"
"github.com/takaishi/mdtoc/config"
"github.com/takaishi/mdtoc/mdtoc"
"github.com/urfave/cli"
"io/ioutil"
"log"
"os"
)
func main() {
app := cli.NewApp()
app.Version = config.Version
app.Flags = []cli.Flag{
cli.StringFlag{
Name: "file, f",
Usage: "Specify to generate table of contents.",
},
cli.BoolFlag{
Name: "in-file, i",
Usage: "Insert table of contents to md file specified --file option.",
},
cli.IntFlag{
Name: "level, l",
Value: 2,
Usage: "Specify the level of the header to insert as the table of contents.",
},
}
app.Action = func(c *cli.Context) error {
return action(c)
}
err := app.Run(os.Args)
if err != nil {
log.Fatal(err)
}
}
func action(c *cli.Context) error {
mdtoc := mdtoc.MDToc{File: c.String("file"), InFile: c.Bool("in-file"), Level: c.Int("level")}
input, err := ioutil.ReadFile(mdtoc.File)
if err != nil {
return err
}
toc := mdtoc.GenerateTOC(input)
output, err := mdtoc.InsertTOC(string(input), toc)
if err != nil {
return err
}
if c.Bool("in-file") {
f, err := os.OpenFile(c.String("file"), os.O_WRONLY|os.O_TRUNC, os.ModeAppend)
defer f.Close()
if err != nil {
return err
}
_, err = f.Write([]byte(output))
if err != nil {
return err
}
} else {
fmt.Printf(output)
}
return nil
}