Repository navigation
Expand file tree
/
Copy pathmarkdown.go
More file actions
488 lines (446 loc) · 13.7 KB
/
Copy pathmarkdown.go
File metadata and controls
488 lines (446 loc) · 13.7 KB
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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
package cli
import (
"errors"
"fmt"
"io"
"maps"
"os"
"path/filepath"
"slices"
"strings"
"unicode"
)
// DocIndex is the name of the file holding the documentation of the
// command at the root of a tree written by [Doc.Write].
const DocIndex = "README.md"
// A Doc generates markdown documentation for the command tree rooted at
// Cmd. The zero value of every field but Cmd generates self contained
// markdown; the others add links to documentation published elsewhere.
//
// Nothing here is visible to [Command.Usage]: the synopses and
// descriptions of the commands themselves stay plain text, and only the
// copy which lands in markdown is decorated.
type Doc struct {
Cmd *Command
// Site is the base URL of documentation published on the web.
// When it is set, the page of each command links to the page for
// that command on the site, and any relative URL in Terms is
// taken as a path under Site.
Site string
// Page maps a command to the path of its page under Site. A nil
// Page means [DefaultPage]; a Page returning "" means that the
// command has no page on the site.
Page func(*Command) string
// Terms maps plain text terms to the URLs documenting them, as in
//
// cli.Terms{"schema": "/schema/"}
//
// The first occurrence of each term in each synopsis and
// description on a page becomes a markdown link. See [Terms] for
// what counts as an occurrence.
Terms Terms
// Linkify, if non-nil, is applied to each synopsis and
// description before Terms is, and may return markdown. It is
// the escape hatch for links which Terms cannot express; the
// links it writes are left alone by Terms.
Linkify func(string) string
}
// Terms maps plain text terms to the URLs which document them.
//
// A term is linked where it occurs as a whole word: the characters
// around it may not be letters, digits, '-' or '_', so that "tony" does
// not match within "tony-format". Matching is case sensitive, the
// longest matching term wins, and only the first occurrence of a term in
// any one synopsis or description is linked, so that a term repeated in
// a sentence does not become a row of links. Occurrences inside
// backticks or inside a link which is already there are left alone.
//
// Where [Doc.Site] is set, a URL which has no scheme is a path under it:
// with a Site of "https://example.com/docs/", the term URL "/schema/"
// and the term URL "schema/" both link to
// "https://example.com/docs/schema/".
type Terms map[string]string
// NewDoc returns a [Doc] generating plain markdown for the tree rooted
// at cmd.
func NewDoc(cmd *Command) *Doc {
return &Doc{Cmd: cmd}
}
// WithSite sets [Doc.Site].
func (d *Doc) WithSite(url string) *Doc {
d.Site = url
return d
}
// WithPage sets [Doc.Page].
func (d *Doc) WithPage(f func(*Command) string) *Doc {
d.Page = f
return d
}
// WithTerms merges ts into [Doc.Terms].
func (d *Doc) WithTerms(ts Terms) *Doc {
if d.Terms == nil {
d.Terms = Terms{}
}
maps.Copy(d.Terms, ts)
return d
}
// WithTerm adds a single term to [Doc.Terms].
func (d *Doc) WithTerm(text, url string) *Doc {
return d.WithTerms(Terms{text: url})
}
// WithLinkify sets [Doc.Linkify].
func (d *Doc) WithLinkify(f func(string) string) *Doc {
d.Linkify = f
return d
}
// DefaultPage maps a command to the path of its page under [Doc.Site]:
// its command path joined with "/", so that the command "o parse" has
// the page "o/parse/".
func DefaultPage(cmd *Command) string {
return strings.Join(strings.Fields(cmd.fullName()), "/") + "/"
}
// Write writes the documentation of d at path.
//
// If [Doc.Cmd] has sub-commands, path names a directory of markdown
// files, one per command in the tree, created if it does not exist.
// [Doc.Cmd] itself is documented in [DocIndex]; every other command is
// documented in a file named after its command path, so that the
// sub-command "b" of the root command "a" lands in "a-b.md". Existing
// files of those names are overwritten.
//
// Otherwise path names a single markdown file, and any missing parent
// directory of it is created.
//
// Options of commands above [Doc.Cmd] are documented as inherited
// options where they apply, but no files are written for them.
func (d *Doc) Write(path string) error {
if len(d.Cmd.Children) != 0 {
return d.writeDir(path)
}
return d.writeFile(d.Cmd, path)
}
// Render writes the page documenting [Doc.Cmd] to w: its synopsis,
// description, invocation, sub-commands, and both its own options and
// those inherited from the commands in its [Command.Path].
//
// Sub-commands are linked as siblings in the same directory, using the
// file names of [Doc.Write]; a page rendered on its own for a command
// with sub-commands therefore has links which only resolve alongside
// such a directory.
func (d *Doc) Render(w io.Writer) error {
return d.render(d.Cmd, w)
}
func (d *Doc) writeDir(dir string) error {
if err := os.MkdirAll(dir, 0o755); err != nil {
return err
}
var errs []error
d.Cmd.walk(func(c *Command) {
errs = append(errs, d.writeFile(c, filepath.Join(dir, d.file(c))))
})
return errors.Join(errs...)
}
func (d *Doc) writeFile(cmd *Command, path string) error {
if dir := filepath.Dir(path); dir != "" {
if err := os.MkdirAll(dir, 0o755); err != nil {
return err
}
}
f, err := os.Create(path)
if err != nil {
return err
}
if err := d.render(cmd, f); err != nil {
f.Close()
return err
}
return f.Close()
}
func (d *Doc) render(cmd *Command, w io.Writer) error {
b := &strings.Builder{}
fmt.Fprintf(b, "# %s\n\n", cmd.fullName())
if s := cmd.shortSynopsis(); s != "" {
fmt.Fprintf(b, "%s\n\n", d.link(s))
}
if cmd.Description != "" {
fmt.Fprintf(b, "%s\n\n", d.link(strings.TrimSpace(cmd.Description)))
}
if len(cmd.Aliases) != 0 {
als := make([]string, 0, len(cmd.Aliases))
for _, al := range cmd.Aliases {
als = append(als, "`"+al+"`")
}
fmt.Fprintf(b, "Also known as %s.\n\n", strings.Join(als, ", "))
}
d.usage(b, cmd)
d.subs(b, cmd)
d.opts(b, cmd)
d.seeAlso(b, cmd)
_, err := io.WriteString(w, b.String())
return err
}
func (d *Doc) usage(b *strings.Builder, cmd *Command) {
line, ok := cmd.usageLine()
switch {
case ok:
case len(cmd.Children) != 0:
line = cmd.fullName() + " [options] <command> [arguments]"
default:
line = cmd.fullName() + " [options] [arguments]"
}
fmt.Fprintf(b, "## Usage\n\n```\n%s\n```\n\n", line)
}
func (d *Doc) subs(b *strings.Builder, cmd *Command) {
if len(cmd.Children) == 0 {
return
}
fmt.Fprintf(b, "## Commands\n\n")
fmt.Fprintf(b, "| command | synopsis |\n| --- | --- |\n")
for _, sub := range cmd.Children {
syn := d.link(mdCell(sub.shortSynopsis()))
if line, ok := sub.usageLine(); ok {
syn = "`" + mdCell(line) + "`"
}
fmt.Fprintf(b, "| [`%s`](%s) | %s |\n", mdCell(sub.Name), d.file(sub), syn)
}
fmt.Fprintln(b)
}
func (d *Doc) opts(b *strings.Builder, cmd *Command) {
// AllOpts accounts for the options suppressed with
// [Command.WithSuppressedOpts] anywhere along the path.
avail := map[*Opt]bool{}
for _, o := range cmd.AllOpts() {
avail[o] = true
}
type section struct {
cmd *Command
opts []*Opt
}
var secs []section
bools := false
for _, c := range cmd.Path() {
var opts []*Opt
for _, o := range c.Opts {
if !avail[o] {
continue
}
opts = append(opts, o)
bools = bools || o.Type == Bool
}
if len(opts) != 0 {
secs = append(secs, section{cmd: c, opts: opts})
}
}
fmt.Fprintf(b, "## Options\n\n")
if len(secs) == 0 {
fmt.Fprintf(b, "`%s` takes no options.\n\n", cmd.fullName())
return
}
for _, sec := range secs {
if sec.cmd == cmd {
fmt.Fprintf(b, "### `%s` options\n\n", cmd.fullName())
} else {
fmt.Fprintf(b, "### inherited from `%s`\n\n", sec.cmd.fullName())
}
fmt.Fprintf(b, "| option | type | default | description |\n| --- | --- | --- | --- |\n")
for _, o := range sec.opts {
fmt.Fprintf(b, "| %s | %s | %s | %s |\n",
mdFlags(o), mdCell(o.Type.String()), mdDefault(o), d.link(mdCell(o.Description)))
}
fmt.Fprintln(b)
}
if len(secs) > 1 || secs[0].cmd != cmd {
fmt.Fprintf(b, "Inherited options may be given either before or after the "+
"command they are inherited by.\n\n")
}
if bools {
fmt.Fprintf(b, "Boolean options take no argument and may be negated with a "+
"`no-` prefix, as in `-no-debug`.\n\n")
}
}
func (d *Doc) seeAlso(b *strings.Builder, cmd *Command) {
var lines []string
if u := d.pageURL(cmd); u != "" {
lines = append(lines, fmt.Sprintf("- [published documentation](%s)", u))
}
if cmd != d.Cmd && cmd.Parent != nil {
lines = append(lines, fmt.Sprintf("- [`%s`](%s)",
cmd.Parent.fullName(), d.file(cmd.Parent)))
for _, sib := range cmd.Parent.Children {
if sib == cmd {
continue
}
lines = append(lines, fmt.Sprintf("- [`%s`](%s)", sib.fullName(), d.file(sib)))
}
}
if len(lines) == 0 {
return
}
fmt.Fprintf(b, "## See also\n\n%s\n\n", strings.Join(lines, "\n"))
}
// pageURL is the URL documenting cmd on [Doc.Site], or "" if there is none.
func (d *Doc) pageURL(cmd *Command) string {
if d.Site == "" {
return ""
}
page := DefaultPage
if d.Page != nil {
page = d.Page
}
p := page(cmd)
if p == "" {
return ""
}
return d.url(p)
}
// file is the markdown file, relative to the directory written by
// [Doc.Write], documenting cmd.
func (d *Doc) file(cmd *Command) string {
if cmd == d.Cmd {
return DocIndex
}
return docFileName(cmd)
}
// MarkdownDocs writes markdown documentation for cmd at path, as
// [Doc.Write] does for a [Doc] with no links.
func (cmd *Command) MarkdownDocs(path string) error {
return NewDoc(cmd).Write(path)
}
// MarkdownDocDir writes one markdown file per command in the tree rooted
// at cmd into dir, as [Doc.Write] does for a [Doc] with no links and a
// command with sub-commands.
func (cmd *Command) MarkdownDocDir(dir string) error {
return NewDoc(cmd).writeDir(dir)
}
// MarkdownDocFile writes the page documenting cmd to the file at path,
// creating any missing parent directories and overwriting any existing
// file.
func (cmd *Command) MarkdownDocFile(path string) error {
return NewDoc(cmd).writeFile(cmd, path)
}
// MarkdownDoc writes the page documenting cmd to w, as [Doc.Render] does
// for a [Doc] with no links.
func (cmd *Command) MarkdownDoc(w io.Writer) error {
return NewDoc(cmd).Render(w)
}
// walk calls f on cmd and, depth first, on each of its descendants.
func (cmd *Command) walk(f func(*Command)) {
f(cmd)
for _, sub := range cmd.Children {
sub.walk(f)
}
}
// fullName is the command line by which cmd is invoked, such as "git remote add".
func (cmd *Command) fullName() string {
path := cmd.Path()
names := make([]string, 0, len(path))
for _, c := range path {
names = append(names, c.Name)
}
return strings.Join(names, " ")
}
// shortSynopsis is cmd.Synopsis read as the prose it usually is, without
// the leading command name which, by the convention of [Command.Usage],
// it repeats. A synopsis which is an invocation rather than prose has
// no prose in it, and is left to [Command.usageLine].
func (cmd *Command) shortSynopsis() string {
if _, ok := cmd.usageLine(); ok {
return ""
}
s := strings.TrimSpace(cmd.Synopsis)
first, rest, ok := strings.Cut(s, " ")
if !ok {
return s
}
if cmd.named(first) {
return strings.TrimSpace(rest)
}
return s
}
// usageLine is cmd.Synopsis read as an invocation, as in
// "o [opts] command [opts]" or "cp SRC DST", with the leading command
// name it repeats replaced by the whole command path.
//
// Both kinds of synopsis begin with the command name, so which one an
// author wrote is told by what follows it: the punctuation of a
// placeholder or an option, or a placeholder shouted in upper case.
// Only prose reads as prose, and stripping the name off an invocation to
// print it as prose leaves a fragment.
func (cmd *Command) usageLine() (string, bool) {
first, rest, ok := strings.Cut(strings.TrimSpace(cmd.Synopsis), " ")
if !ok || !cmd.named(first) {
return "", false
}
rest = strings.TrimSpace(rest)
if !isInvocation(rest) {
return "", false
}
return cmd.fullName() + " " + rest, true
}
// named reports whether s is a name cmd answers to.
func (cmd *Command) named(s string) bool {
return s == cmd.Name || slices.Contains(cmd.Aliases, s)
}
// isInvocation reports whether s is what follows the command name in a
// synopsis written as an invocation.
func isInvocation(s string) bool {
if s == "" {
return false
}
switch s[0] {
case '[', '<', '{', '(', '-', '|':
return true
}
tok, _, _ := strings.Cut(s, " ")
return isShout(tok)
}
// isShout reports whether s is a placeholder in upper case, as the SRC
// of "cp SRC DST". A single letter is not one: it is the "A" of
// "a A tool for things".
func isShout(s string) bool {
upper := 0
for _, r := range s {
switch {
case unicode.IsUpper(r):
upper++
case unicode.IsLower(r):
return false
}
}
return upper > 1
}
func docFileName(cmd *Command) string {
return docFileEsc(strings.Join(strings.Fields(cmd.fullName()), "-")) + ".md"
}
// docFileEsc replaces anything outside of a conservative portable file
// name with '_', so that command names needn't be file names.
func docFileEsc(s string) string {
return strings.Map(func(r rune) rune {
switch {
case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9':
return r
case r == '-', r == '_', r == '.':
return r
default:
return '_'
}
}, s)
}
func mdFlags(o *Opt) string {
names := make([]string, 0, len(o.Aliases)+1)
for _, n := range append([]string{o.Name}, o.Aliases...) {
names = append(names, "`-"+mdCell(n)+"`")
}
return strings.Join(names, ", ")
}
func mdDefault(o *Opt) string {
if o.Default == nil {
return ""
}
return "`" + mdCell(fmt.Sprintf("%v", *o.Default)) + "`"
}
// mdCell makes s safe to place in a cell of a markdown table.
func mdCell(s string) string {
s = strings.ReplaceAll(s, "|", "\\|")
s = strings.ReplaceAll(s, "\n", " ")
return strings.TrimSpace(s)
}