1package commands
2
3import (
4 "sort"
5
6 "github.com/spf13/cobra"
7)
8
9type commandOptions struct {
10 desc bool
11}
12
13func newCommandsCommand() *cobra.Command {
14 env := newEnv()
15 options := commandOptions{}
16
17 cmd := &cobra.Command{
18 Use: "commands [<option>...]",
19 Short: "Display available commands.",
20 RunE: func(cmd *cobra.Command, args []string) error {
21 return runCommands(env, options)
22 },
23 }
24
25 flags := cmd.Flags()
26 flags.SortFlags = false
27
28 flags.BoolVarP(&options.desc, "pretty", "p", false,
29 "Output the command description as well as Markdown compatible comment",
30 )
31
32 return cmd
33}
34
35func runCommands(env *Env, opts commandOptions) error {
36 first := true
37
38 var allCmds []*cobra.Command
39 queue := []*cobra.Command{NewRootCommand()}
40
41 for len(queue) > 0 {
42 cmd := queue[0]
43 queue = queue[1:]
44 allCmds = append(allCmds, cmd)
45 queue = append(queue, cmd.Commands()...)
46 }
47
48 sort.Sort(commandSorterByName(allCmds))
49
50 for _, cmd := range allCmds {
51 if !first {
52 env.out.Println()
53 }
54
55 first = false
56
57 if opts.desc {
58 env.out.Printf("# %s\n", cmd.Short)
59 }
60
61 env.out.Print(cmd.UseLine())
62
63 if opts.desc {
64 env.out.Println()
65 }
66 }
67
68 if !opts.desc {
69 env.out.Println()
70 }
71
72 return nil
73}
74
75type commandSorterByName []*cobra.Command
76
77func (c commandSorterByName) Len() int { return len(c) }
78func (c commandSorterByName) Swap(i, j int) { c[i], c[j] = c[j], c[i] }
79func (c commandSorterByName) Less(i, j int) bool { return c[i].CommandPath() < c[j].CommandPath() }