-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmarkdown_test.go
More file actions
264 lines (242 loc) · 8.63 KB
/
Copy pathmarkdown_test.go
File metadata and controls
264 lines (242 loc) · 8.63 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
package cli
import (
"os"
"path/filepath"
"regexp"
"slices"
"strings"
"testing"
)
type docConfig struct {
Debug bool `cli:"name=debug aliases=d desc='turn on debugging'"`
Name string `cli:"name=n aliases=name desc='who to greet' default=sam"`
}
// docCmd builds a small tree: a root with two children, one of which has a
// child of its own and suppresses an inherited option.
func docCmd(t *testing.T) *Command {
t.Helper()
rootOpts, err := StructOpts(&docConfig{})
if err != nil {
t.Fatal(err)
}
return NewCommand("root").
WithSynopsis("root do things").
WithDescription("root is the root command").
WithOpts(rootOpts...).
WithSubs(
NewCommand("a").
WithSynopsis("a the a command").
WithOpts(&Opt{Name: "count", Type: Int, Description: "how many"}),
NewCommand("b").
WithAliases("bb").
WithSuppressedOpts("debug").
WithSubs(NewCommand("deep").WithSynopsis("deep a nested command")),
)
}
func docFiles(t *testing.T, cmd *Command) (string, map[string]string) {
t.Helper()
dir := t.TempDir()
if err := cmd.MarkdownDocs(dir); err != nil {
t.Fatal(err)
}
ents, err := os.ReadDir(dir)
if err != nil {
t.Fatal(err)
}
res := map[string]string{}
for _, ent := range ents {
b, err := os.ReadFile(filepath.Join(dir, ent.Name()))
if err != nil {
t.Fatal(err)
}
res[ent.Name()] = string(b)
}
return dir, res
}
// A command with sub-commands documents the whole tree, one file per command,
// named after the command path, with the root in DocIndex.
func TestMarkdownDocsWritesADirForATree(t *testing.T) {
_, files := docFiles(t, docCmd(t))
want := []string{DocIndex, "root-a.md", "root-b.md", "root-b-deep.md"}
for _, name := range want {
if _, ok := files[name]; !ok {
t.Errorf("missing %s, got %v", name, sortedKeys(files))
}
}
if len(files) != len(want) {
t.Errorf("wrote %v, want exactly %v", sortedKeys(files), want)
}
}
// A command with no sub-commands is a single page, and the path given is the
// file itself rather than a directory holding it.
func TestMarkdownDocsWritesAFileForASingleCommand(t *testing.T) {
path := filepath.Join(t.TempDir(), "sub", "solo.md")
cmd := NewCommand("solo").
WithSynopsis("solo all alone").
WithOpts(&Opt{Name: "v", Type: Bool, Description: "verbose"})
if err := cmd.MarkdownDocs(path); err != nil {
t.Fatal(err)
}
b, err := os.ReadFile(path)
if err != nil {
t.Fatalf("MarkdownDocs wrote no file at %s: %v", path, err)
}
doc := string(b)
for _, want := range []string{"# solo", "all alone", "`-v`", "solo [options] [arguments]"} {
if !strings.Contains(doc, want) {
t.Errorf("doc for solo does not contain %q:\n%s", want, doc)
}
}
if strings.Contains(doc, "## Commands") {
t.Errorf("doc for a childless command has a Commands section:\n%s", doc)
}
}
// Every link written into the directory has to land on a file in it: the root
// is linked as DocIndex and not as "root.md", and nested names must agree
// between the page that links them and the file that is written.
func TestMarkdownDocDirLinksResolve(t *testing.T) {
dir, files := docFiles(t, docCmd(t))
link := regexp.MustCompile(`\]\(([^)]+)\)`)
n := 0
for name, doc := range files {
for _, m := range link.FindAllStringSubmatch(doc, -1) {
n++
if _, err := os.Stat(filepath.Join(dir, m[1])); err != nil {
t.Errorf("%s links to %q, which was not written", name, m[1])
}
}
}
if n == 0 {
t.Error("no links at all between the pages of a command tree")
}
}
// The options a command takes come from its whole path, and the page has to
// say which are its own and which come from above it.
func TestMarkdownDocSeparatesOwnFromInheritedOptions(t *testing.T) {
_, files := docFiles(t, docCmd(t))
doc := files["root-a.md"]
own := strings.Index(doc, "### `root a` options")
inherited := strings.Index(doc, "### inherited from `root`")
if own < 0 || inherited < 0 {
t.Fatalf("root a is missing an options section:\n%s", doc)
}
if !strings.Contains(doc[own:], "`-count`") {
t.Errorf("-count is not among root a's own options:\n%s", doc)
}
if !strings.Contains(doc[inherited:own], "`-debug`, `-d`") {
t.Errorf("-debug is not documented as inherited from root:\n%s", doc)
}
if !strings.Contains(doc, "| `sam` |") {
t.Errorf("the default of -n is missing:\n%s", doc)
}
}
// An option suppressed with WithSuppressedOpts cannot be given to the command
// or to anything below it, so it must not be documented there either.
func TestMarkdownDocOmitsSuppressedOptions(t *testing.T) {
_, files := docFiles(t, docCmd(t))
for _, name := range []string{"root-b.md", "root-b-deep.md"} {
if strings.Contains(files[name], "-debug") {
t.Errorf("%s documents -debug, which b suppresses:\n%s", name, files[name])
}
}
if !strings.Contains(files["root-a.md"], "-debug") {
t.Error("root a no longer documents -debug, which only b suppresses")
}
}
// Descriptions are written by the caller and land in table cells, where an
// unescaped pipe would silently split the row into the wrong columns.
func TestMarkdownDocEscapesTableCells(t *testing.T) {
cmd := NewCommand("pipes").
WithOpts(&Opt{Name: "f", Type: String, Description: "a|b, one or the other"})
b := &strings.Builder{}
if err := cmd.MarkdownDoc(b); err != nil {
t.Fatal(err)
}
if !strings.Contains(b.String(), `a\|b`) {
t.Errorf("the pipe in a description was not escaped:\n%s", b)
}
}
// The synopsis convention of Command.Usage repeats the command name; a
// heading followed by the name again reads badly, so it is dropped.
func TestMarkdownDocDropsTheNameRepeatedInTheSynopsis(t *testing.T) {
b := &strings.Builder{}
cmd := NewCommand("only").WithSynopsis("only does one thing")
if err := cmd.MarkdownDoc(b); err != nil {
t.Fatal(err)
}
if !strings.Contains(b.String(), "\ndoes one thing\n") {
t.Errorf("synopsis still repeats the command name:\n%s", b)
}
}
// A synopsis is written either as prose or as the invocation it names,
// and both begin with the command name. Stripping the name off an
// invocation and printing what is left as prose leaves a fragment: an
// "o [opts] command [opts]" became a line reading "[opts] command
// [opts]" under the title. An invocation belongs in the usage block,
// where it says more than the one this package would otherwise generate.
func TestMarkdownDocUsesASynopsisWrittenAsAnInvocation(t *testing.T) {
for _, test := range []struct {
synopsis string
want string
}{
{"o [opts] command [opts]", "o [opts] command [opts]"},
{"o <command> [-flags]", "o <command> [-flags]"},
{"o SRC DST", "o SRC DST"},
{"o -x thing", "o -x thing"},
} {
b := &strings.Builder{}
cmd := NewCommand("o").WithSynopsis(test.synopsis)
if err := cmd.MarkdownDoc(b); err != nil {
t.Fatal(err)
}
doc := b.String()
if !strings.Contains(doc, "## Usage\n\n```\n"+test.want+"\n```") {
t.Errorf("synopsis %q is not the usage line:\n%s", test.synopsis, doc)
}
if strings.Contains(doc, "\n"+strings.TrimPrefix(test.want, "o ")+"\n\n##") {
t.Errorf("synopsis %q left a fragment under the title:\n%s", test.synopsis, doc)
}
}
}
// Prose is still prose: the name it repeats comes off and it reads as
// the sentence it is, rather than being mistaken for an invocation.
func TestMarkdownDocKeepsAProseSynopsisProse(t *testing.T) {
for _, test := range []struct{ synopsis, want string }{
{"o read and write tony", "read and write tony"},
{"o A tool for reading tony", "A tool for reading tony"},
{"read and write tony", "read and write tony"},
} {
b := &strings.Builder{}
cmd := NewCommand("o").WithSynopsis(test.synopsis)
if err := cmd.MarkdownDoc(b); err != nil {
t.Fatal(err)
}
doc := b.String()
if !strings.Contains(doc, "# o\n\n"+test.want+"\n") {
t.Errorf("synopsis %q does not read as prose:\n%s", test.synopsis, doc)
}
if !strings.Contains(doc, "o [options] [arguments]") {
t.Errorf("synopsis %q displaced the generated usage line:\n%s", test.synopsis, doc)
}
}
}
// An invocation names the whole command line, so a sub-command's is
// written out from the root rather than from its own name.
func TestMarkdownDocInvocationSpellsTheWholePath(t *testing.T) {
root := NewCommand("o").WithSubs(NewCommand("parse").WithSynopsis("parse [-s schema] FILE"))
_, files := docFiles(t, root)
if !strings.Contains(files["o-parse.md"], "```\no parse [-s schema] FILE\n```") {
t.Errorf("the invocation of o parse is not written from the root:\n%s", files["o-parse.md"])
}
if !strings.Contains(files[DocIndex], "| `o parse [-s schema] FILE` |") {
t.Errorf("the commands table does not show the invocation:\n%s", files[DocIndex])
}
}
func sortedKeys(m map[string]string) []string {
res := make([]string, 0, len(m))
for k := range m {
res = append(res, k)
}
slices.Sort(res)
return res
}