1package root
2
3import (
4	"bytes"
5	"fmt"
6	"io"
7	"strings"
8
9	"github.com/cli/cli/v2/pkg/iostreams"
10	"github.com/cli/cli/v2/pkg/markdown"
11	"github.com/spf13/cobra"
12)
13
14func referenceHelpFn(io *iostreams.IOStreams) func(*cobra.Command, []string) {
15	return func(cmd *cobra.Command, args []string) {
16		wrapWidth := 0
17		style := "notty"
18		if io.IsStdoutTTY() {
19			wrapWidth = io.TerminalWidth()
20			style = markdown.GetStyle(io.DetectTerminalTheme())
21		}
22
23		md, err := markdown.RenderWithWrap(cmd.Long, style, wrapWidth)
24		if err != nil {
25			fmt.Fprintln(io.ErrOut, err)
26			return
27		}
28
29		if !io.IsStdoutTTY() {
30			fmt.Fprint(io.Out, dedent(md))
31			return
32		}
33
34		_ = io.StartPager()
35		defer io.StopPager()
36		fmt.Fprint(io.Out, md)
37	}
38}
39
40func referenceLong(cmd *cobra.Command) string {
41	buf := bytes.NewBufferString("# gh reference\n\n")
42	for _, c := range cmd.Commands() {
43		if c.Hidden {
44			continue
45		}
46		cmdRef(buf, c, 2)
47	}
48	return buf.String()
49}
50
51func cmdRef(w io.Writer, cmd *cobra.Command, depth int) {
52	// Name + Description
53	fmt.Fprintf(w, "%s `%s`\n\n", strings.Repeat("#", depth), cmd.UseLine())
54	fmt.Fprintf(w, "%s\n\n", cmd.Short)
55
56	// Flags
57	// TODO: fold in InheritedFlags/PersistentFlags, but omit `--help` due to repetitiveness
58	if flagUsages := cmd.Flags().FlagUsages(); flagUsages != "" {
59		fmt.Fprintf(w, "```\n%s````\n\n", dedent(flagUsages))
60	}
61
62	// Subcommands
63	for _, c := range cmd.Commands() {
64		if c.Hidden {
65			continue
66		}
67		cmdRef(w, c, depth+1)
68	}
69}
70