Merge pull request #2906 from hashicorp/f-custom-help

Use a custom help output function
This commit is contained in:
Alex Dadgar 2017-07-25 17:31:44 -07:00 committed by GitHub
commit 8c45963440

49
main.go
View file

@ -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] <command> [<args>]\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()
}