-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
92 lines (80 loc) · 1.87 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package main
import (
"flag"
"fmt"
"os"
"regexp"
"strings"
"github.com/anotherhadi/markdown"
)
func formatTitle(title string) string {
str := strings.TrimSpace(title)
str = strings.ReplaceAll(str, " ", "-")
str = regexp.MustCompile(`[^a-zA-Z0-9 _-]+`).ReplaceAllString(str, "")
str = strings.ToLower(str)
return str
}
func main() {
var indentationString string
var depth int
var startBy int
flag.StringVar(&indentationString, "indent", " ", "Indentation string (' ','tab')")
flag.IntVar(
&depth,
"depth",
3,
"Depth of the table of contents (1,2,...,6). 2 will print only H1 and H2",
)
flag.IntVar(&startBy, "start-by", 1, "Start by specific header (1,2,...,6). 2 will start by H2")
flag.Parse()
var filePath string
if len(flag.Args()) < 1 {
fmt.Println("Usage: markdown-table-of-contents [markdownfile.md]")
fmt.Println("Type 'markdown-table-of-contents -h' for help")
os.Exit(1)
}
filePath = flag.Args()[0]
md := markdown.New(filePath)
err := md.Read()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
var strs []string = []string{}
for _, section := range md.Sections {
if section.SectionType == markdown.NullSection {
continue
}
numberOfSpaces := len(string(section.SectionType)) - 1
if numberOfSpaces+1 > depth {
continue
}
if numberOfSpaces+1 < startBy {
continue
}
var str string
str += strings.Repeat(indentationString, numberOfSpaces)
str += "- [" + section.Text + "](#" + formatTitle(section.Text) + ")"
strs = append(strs, str)
}
// If all start with indent, remove all
for {
allStartWithIndent := true
for _, str := range strs {
if !strings.HasPrefix(str, indentationString) {
allStartWithIndent = false
break
}
}
if allStartWithIndent {
for i := range strs {
strs[i] = strs[i][len(indentationString):]
}
} else {
break
}
}
for _, str := range strs {
fmt.Println(str)
}
}