-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathhelp_sections.go
57 lines (44 loc) · 1.42 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
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 {
unmodifiedCmd := &cobra.Command{}
usageTemplate := unmodifiedCmd.UsageTemplate()
const defaultTpl = `{{if .HasAvailableSubCommands}}
Available Commands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}}
{{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}`
if !strings.Contains(usageTemplate, defaultTpl) {
panic("Expected to find available commands section in spf13/cobra default usage template")
}
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)
}