diff options
author | Jesse Donat <donatj@gmail.com> | 2018-10-12 17:53:19 -0500 |
---|---|---|
committer | Andrew Jackura <ajackura@google.com> | 2018-10-12 15:53:19 -0700 |
commit | 9dd77848a6fe0ab571d4a7a32bb036dab70aff51 (patch) | |
tree | aa3897486f17e4c1afc642e7ac8c8e65ec13a33e | |
parent | 5bae204cdfb2d92dcc333d56014bae6a2f6c58b1 (diff) | |
download | go-subcommands-9dd77848a6fe0ab571d4a7a32bb036dab70aff51.tar.gz |
Groups aliased commands with original (#16)
-rw-r--r-- | subcommands.go | 37 |
1 files changed, 36 insertions, 1 deletions
diff --git a/subcommands.go b/subcommands.go index bb5ff01..951a4f6 100644 --- a/subcommands.go +++ b/subcommands.go @@ -26,6 +26,7 @@ import ( "os" "path" "sort" + "strings" ) // A Command represents a single command. @@ -197,8 +198,32 @@ func explainGroup(w io.Writer, group *commandGroup) { fmt.Fprintf(w, "Subcommands for %s:\n", group.name) } sort.Sort(group) + + aliases := make(map[string][]string) + for _, cmd := range group.commands { + if alias, ok := cmd.(*aliaser); ok { + root := dealias(alias).Name() + + if _, ok := aliases[root]; !ok { + aliases[root] = []string{} + } + aliases[root] = append(aliases[root], alias.Name()) + } + } + for _, cmd := range group.commands { - fmt.Fprintf(w, "\t%-15s %s\n", cmd.Name(), cmd.Synopsis()) + if _, ok := cmd.(*aliaser); ok { + continue + } + + name := cmd.Name() + names := []string{name} + + if a, ok := aliases[name]; ok { + names = append(names, a...) + } + + fmt.Fprintf(w, "\t%-15s %s\n", strings.Join(names, ", "), cmd.Synopsis()) } fmt.Fprintln(w) } @@ -348,6 +373,16 @@ func Alias(alias string, cmd Command) Command { return &aliaser{alias, cmd} } +// dealias recursivly dealiases a command until a non-aliased command +// is reached. +func dealias(cmd Command) Command { + if alias, ok := cmd.(*aliaser); ok { + return dealias(alias.Command) + } + + return cmd +} + // DefaultCommander is the default commander using flag.CommandLine for flags // and os.Args[0] for the command name. var DefaultCommander *Commander |