@@ -2,15 +2,20 @@ package main
22
33import (
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 (
2126func 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.
3137Usage:
3238
3339 src doc -o DIR
40+ src doc -yaml -o FILE
3441
3542Examples:
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+
187334func 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+
199374type docRenderer struct {
200375 commandTemplate * template.Template
201376 groupTemplate * template.Template
@@ -204,31 +379,7 @@ type docRenderer struct {
204379func 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
301460func (dr * docRenderer ) RenderGroup (fqcn string , commands map [string ]string ) (string , error ) {
0 commit comments