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