-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathhelp_sections.go
75 lines (56 loc) · 2.12 KB
/
help_sections.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package cobrautil
import (
"fmt"
"strings"
"github.com/spf13/cobra"
)
func init() {
cobra.AddTemplateFunc("commandsWithAnnotation", func(cmd *cobra.Command, key, value string) []*cobra.Command {
var result []*cobra.Command
for _, c := range cmd.Commands() {
anns := map[string]string{}
if c.Annotations != nil {
anns = c.Annotations
}
if anns[key] == value {
result = append(result, c)
}
}
return result
})
}
type HelpSection struct {
Key string
Value string
Title string
}
func HelpSectionsUsageTemplate(sections []HelpSection) string {
usageTemplate := `Usage:{{if .Runnable}}
{{.UseLine}}{{end}}{{if .HasAvailableSubCommands}}
{{.CommandPath}} [command]{{end}}{{if gt (len .Aliases) 0}}
Aliases:
{{.NameAndAliases}}{{end}}{{if .HasExample}}
Examples:
{{.Example}}{{end}}{{if .HasAvailableSubCommands}}
Available Commands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}}
{{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}
Flags:
{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}}
Global Flags:
{{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasHelpSubCommands}}
Additional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}}
{{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}}
Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}}
`
const defaultTpl = `{{if .HasAvailableSubCommands}}
Available Commands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}}
{{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}`
newTpl := "{{if .HasAvailableSubCommands}}"
for _, section := range sections {
newTpl += fmt.Sprintf(`{{$cmds := (commandsWithAnnotation . "%s" "%s")}}{{if $cmds}}
%s{{range $cmds}}{{if (or .IsAvailableCommand (eq .Name "help"))}}
{{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}`, section.Key, section.Value, section.Title)
}
newTpl += "{{end}}"
return strings.Replace(usageTemplate, defaultTpl, newTpl, 1)
}