Skip to content

Commit f7f345b

Browse files
committed
feat/doc: add 'src doc -yaml' for a structured command reference
The new Sourcegraph docs site needs the CLI reference as data, so that it can lay out the pages as it wants. 'src doc -yaml -o FILE' writes one YAML document per command, in the format of Cobra's doc.GenYaml. The new Cobra-based src CLI can write the same file with doc.GenYaml.
1 parent 77ed79e commit f7f345b

3 files changed

Lines changed: 241 additions & 38 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@ All notable changes to `src-cli` are documented in this file.
1313

1414
### Added
1515

16+
- `src doc -yaml -o FILE` writes the command reference as YAML, in the format of Cobra's `doc.GenYaml`.
17+
1618
- `src` now prints a warning to stderr when it is older than the version recommended by your Sourcegraph instance. The recommended version is looked up at most once every 24 hours per instance. To disable the check, set the `SRC_SKIP_VERSION_CHECK` environment variable to any non-blank string. [#930](https://github.com/sourcegraph/src-cli/issues/930)
1719

1820
### Changed

‎cmd/src/doc.go‎

Lines changed: 197 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,20 @@ package main
22

33
import (
44
"bytes"
5+
"cmp"
56
"flag"
67
"fmt"
78
"io"
89
"maps"
910
"os"
1011
"path"
12+
"slices"
1113
"strings"
1214
"text/template"
1315

16+
"github.com/urfave/cli/v3"
17+
"gopkg.in/yaml.v3"
18+
1419
"github.com/sourcegraph/sourcegraph/lib/docgen"
1520
"github.com/sourcegraph/sourcegraph/lib/errors"
1621
"github.com/sourcegraph/sourcegraph/lib/output"
@@ -21,7 +26,8 @@ import (
2126
func init() {
2227
flagSet := flag.NewFlagSet("doc", flag.ExitOnError)
2328
var (
24-
outputFlag = flagSet.String("o", "", "Output directory")
29+
outputFlag = flagSet.String("o", "", "Output directory, or output file with -yaml")
30+
yamlFlag = flagSet.Bool("yaml", false, "Write the reference as one YAML file instead of Markdown files")
2531
)
2632

2733
usage := `
@@ -31,10 +37,13 @@ documentation used within Sourcegraph.
3137
Usage:
3238
3339
src doc -o DIR
40+
src doc -yaml -o FILE
3441
3542
Examples:
3643
3744
$ src doc -o ~/sourcegraph/doc/integration/cli/reference
45+
46+
$ src doc -yaml -o ~/sourcegraph/docs/cli/references.yaml
3847
`
3948

4049
handler := func(args []string) error {
@@ -68,6 +77,25 @@ Examples:
6877
"snapshot": &snapshotCommands,
6978
}
7079

80+
if *yamlFlag {
81+
root := &yamlCommand{cmdDoc: cmdDoc{Name: "src"}}
82+
if root.commands, err = legacyYAMLCommands(commanders, ""); err != nil {
83+
return err
84+
}
85+
for _, cmd := range docgen.VisibleCommands(migratedRootCommand().Commands) {
86+
root.commands = append(root.commands, migratedYAMLCommand("src "+cmd.Name, cmd))
87+
}
88+
var buf bytes.Buffer
89+
if err := root.encode(yaml.NewEncoder(&buf), nil); err != nil {
90+
return err
91+
}
92+
content, err := sanitiseDocText(buf.String())
93+
if err != nil {
94+
return err
95+
}
96+
return os.WriteFile(*outputFlag, []byte(content), 0644)
97+
}
98+
7199
rootSubcommands := map[string]string{}
72100
count := 0
73101
for groupName, cmdr := range commanders {
@@ -184,6 +212,125 @@ Examples:
184212
})
185213
}
186214

215+
// cmdDoc and cmdOption are github.com/spf13/cobra/doc's YAML docs, without the
216+
// fields that src has no data for, so that the Cobra-based src CLI can write
217+
// the same reference with doc.GenYaml.
218+
type cmdDoc struct {
219+
Name string
220+
Synopsis string `yaml:",omitempty"`
221+
Description string `yaml:",omitempty"`
222+
Usage string `yaml:",omitempty"`
223+
Options []cmdOption `yaml:",omitempty"`
224+
SeeAlso []string `yaml:"see_also,omitempty"`
225+
}
226+
227+
type cmdOption struct {
228+
Name string
229+
Shorthand string `yaml:",omitempty"`
230+
DefaultValue string `yaml:"default_value,omitempty"`
231+
Usage string `yaml:",omitempty"`
232+
}
233+
234+
// forceMultiLine is copied from cobra/doc: it makes yaml.v3 write long lines as
235+
// block scalars.
236+
func forceMultiLine(s string) string {
237+
if len(s) > 60 && !strings.Contains(s, "\n") {
238+
s += "\n"
239+
}
240+
return s
241+
}
242+
243+
type yamlCommand struct {
244+
cmdDoc
245+
commands []*yamlCommand
246+
}
247+
248+
// encode writes one YAML document for the command and each of its
249+
// subcommands, as cobra/doc.GenYaml does.
250+
func (c *yamlCommand) encode(enc *yaml.Encoder, parent *yamlCommand) error {
251+
slices.SortFunc(c.commands, func(a, b *yamlCommand) int { return cmp.Compare(a.Name, b.Name) })
252+
doc := c.cmdDoc
253+
// c.Synopsis stays one line for the "see also" lists.
254+
doc.Synopsis = forceMultiLine(c.Synopsis)
255+
if parent != nil {
256+
doc.SeeAlso = append(doc.SeeAlso, parent.Name+" - "+parent.Synopsis)
257+
}
258+
for _, sub := range c.commands {
259+
doc.SeeAlso = append(doc.SeeAlso, sub.Name+" - "+sub.Synopsis)
260+
}
261+
if err := enc.Encode(&doc); err != nil {
262+
return err
263+
}
264+
for _, sub := range c.commands {
265+
if err := sub.encode(enc, c); err != nil {
266+
return err
267+
}
268+
}
269+
return nil
270+
}
271+
272+
func legacyYAMLCommands(commanders map[string]*commander, group string) ([]*yamlCommand, error) {
273+
var commands []*yamlCommand
274+
for _, cmd := range *commanders[group] {
275+
if cmd.hidden {
276+
continue
277+
}
278+
fqcn := strings.TrimSpace(group + " " + cmd.flagSet.Name())
279+
280+
// Most usage functions print "Usage of 'src ...':" and the flags
281+
// before the help. Leave both out: the options list the flags.
282+
cmd.flagSet.SetOutput(io.Discard)
283+
usage, err := captureUsage(cmd)
284+
cmd.flagSet.SetOutput(nil)
285+
if err != nil {
286+
return nil, err
287+
}
288+
usage = strings.TrimSpace(usage)
289+
if first, rest, _ := strings.Cut(usage, "\n"); strings.HasPrefix(first, "Usage of ") {
290+
usage = strings.TrimSpace(rest)
291+
}
292+
293+
c := &yamlCommand{cmdDoc: cmdDoc{Name: "src " + fqcn, Synopsis: cmd.description, Description: forceMultiLine(usage)}}
294+
cmd.flagSet.VisitAll(func(f *flag.Flag) {
295+
c.Options = append(c.Options, cmdOption{Name: f.Name, DefaultValue: forceMultiLine(f.DefValue), Usage: forceMultiLine(f.Usage)})
296+
})
297+
if _, ok := commanders[fqcn]; ok {
298+
if c.commands, err = legacyYAMLCommands(commanders, fqcn); err != nil {
299+
return nil, err
300+
}
301+
}
302+
commands = append(commands, c)
303+
}
304+
return commands, nil
305+
}
306+
307+
func migratedYAMLCommand(name string, cmd *cli.Command) *yamlCommand {
308+
c := &yamlCommand{cmdDoc: cmdDoc{
309+
Name: name,
310+
Synopsis: cmd.Usage,
311+
Description: forceMultiLine(strings.TrimSpace(cmd.Description)),
312+
Usage: strings.TrimSpace(cmd.UsageText),
313+
}}
314+
for _, f := range cmd.Flags {
315+
flag, ok := f.(cli.DocGenerationFlag)
316+
if !ok {
317+
continue
318+
}
319+
option := cmdOption{Name: f.Names()[0], DefaultValue: forceMultiLine(flag.GetValue()), Usage: forceMultiLine(flag.GetUsage())}
320+
for _, alias := range f.Names()[1:] {
321+
if len(alias) == 1 {
322+
option.Shorthand = alias
323+
}
324+
}
325+
c.Options = append(c.Options, option)
326+
}
327+
slices.SortFunc(c.Options, func(a, b cmdOption) int { return cmp.Compare(a.Name, b.Name) })
328+
for _, sub := range docgen.VisibleCommands(cmd.Commands) {
329+
c.commands = append(c.commands, migratedYAMLCommand(name+" "+sub.Name, sub))
330+
}
331+
return c
332+
}
333+
187334
func openDocFile(base, fqcn string) (interface {
188335
io.StringWriter
189336
io.WriteCloser
@@ -196,6 +343,34 @@ func openDocFile(base, fqcn string) (interface {
196343
return os.Create(cmdPath + ".md")
197344
}
198345

346+
// sanitiseDocText replaces the user's directories in v, such as in flag
347+
// defaults, with generic ones.
348+
func sanitiseDocText(v string) (string, error) {
349+
// Just replacing the home directory will probably cover off most
350+
// cases, but we'll do the user cache and config as well just to be
351+
// safe.
352+
cache, err := os.UserCacheDir()
353+
if err != nil {
354+
return "", errors.Wrap(err, "getting user cache dir")
355+
}
356+
357+
config, err := os.UserConfigDir()
358+
if err != nil {
359+
return "", errors.Wrap(err, "getting user config dir")
360+
}
361+
362+
home, err := os.UserHomeDir()
363+
if err != nil {
364+
return "", errors.Wrap(err, "getting home dir")
365+
}
366+
367+
v = strings.ReplaceAll(v, cache, "~/.cache")
368+
v = strings.ReplaceAll(v, config, "~/.config")
369+
v = strings.ReplaceAll(v, home, "~")
370+
371+
return v, nil
372+
}
373+
199374
type docRenderer struct {
200375
commandTemplate *template.Template
201376
groupTemplate *template.Template
@@ -204,31 +379,7 @@ type docRenderer struct {
204379
func newDocRenderer() (*docRenderer, error) {
205380
ct := template.New("command")
206381
ct = ct.Funcs(template.FuncMap{
207-
"sanitise": func(v string) (string, error) {
208-
// Just replacing the home directory will probably cover off most
209-
// cases, but we'll do the user cache and config as well just to be
210-
// safe.
211-
cache, err := os.UserCacheDir()
212-
if err != nil {
213-
return "", errors.Wrap(err, "getting user cache dir")
214-
}
215-
216-
config, err := os.UserConfigDir()
217-
if err != nil {
218-
return "", errors.Wrap(err, "getting user config dir")
219-
}
220-
221-
home, err := os.UserHomeDir()
222-
if err != nil {
223-
return "", errors.Wrap(err, "getting home dir")
224-
}
225-
226-
v = strings.ReplaceAll(v, cache, "~/.cache")
227-
v = strings.ReplaceAll(v, config, "~/.config")
228-
v = strings.ReplaceAll(v, home, "~")
229-
230-
return v, nil
231-
},
382+
"sanitise": sanitiseDocText,
232383
})
233384

234385
ct, err := ct.Parse(docCommandTemplate)
@@ -253,6 +404,25 @@ func (dr *docRenderer) RenderCommand(fqcn string, cmd *command) (string, error)
253404
flags = append(flags, f)
254405
})
255406

407+
usage, err := captureUsage(cmd)
408+
if err != nil {
409+
return "", err
410+
}
411+
412+
buf := &bytes.Buffer{}
413+
if err := dr.commandTemplate.Execute(buf, &docCommandContext{
414+
FQCN: fqcn,
415+
Usage: usage,
416+
Flags: flags,
417+
}); err != nil {
418+
return "", err
419+
}
420+
421+
return buf.String(), nil
422+
}
423+
424+
// captureUsage returns the output of the command's usage function.
425+
func captureUsage(cmd *command) (string, error) {
256426
// The usage functions are, unfortunately, a bit of a mess right now. Some
257427
// output to flag.CommandLine.Output(), some to os.Stderr, some to
258428
// os.Stdout. So let's replace the stdout and stderr variables temporarily
@@ -284,18 +454,7 @@ func (dr *docRenderer) RenderCommand(fqcn string, cmd *command) (string, error)
284454
cmd.flagSet.Usage()
285455
}
286456
w.Close()
287-
usage := <-out
288-
289-
buf := &bytes.Buffer{}
290-
if err := dr.commandTemplate.Execute(buf, &docCommandContext{
291-
FQCN: fqcn,
292-
Usage: usage,
293-
Flags: flags,
294-
}); err != nil {
295-
return "", err
296-
}
297-
298-
return buf.String(), nil
457+
return <-out, nil
299458
}
300459

301460
func (dr *docRenderer) RenderGroup(fqcn string, commands map[string]string) (string, error) {

‎cmd/src/doc_test.go‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package main
22

33
import (
4+
"io"
45
"io/fs"
56
"os"
67
"path/filepath"
@@ -10,6 +11,7 @@ import (
1011
"testing"
1112

1213
"github.com/google/go-cmp/cmp"
14+
"gopkg.in/yaml.v3"
1315
)
1416

1517
// legacyGroupsWithoutSubcommandPages lists legacy command groups that are
@@ -217,3 +219,43 @@ func TestDocRootIndexMatchesHelp(t *testing.T) {
217219
t.Errorf("'src doc' root index does not match 'src help' (-help +index):\n%s", diff)
218220
}
219221
}
222+
223+
// 'src doc -yaml' must write valid YAML for exactly the commands that have
224+
// Markdown pages.
225+
func TestDocYAMLMatchesMarkdown(t *testing.T) {
226+
var want []string
227+
for _, rel := range expectedDocFiles {
228+
name := strings.TrimSuffix(strings.TrimSuffix(rel, ".md"), "index")
229+
want = append(want, strings.TrimSpace("src "+strings.ReplaceAll(name, "/", " ")))
230+
}
231+
sort.Strings(want)
232+
233+
file := filepath.Join(t.TempDir(), "reference.yaml")
234+
for _, cmd := range commands {
235+
if cmd.flagSet.Name() == "doc" {
236+
if err := cmd.handler([]string{"-yaml", "-o", file}); err != nil {
237+
t.Fatalf("src doc -yaml: %v", err)
238+
}
239+
}
240+
}
241+
f, err := os.Open(file)
242+
if err != nil {
243+
t.Fatal(err)
244+
}
245+
defer f.Close()
246+
var got []string
247+
for dec := yaml.NewDecoder(f); ; {
248+
var doc cmdDoc
249+
if err := dec.Decode(&doc); err == io.EOF {
250+
break
251+
} else if err != nil {
252+
t.Fatal(err)
253+
}
254+
got = append(got, doc.Name)
255+
}
256+
sort.Strings(got)
257+
258+
if diff := cmp.Diff(want, got); diff != "" {
259+
t.Errorf("'src doc -yaml' commands do not match the Markdown pages (-markdown +yaml):\n%s", diff)
260+
}
261+
}

0 commit comments

Comments
 (0)