-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
182 lines (152 loc) · 4.54 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
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
package main
import (
"bytes"
"errors"
"flag"
"fmt"
"io"
"net/url"
"os"
"strings"
"github.com/apocelipes/autotoc/internal/utils"
"github.com/apocelipes/autotoc/pkg/format"
"github.com/apocelipes/autotoc/pkg/parser"
)
func checkError(err error) {
if err != nil {
_, _ = fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
func main() {
topTag := utils.StringFlagWithShortName("top-tag",
"t",
topTagDefault,
topTagUsage)
formatter := utils.StringFlagWithShortName("formatter",
"f",
formatterDefault,
formatterUsage)
catalogID := flag.String("catalog-id",
catalogIDDefault,
catalogIDUsage)
catalogTitle := flag.String("title",
catalogTitleDefault,
catalogTitleUsage)
catalogOutputType := utils.StringFlagWithShortName("output",
"o",
catalogOutputTypeDefault,
catalogOutputTypeUsage)
catalogScanType := utils.StringFlagWithShortName("title-language",
"l",
catalogScanTypeDefault,
catalogScanTypeUsage)
catalogIndent := utils.StringFlagWithShortName("indent",
"i",
catalogIndentDefault,
catalogIndentUsage)
writeBack := flag.Bool("w", false, writeBackUsage)
tocMark := utils.StringFlagWithShortName("toc-mark",
"m",
tocMarkDefault,
tocMarkUsage)
excludeTitle := flag.String("exclude-title",
excludeTitleDefault,
excludeTitleUsage)
excludeFilter := flag.String("exclude-filter",
"",
excludeFilterUsage)
noExclude := flag.Bool("no-exclude", false, noExcludeUsage)
fullOutput := flag.Bool("full", false, fullOutputUsage)
noEncode := flag.Bool("no-encode", false, noEncodeUsage)
flag.Parse()
if *writeBack && *fullOutput {
checkError(errors.New("--full 不能和选项 -w 一起使用"))
}
var f *os.File
if len(flag.Args()) == 0 {
// 未提供文件名参数时判断是否处于pipe中,是则stdin为输入文件,不可能为terminal
if utils.IsStdinTerminal() {
_, _ = os.Stderr.WriteString("错误:需要一个输入文件")
flag.Usage()
}
if *writeBack {
checkError(errors.New("-w 不能在输入为 stdin 时使用"))
}
f = os.Stdin
} else {
openFlag := os.O_RDONLY
if *writeBack {
openFlag = os.O_RDWR
}
var err error
f, err = os.OpenFile(flag.Arg(0), openFlag, 0)
checkError(err)
defer f.Close()
}
// 终端可能无法直接输入tab,所以用\t代替
if *catalogIndent == "\\t" {
*catalogIndent = "\t"
}
options := []parser.Option{
parser.WithTopTag(*topTag),
parser.WithScanType(*catalogScanType),
parser.WithTOCMark(*tocMark),
}
if !*noExclude {
titleFilter := &parser.DefaultFilter{}
titleFilter.SetExcludeTitles(*excludeTitle)
checkError(titleFilter.SetExcludeRegExp(*excludeFilter))
options = append(options, parser.WithFilter(titleFilter))
}
if !*noEncode {
options = append(options, parser.WithURLEncoder(url.PathEscape))
}
fileContent, err := io.ReadAll(f)
checkError(err)
mdParser := parser.GetParser(options...)
ret := mdParser.Parse(bytes.NewReader(fileContent))
if len(ret) == 0 {
// not an error
_, _ = os.Stdout.WriteString("未找到任何标题")
return
}
var catalogContent string
switch *catalogOutputType {
case "html":
catalogContent = renderHTMLTitles(*catalogID, *catalogTitle, *catalogIndent, *formatter, ret)
case "md":
catalogContent = renderMarkdownTitles(*catalogTitle, *catalogIndent, ret)
default:
checkError(fmt.Errorf("不支持的格式化类型: %v", *catalogOutputType))
}
if *writeBack {
checkError(utils.WriteCatalog(fileContent, catalogContent, *tocMark, false, f.Name()))
return
} else if *fullOutput {
checkError(utils.WriteCatalog(fileContent, catalogContent, *tocMark, true, f.Name()))
return
}
fmt.Println(catalogContent)
}
func renderHTMLTitles(catalogID, catalogTitle, catalogIndent, formatter string, titles []*parser.TitleNode) string {
html := strings.Builder{}
for _, v := range titles {
html.WriteString(v.HTML())
}
data := format.RenderCatalog(catalogID, catalogTitle, html.String())
formatHTMLFunc := format.NewFormatter(formatter)
if formatHTMLFunc == nil {
checkError(fmt.Errorf("unsupported HTML formatter: %v", formatter))
}
return formatHTMLFunc(data, catalogIndent)
}
func renderMarkdownTitles(catalogTitle, catalogIndent string, titles []*parser.TitleNode) string {
md := strings.Builder{}
md.WriteString("#### " + catalogTitle + "\n\n")
for _, v := range titles {
// each parent has no indent
md.WriteString(v.Markdown(catalogIndent, 0))
}
return md.String()
}