This repository was archived by the owner on Jun 28, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 195
/
Copy pathmain.go
348 lines (280 loc) · 7.06 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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
//
// Copyright (c) 2019 Intel Corporation
//
// SPDX-License-Identifier: Apache-2.0
//
package main
import (
"errors"
"fmt"
"os"
"time"
"github.com/sirupsen/logrus"
"github.com/urfave/cli"
)
type DataToShow int
const (
// Character used (after an optional filename) before a heading ID.
anchorPrefix = "#"
// Character used to signify an "absolute link path" which should
// expand to the value of the document root.
absoluteLinkPrefix = "/"
showLinks DataToShow = iota
showHeadings DataToShow = iota
textFormat = "text"
tsvFormat = "tsv"
defaultOutputFormat = textFormat
defaultSeparator = "\t"
)
var (
// set by the build
name = ""
version = ""
commit = ""
strict = false
// list entry character to use when generating TOCs
listPrefix = "*"
logger *logrus.Entry
errNeedFile = errors.New("need markdown file")
)
// Black Friday sometimes chokes on markdown (I know!!), so record how many
// extra headings we found.
var extraHeadings int
// Root directory used to handle "absolute link paths" that start with a slash
// to denote the "top directory", like this:
//
// [Foo](/absolute-link.md)
var docRoot string
var notes = fmt.Sprintf(`
NOTES:
- The document root is used to handle markdown references that begin with %q,
denoting that the path that follows is an "absolute path" from the specified
document root path.
- The order the document nodes are parsed internally is not known to
this program. This means that if multiple errors exist in the document,
running this tool multiple times will error one *one* of the errors, but not
necessarily the same one as last time.
LIMITATIONS:
- The default document root only works if this tool is run from the top-level
of a repository.
`, absoluteLinkPrefix)
var formatFlag = cli.StringFlag{
Name: "format",
Usage: "display in specified format ('help' to show all)",
Value: defaultOutputFormat,
}
var separatorFlag = cli.StringFlag{
Name: "separator",
Usage: fmt.Sprintf("use the specified separator character (%s format only)", tsvFormat),
Value: defaultSeparator,
}
var noHeaderFlag = cli.BoolFlag{
Name: "no-header",
Usage: "disable display of header (if format supports one)",
}
func init() {
logger = logrus.WithFields(logrus.Fields{
"name": name,
"source": "check-markdown",
"version": version,
"commit": commit,
"pid": os.Getpid(),
})
logger.Logger.Formatter = &logrus.TextFormatter{
TimestampFormat: time.RFC3339Nano,
//DisableColors: true,
}
// Write to stdout to avoid upsetting CI systems that consider stderr
// writes as indicating an error.
logger.Logger.Out = os.Stdout
}
func handleLogging(c *cli.Context) {
logLevel := logrus.InfoLevel
if c.GlobalBool("debug") {
logLevel = logrus.DebugLevel
}
logger.Logger.SetLevel(logLevel)
}
func handleDoc(c *cli.Context, createTOC bool) error {
handleLogging(c)
if c.NArg() == 0 {
return errNeedFile
}
fileName := c.Args().First()
if fileName == "" {
return errNeedFile
}
singleDocOnly := c.GlobalBool("single-doc-only")
doc := newDoc(fileName, logger)
doc.ShowTOC = createTOC
if createTOC {
// Only makes sense to generate a single TOC!
singleDocOnly = true
}
// Parse the main document first
err := doc.parse()
if err != nil {
return err
}
if singleDocOnly && len(docs) > 1 {
doc.Logger.Debug("Not checking referenced files at user request")
return nil
}
// Now handle all other docs that the main doc references.
// This requires care to avoid recursion.
for {
count := len(docs)
parsed := 0
for _, doc := range docs {
if doc.Parsed {
// Document has already been handled
parsed++
continue
}
if err := doc.parse(); err != nil {
return err
}
}
if parsed == count {
break
}
}
err = handleIntraDocLinks()
if err != nil {
return err
}
if !createTOC {
doc.Logger.Info("Checked file")
doc.showStats()
}
count := len(docs)
if count > 1 {
// Update to ignore main document
count--
doc.Logger.WithField("reference-document-count", count).Info("Checked referenced files")
for _, d := range docs {
if d.Name == doc.Name {
// Ignore main document
continue
}
fmt.Printf("\t%q\n", d.Name)
}
}
// Highlight blackfriday deficiencies
if !doc.ShowTOC && extraHeadings > 0 {
doc.Logger.WithField("extra-heading-count", extraHeadings).Debug("Found extra headings")
}
return nil
}
// commonListHandler is used to handle all list operations.
func commonListHandler(context *cli.Context, what DataToShow) error {
handleLogging(context)
handlers := NewDisplayHandlers(context.String("separator"), context.Bool("no-header"))
format := context.String("format")
if format == "help" {
availableFormats := handlers.Get()
for _, format := range availableFormats {
fmt.Fprintf(outputFile, "%s\n", format)
}
return nil
}
handler := handlers.find(format)
if handler == nil {
return fmt.Errorf("no handler for format %q", format)
}
if context.NArg() == 0 {
return errNeedFile
}
file := context.Args().Get(0)
return show(file, logger, handler, what)
}
func realMain() error {
cwd, err := os.Getwd()
if err != nil {
return err
}
docRoot = cwd
cli.VersionPrinter = func(c *cli.Context) {
fmt.Fprintln(os.Stdout, c.App.Version)
}
cli.AppHelpTemplate = fmt.Sprintf(`%s%s`, cli.AppHelpTemplate, notes)
app := cli.NewApp()
app.Name = name
app.Version = fmt.Sprintf("%s %s (commit %v)", name, version, commit)
app.Description = "Tool to check GitHub-Flavoured Markdown (GFM) format documents"
app.Usage = app.Description
app.UsageText = fmt.Sprintf("%s [options] file ...", app.Name)
app.Flags = []cli.Flag{
cli.BoolFlag{
Name: "debug, d",
Usage: "display debug information",
},
cli.StringFlag{
Name: "doc-root, r",
Usage: "specify document root",
Value: docRoot,
},
cli.BoolFlag{
Name: "single-doc-only, o",
Usage: "only check primary (specified) document",
},
cli.BoolFlag{
Name: "strict, s",
Usage: "enable strict mode",
},
}
app.Commands = []cli.Command{
{
Name: "check",
Usage: "perform tests on the specified document",
Description: "Exit code denotes success",
Action: func(c *cli.Context) error {
return handleDoc(c, false)
},
},
{
Name: "toc",
Usage: "display a markdown Table of Contents",
Action: func(c *cli.Context) error {
return handleDoc(c, true)
},
},
{
Name: "list",
Usage: "display particular parts of the document",
Subcommands: []cli.Command{
{
Name: "headings",
Usage: "display headings",
Flags: []cli.Flag{
formatFlag,
noHeaderFlag,
separatorFlag,
},
Action: func(c *cli.Context) error {
return commonListHandler(c, showHeadings)
},
},
{
Name: "links",
Usage: "display links",
Flags: []cli.Flag{
formatFlag,
noHeaderFlag,
separatorFlag,
},
Action: func(c *cli.Context) error {
return commonListHandler(c, showLinks)
},
},
},
},
}
return app.Run(os.Args)
}
func main() {
err := realMain()
if err != nil {
logger.Fatalf("%v", err)
}
}