From 994a7028e275fefa0b3bbd88c4c48c0942c9be3a Mon Sep 17 00:00:00 2001 From: Soulou Date: Fri, 21 Aug 2015 10:58:14 +0200 Subject: [PATCH] Categories as slice, not a map anymore, order is always preserved --- app.go | 8 +++++--- category.go | 30 ++++++++++++++++++++++++++++++ help.go | 4 ++-- 3 files changed, 37 insertions(+), 5 deletions(-) create mode 100644 category.go diff --git a/app.go b/app.go index fdb2ba5..5ebf201 100644 --- a/app.go +++ b/app.go @@ -6,6 +6,7 @@ import ( "io/ioutil" "os" "path" + "sort" "time" ) @@ -37,7 +38,7 @@ type App struct { // Display commands by category CategorizedHelp bool // Populate when displaying AppHelp - Categories map[string]Commands + Categories CommandCategories // 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 @@ -100,11 +101,12 @@ func (a *App) Run(arguments []string) (err error) { } if a.CategorizedHelp { - a.Categories = make(map[string]Commands) + a.Categories = CommandCategories{} for _, command := range a.Commands { - a.Categories[command.Category] = append(a.Categories[command.Category], command) + a.Categories = a.Categories.AddCommand(command.Category, command) } } + sort.Sort(a.Categories) newCmds := []Command{} for _, c := range a.Commands { diff --git a/category.go b/category.go new file mode 100644 index 0000000..7dbf218 --- /dev/null +++ b/category.go @@ -0,0 +1,30 @@ +package cli + +type CommandCategories []*CommandCategory + +type CommandCategory struct { + Name string + Commands Commands +} + +func (c CommandCategories) Less(i, j int) bool { + return c[i].Name < c[j].Name +} + +func (c CommandCategories) Len() int { + return len(c) +} + +func (c CommandCategories) Swap(i, j int) { + c[i], c[j] = c[j], c[i] +} + +func (c CommandCategories) AddCommand(category string, command Command) CommandCategories { + for _, commandCategory := range c { + if commandCategory.Name == category { + commandCategory.Commands = append(commandCategory.Commands, command) + return c + } + } + return append(c, &CommandCategory{Name: category, Commands: []Command{command}}) +} diff --git a/help.go b/help.go index 8285ff0..7838c89 100644 --- a/help.go +++ b/help.go @@ -23,8 +23,8 @@ VERSION: AUTHOR(S): {{range .Authors}}{{ . }}{{end}} {{end}}{{if .Commands}} -COMMANDS:{{if .CategorizedHelp}}{{range $category, $commands := .Categories}}{{if $category}} - {{$category}}{{ ":" }}{{end}}{{range $commands}} +COMMANDS:{{if .CategorizedHelp}}{{range .Categories}}{{if .Name}} + {{.Name}}{{ ":" }}{{end}}{{range .Commands}} {{.Name}}{{with .ShortName}}, {{.}}{{end}}{{ "\t" }}{{.Usage}}{{end}} {{end}}{{else}}{{range .Commands}} {{.Name}}{{with .ShortName}}, {{.}}{{end}}{{ "\t" }}{{.Usage}}{{end}}