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