-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmdtoc.go
197 lines (173 loc) · 4.32 KB
/
mdtoc.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
package mdtoc
import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"os"
"strings"
"unicode"
)
const headerFormat = "- [%s](#%s)"
const atxHeader = "#"
const headerIdent = " "
func isValidHeaderRune(r rune) bool {
return unicode.IsNumber(r) || unicode.IsLetter(r) || unicode.IsSpace(r)
}
func normalizeHeader(header string) string {
lowerNoHash := strings.TrimLeft(strings.ToLower(header), "#")
noInvalidChars := []rune{}
for _, r := range lowerNoHash {
if isValidHeaderRune(r) {
noInvalidChars = append(noInvalidChars, r)
}
}
return strings.Replace(string(noInvalidChars), " ", "-", -1)
}
type writer func(data string)
func writeHeader(
writeOutput writer,
level int,
header string,
headersCount map[string]int,
) {
normalizedHeader := normalizeHeader(header)
count := headersCount[normalizedHeader]
headersCount[normalizedHeader] = count + 1
if count > 0 {
normalizedHeader = fmt.Sprintf("%s-%d", normalizedHeader, count)
}
line := fmt.Sprintf(
headerFormat,
header,
normalizedHeader,
)
for i := 1; i < level; i++ {
writeOutput(headerIdent)
}
writeOutput(line + "\n")
}
func parseHeader(line string) (int, string, bool) {
if !startsWithAtxHeader(line) {
return 0, "", false
}
spaceTrimmed := strings.TrimRight(line, " ")
parsed := strings.Split(spaceTrimmed, " ")
if len(parsed) == 1 {
return 0, "", false
}
headerlevel := len(parsed[0])
header := parsed[1:]
return headerlevel, strings.Join(header, " "), true
}
func startsWithAtxHeader(line string) bool {
return strings.Index(line, atxHeader) == 0
}
func skipUntil(scanner *bufio.Scanner, stop func(string) bool) error {
for scanner.Scan() {
if stop(scanner.Text()) {
return nil
}
}
return errors.New("skipped all content")
}
func Generate(input io.Reader, output io.Writer) error {
headerStart := "<!-- mdtocstart -->"
tocHeader := "# Table of Contents"
headerEnd := "<!-- mdtocend -->"
scanner := bufio.NewScanner(input)
headersCount := map[string]int{}
var writeErr error
writeOutput := func(s string) {
if writeErr != nil {
return
}
_, writeErr = output.Write([]byte(s))
}
var original bytes.Buffer
var isCodeSection bool
var wroteHeader bool
for scanner.Scan() {
line := scanner.Text()
if strings.TrimSpace(line) == headerStart {
err := skipUntil(scanner, func(l string) bool {
return strings.TrimSpace(l) == headerEnd
})
if err != nil {
return fmt.Errorf("error removing headers(corrupted headers?): %s", err)
}
err = skipUntil(scanner, func(l string) bool { return l != "" })
if err != nil {
// Just header present, removed headers
return nil
}
line = scanner.Text()
}
_, err := original.Write([]byte(line + "\n"))
if err != nil {
return err
}
if strings.HasPrefix(line, "```") {
isCodeSection = !isCodeSection
}
level, header, ok := parseHeader(line)
if !ok || isCodeSection {
continue
}
if !wroteHeader {
writeOutput(headerStart)
writeOutput("\n\n")
writeOutput(tocHeader)
writeOutput("\n\n")
wroteHeader = true
}
writeHeader(writeOutput, level, header, headersCount)
}
if scanner.Err() != nil {
return scanner.Err()
}
if wroteHeader {
writeOutput("\n")
writeOutput(headerEnd)
writeOutput("\n\n")
}
writeOutput(original.String())
return writeErr
}
func GenerateFromFile(inputpath string, output io.Writer) error {
file, err := os.Open(inputpath)
if err != nil {
return fmt.Errorf("GenerateFromFile: error opening file: %s", err)
}
defer file.Close()
return Generate(file, output)
}
func GenerateInPlace(inputpath string) error {
var output bytes.Buffer
err := GenerateFromFile(inputpath, &output)
if err != nil {
return err
}
file, err := os.Create(inputpath)
if err != nil {
// TODO: That is why we need a backup file for the original one :-)
return fmt.Errorf("GenerateInPlace: unable to truncate file: %s", err)
}
defer file.Close()
expectedwrite := int64(output.Len())
written, err := io.Copy(file, &output)
if err != nil {
// TODO: That is why we need a backup file for the original one :-)
return fmt.Errorf("GenerateInPlace: unable to copy contents: %s", err)
}
if written != expectedwrite {
// TODO: That is why we need a backup file for the original one :-)
return fmt.Errorf(
"GenerateInPlace: unable to copy contents: wrote %d expected %d",
written,
expectedwrite,
)
}
return nil
}