Skip to content

Commit 3008be3

Browse files
committed
feat/doc: add 'src doc -json' 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 -json -o FILE' writes one JSON tree of all visible commands, with their summary, usage, help, flags, and subcommands.
1 parent 61d7456 commit 3008be3

3 files changed

Lines changed: 203 additions & 40 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 -json -o FILE` writes the command reference as one JSON file: a tree of all commands with their help text and flags.
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: 159 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,20 @@ package main
22

33
import (
44
"bytes"
5+
"cmp"
6+
"encoding/json"
57
"flag"
68
"fmt"
79
"io"
810
"maps"
911
"os"
1012
"path"
13+
"slices"
1114
"strings"
1215
"text/template"
1316

17+
"github.com/urfave/cli/v3"
18+
1419
"github.com/sourcegraph/sourcegraph/lib/docgen"
1520
"github.com/sourcegraph/sourcegraph/lib/errors"
1621
"github.com/sourcegraph/sourcegraph/lib/output"
@@ -21,20 +26,24 @@ 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 -json")
30+
jsonFlag = flagSet.Bool("json", false, "Write the reference as one JSON file instead of Markdown files")
2531
)
2632

2733
usage := `
28-
'src doc' is an internal command that generates the Markdown reference
34+
'src doc' is an internal command that generates the Markdown or JSON reference
2935
documentation used within Sourcegraph.
3036
3137
Usage:
3238
3339
src doc -o DIR
40+
src doc -json -o FILE
3441
3542
Examples:
3643
3744
$ src doc -o ~/sourcegraph/doc/integration/cli/reference
45+
46+
$ src doc -json -o ~/sourcegraph/docs/cli/references.json
3847
`
3948

4049
handler := func(args []string) error {
@@ -44,7 +53,7 @@ Examples:
4453

4554
out := output.NewOutput(flagSet.Output(), output.OutputOpts{Verbose: *verbose})
4655
if *outputFlag == "" {
47-
out.WriteLine(output.Line(output.EmojiFailure, output.StyleWarning, "output directory must be set via -o"))
56+
out.WriteLine(output.Line(output.EmojiFailure, output.StyleWarning, "output must be set via -o"))
4857
flagSet.Usage()
4958
return cmderrors.ExitCode(1, nil)
5059
}
@@ -68,6 +77,29 @@ Examples:
6877
"snapshot": &snapshotCommands,
6978
}
7079

80+
if *jsonFlag {
81+
root := &docCommand{Name: "src"}
82+
if root.Commands, err = legacyDocCommands(commanders, ""); err != nil {
83+
return err
84+
}
85+
for _, cmd := range docgen.VisibleCommands(migratedRootCommand().Commands) {
86+
root.Commands = append(root.Commands, migratedDocCommand("src "+cmd.Name, cmd))
87+
}
88+
sortDocCommands(root.Commands)
89+
var buf bytes.Buffer
90+
enc := json.NewEncoder(&buf)
91+
enc.SetEscapeHTML(false)
92+
enc.SetIndent("", " ")
93+
if err := enc.Encode(root); err != nil {
94+
return err
95+
}
96+
content, err := sanitiseDocText(buf.String())
97+
if err != nil {
98+
return err
99+
}
100+
return os.WriteFile(*outputFlag, []byte(content), 0644)
101+
}
102+
71103
rootSubcommands := map[string]string{}
72104
count := 0
73105
for groupName, cmdr := range commanders {
@@ -184,6 +216,81 @@ Examples:
184216
})
185217
}
186218

219+
// docCommand is one command in the reference that 'src doc -json' writes: a
220+
// single tree of all visible commands, like gcloud's CLI tree.
221+
type docCommand struct {
222+
Name string `json:"name"`
223+
Summary string `json:"summary,omitempty"`
224+
Usage string `json:"usage,omitempty"`
225+
Help string `json:"help,omitempty"`
226+
Flags []docFlag `json:"flags,omitempty"`
227+
Commands []*docCommand `json:"commands,omitempty"`
228+
}
229+
230+
type docFlag struct {
231+
Name string `json:"name"`
232+
Aliases []string `json:"aliases,omitempty"`
233+
Default string `json:"default,omitempty"`
234+
Description string `json:"description,omitempty"`
235+
}
236+
237+
func sortDocCommands(commands []*docCommand) {
238+
slices.SortFunc(commands, func(a, b *docCommand) int { return cmp.Compare(a.Name, b.Name) })
239+
}
240+
241+
func legacyDocCommands(commanders map[string]*commander, group string) ([]*docCommand, error) {
242+
var commands []*docCommand
243+
for _, cmd := range *commanders[group] {
244+
if cmd.hidden {
245+
continue
246+
}
247+
fqcn := strings.TrimSpace(group + " " + cmd.flagSet.Name())
248+
249+
// Most usage functions print "Usage of 'src ...':" and the flags
250+
// before the help. Leave both out: the flags are listed separately.
251+
cmd.flagSet.SetOutput(io.Discard)
252+
usage, err := captureUsage(cmd)
253+
cmd.flagSet.SetOutput(nil)
254+
if err != nil {
255+
return nil, err
256+
}
257+
usage = strings.TrimSpace(usage)
258+
if first, rest, _ := strings.Cut(usage, "\n"); strings.HasPrefix(first, "Usage of ") {
259+
usage = strings.Trim(rest, "\n")
260+
}
261+
262+
c := &docCommand{Name: "src " + fqcn, Summary: cmd.description, Help: usage}
263+
cmd.flagSet.VisitAll(func(f *flag.Flag) {
264+
c.Flags = append(c.Flags, docFlag{Name: f.Name, Default: f.DefValue, Description: f.Usage})
265+
})
266+
if _, ok := commanders[fqcn]; ok {
267+
if c.Commands, err = legacyDocCommands(commanders, fqcn); err != nil {
268+
return nil, err
269+
}
270+
}
271+
commands = append(commands, c)
272+
}
273+
sortDocCommands(commands)
274+
return commands, nil
275+
}
276+
277+
func migratedDocCommand(name string, cmd *cli.Command) *docCommand {
278+
c := &docCommand{
279+
Name: name,
280+
Summary: cmd.Usage,
281+
Usage: strings.TrimSpace(cmd.UsageText),
282+
Help: strings.TrimSpace(cmd.Description),
283+
}
284+
for _, f := range cmd.Flags {
285+
df := f.(cli.DocGenerationFlag)
286+
c.Flags = append(c.Flags, docFlag{Name: f.Names()[0], Aliases: f.Names()[1:], Default: df.GetValue(), Description: df.GetUsage()})
287+
}
288+
for _, sub := range docgen.VisibleCommands(cmd.Commands) {
289+
c.Commands = append(c.Commands, migratedDocCommand(name+" "+sub.Name, sub))
290+
}
291+
return c
292+
}
293+
187294
func openDocFile(base, fqcn string) (interface {
188295
io.StringWriter
189296
io.WriteCloser
@@ -196,6 +303,34 @@ func openDocFile(base, fqcn string) (interface {
196303
return os.Create(cmdPath + ".md")
197304
}
198305

306+
// sanitiseDocText replaces the user's directories in v, such as in flag
307+
// defaults, with generic ones.
308+
func sanitiseDocText(v string) (string, error) {
309+
// Just replacing the home directory will probably cover off most
310+
// cases, but we'll do the user cache and config as well just to be
311+
// safe.
312+
cache, err := os.UserCacheDir()
313+
if err != nil {
314+
return "", errors.Wrap(err, "getting user cache dir")
315+
}
316+
317+
config, err := os.UserConfigDir()
318+
if err != nil {
319+
return "", errors.Wrap(err, "getting user config dir")
320+
}
321+
322+
home, err := os.UserHomeDir()
323+
if err != nil {
324+
return "", errors.Wrap(err, "getting home dir")
325+
}
326+
327+
v = strings.ReplaceAll(v, cache, "~/.cache")
328+
v = strings.ReplaceAll(v, config, "~/.config")
329+
v = strings.ReplaceAll(v, home, "~")
330+
331+
return v, nil
332+
}
333+
199334
type docRenderer struct {
200335
commandTemplate *template.Template
201336
groupTemplate *template.Template
@@ -204,31 +339,7 @@ type docRenderer struct {
204339
func newDocRenderer() (*docRenderer, error) {
205340
ct := template.New("command")
206341
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-
},
342+
"sanitise": sanitiseDocText,
232343
})
233344

234345
ct, err := ct.Parse(docCommandTemplate)
@@ -253,6 +364,25 @@ func (dr *docRenderer) RenderCommand(fqcn string, cmd *command) (string, error)
253364
flags = append(flags, f)
254365
})
255366

367+
usage, err := captureUsage(cmd)
368+
if err != nil {
369+
return "", err
370+
}
371+
372+
buf := &bytes.Buffer{}
373+
if err := dr.commandTemplate.Execute(buf, &docCommandContext{
374+
FQCN: fqcn,
375+
Usage: usage,
376+
Flags: flags,
377+
}); err != nil {
378+
return "", err
379+
}
380+
381+
return buf.String(), nil
382+
}
383+
384+
// captureUsage returns the output of the command's usage function.
385+
func captureUsage(cmd *command) (string, error) {
256386
// The usage functions are, unfortunately, a bit of a mess right now. Some
257387
// output to flag.CommandLine.Output(), some to os.Stderr, some to
258388
// os.Stdout. So let's replace the stdout and stderr variables temporarily
@@ -284,18 +414,7 @@ func (dr *docRenderer) RenderCommand(fqcn string, cmd *command) (string, error)
284414
cmd.flagSet.Usage()
285415
}
286416
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
417+
return <-out, nil
299418
}
300419

301420
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+
"encoding/json"
45
"io/fs"
56
"os"
67
"path/filepath"
@@ -217,3 +218,44 @@ func TestDocRootIndexMatchesHelp(t *testing.T) {
217218
t.Errorf("'src doc' root index does not match 'src help' (-help +index):\n%s", diff)
218219
}
219220
}
221+
222+
// 'src doc -json' must write exactly the commands that have Markdown pages.
223+
func TestDocJSONMatchesMarkdown(t *testing.T) {
224+
var want []string
225+
for _, rel := range expectedDocFiles {
226+
name := strings.TrimSuffix(strings.TrimSuffix(rel, ".md"), "index")
227+
want = append(want, strings.TrimSpace("src "+strings.ReplaceAll(name, "/", " ")))
228+
}
229+
sort.Strings(want)
230+
231+
file := filepath.Join(t.TempDir(), "reference.json")
232+
for _, cmd := range commands {
233+
if cmd.flagSet.Name() == "doc" {
234+
if err := cmd.handler([]string{"-json", "-o", file}); err != nil {
235+
t.Fatalf("src doc -json: %v", err)
236+
}
237+
}
238+
}
239+
data, err := os.ReadFile(file)
240+
if err != nil {
241+
t.Fatal(err)
242+
}
243+
var root docCommand
244+
if err := json.Unmarshal(data, &root); err != nil {
245+
t.Fatal(err)
246+
}
247+
var got []string
248+
var walk func(*docCommand)
249+
walk = func(c *docCommand) {
250+
got = append(got, c.Name)
251+
for _, sub := range c.Commands {
252+
walk(sub)
253+
}
254+
}
255+
walk(&root)
256+
sort.Strings(got)
257+
258+
if diff := cmp.Diff(want, got); diff != "" {
259+
t.Errorf("'src doc -json' commands do not match the Markdown pages (-markdown +json):\n%s", diff)
260+
}
261+
}

0 commit comments

Comments
 (0)