commands.go

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