commands.go

 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		queue = append(queue, cmd.Commands()...)
31	}
32
33	sort.Sort(commandSorterByName(allCmds))
34
35	for _, cmd := range allCmds {
36		if !first {
37			fmt.Println()
38		}
39
40		first = false
41
42		if commandsDesc {
43			fmt.Printf("# %s\n", cmd.Short)
44		}
45
46		fmt.Print(cmd.UseLine())
47
48		if commandsDesc {
49			fmt.Println()
50		}
51	}
52
53	if !commandsDesc {
54		fmt.Println()
55	}
56
57	return nil
58}
59
60var commandsCmd = &cobra.Command{
61	Use:   "commands [<option>...]",
62	Short: "Display available commands.",
63	RunE:  runCommands,
64}
65
66func init() {
67	RootCmd.AddCommand(commandsCmd)
68
69	commandsCmd.Flags().SortFlags = false
70
71	commandsCmd.Flags().BoolVarP(&commandsDesc, "pretty", "p", false,
72		"Output the command description as well as Markdown compatible comment",
73	)
74}