Allow to sort commands by category

main
Soulou 10 years ago committed by Jesse Szwedko
parent aca5b047ed
commit a0801792cc

@ -34,6 +34,10 @@ type App struct {
HideHelp bool
// Boolean to hide built-in version flag
HideVersion bool
// Display commands by category
CategorizedHelp bool
// Populate when displaying AppHelp
Categories map[string]Commands
// An action to execute when the bash-completion flag is set
BashComplete func(context *Context)
// An action to execute before any subcommands are run, but after the context is ready
@ -95,6 +99,13 @@ func (a *App) Run(arguments []string) (err error) {
a.Authors = append(a.Authors, Author{Name: a.Author, Email: a.Email})
}
if a.CategorizedHelp {
a.Categories = make(map[string]Commands)
for _, command := range a.Commands {
a.Categories[command.Category] = append(a.Categories[command.Category], command)
}
}
newCmds := []Command{}
for _, c := range a.Commands {
if c.HelpName == "" {

@ -22,6 +22,8 @@ type Command struct {
Description string
// A short description of the arguments of this command
ArgsUsage string
// The category the command is part of
Category string
// The function to call when checking for bash command completions
BashComplete func(context *Context)
// An action to execute before any sub-subcommands are run, but after the context is ready
@ -37,7 +39,7 @@ type Command struct {
// If this function is not set, the "Incorrect usage" is displayed and the execution is interrupted.
OnUsageError func(context *Context, err error) error
// List of child commands
Subcommands []Command
Subcommands Commands
// List of flags to parse
Flags []Flag
// Treat all flags as normal arguments if true
@ -59,6 +61,8 @@ func (c Command) FullName() string {
return strings.Join(c.commandNamePath, " ")
}
type Commands []Command
// Invokes the command given the context, parses ctx.Args() to generate command-specific flags
func (c Command) Run(ctx *Context) (err error) {
if len(c.Subcommands) > 0 {

@ -23,9 +23,12 @@ VERSION:
AUTHOR(S):
{{range .Authors}}{{ . }}{{end}}
{{end}}{{if .Commands}}
COMMANDS:
{{range .Commands}}{{join .Names ", "}}{{ "\t" }}{{.Usage}}
{{end}}{{end}}{{if .Flags}}
COMMANDS:{{if .CategorizedHelp}}{{range $category, $commands := .Categories}}{{if $category}}
{{$category}}{{ ":" }}{{end}}{{range $commands}}
{{.Name}}{{with .ShortName}}, {{.}}{{end}}{{ "\t" }}{{.Usage}}{{end}}
{{end}}{{else}}{{range .Commands}}
{{.Name}}{{with .ShortName}}, {{.}}{{end}}{{ "\t" }}{{.Usage}}{{end}}
{{end}}{{end}}{{if .Flags}}
GLOBAL OPTIONS:
{{range .Flags}}{{.}}
{{end}}{{end}}{{if .Copyright }}
@ -43,6 +46,9 @@ var CommandHelpTemplate = `NAME:
USAGE:
{{.HelpName}}{{if .Flags}} [command options]{{end}} {{if .ArgsUsage}}{{.ArgsUsage}}{{else}}[arguments...]{{end}}{{if .Description}}
{{if .Category}}CATEGORY:
{{.Category}}
{{end}}
DESCRIPTION:
{{.Description}}{{end}}{{if .Flags}}

Loading…
Cancel
Save