From e15e9ee976f79ffb10f6e5d9901174e0eca86e38 Mon Sep 17 00:00:00 2001 From: Alex Dadgar Date: Tue, 25 Jul 2017 15:42:22 -0700 Subject: [PATCH] Custom help output --- main.go | 49 ++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 48 insertions(+), 1 deletion(-) diff --git a/main.go b/main.go index d2c785d69..ad12a0691 100644 --- a/main.go +++ b/main.go @@ -1,8 +1,12 @@ package main import ( + "bytes" "fmt" + "log" "os" + "sort" + "strings" "github.com/mitchellh/cli" "github.com/sean-/seed" @@ -44,7 +48,7 @@ func RunCustom(args []string, commands map[string]cli.CommandFactory) int { Args: args, Commands: commands, Autocomplete: true, - HelpFunc: cli.FilteredHelpFunc(commandsInclude, cli.BasicHelpFunc("nomad")), + HelpFunc: cli.FilteredHelpFunc(commandsInclude, helpFunc), } exitCode, err := cli.Run() @@ -55,3 +59,46 @@ func RunCustom(args []string, commands map[string]cli.CommandFactory) int { return exitCode } + +// helpFunc is a custom help function. At the moment it is essentially a copy of +// the cli.BasicHelpFunc that includes flags demonstrating how to use the +// autocomplete flags. +func helpFunc(commands map[string]cli.CommandFactory) string { + var buf bytes.Buffer + buf.WriteString("Usage: nomad [-version] [-help] [-autocomplete-(un)install] []\n\n") + buf.WriteString("Available commands are:\n") + + // Get the list of keys so we can sort them, and also get the maximum + // key length so they can be aligned properly. + keys := make([]string, 0, len(commands)) + maxKeyLen := 0 + for key := range commands { + if len(key) > maxKeyLen { + maxKeyLen = len(key) + } + + keys = append(keys, key) + } + sort.Strings(keys) + + for _, key := range keys { + commandFunc, ok := commands[key] + if !ok { + // This should never happen since we JUST built the list of + // keys. + panic("command not found: " + key) + } + + command, err := commandFunc() + if err != nil { + log.Printf("[ERR] cli: Command '%s' failed to load: %s", + key, err) + continue + } + + key = fmt.Sprintf("%s%s", key, strings.Repeat(" ", maxKeyLen-len(key))) + buf.WriteString(fmt.Sprintf(" %s %s\n", key, command.Synopsis())) + } + + return buf.String() +}