forked from projectatomic/atomic-enterprise
-
Notifications
You must be signed in to change notification settings - Fork 0
/
templater.go
91 lines (76 loc) · 2.19 KB
/
templater.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package templates
import (
"bytes"
"fmt"
"strings"
"text/template"
"github.com/spf13/cobra"
flag "github.com/spf13/pflag"
)
type Templater struct {
UsageTemplate string
Exposed []string
}
func (templater *Templater) UsageFunc() func(*cobra.Command) error {
return func(c *cobra.Command) error {
t := template.New("custom")
t.Funcs(template.FuncMap{
"trim": strings.TrimSpace,
"gt": cobra.Gt,
"eq": cobra.Eq,
"rpad": func(s string, padding int) string {
template := fmt.Sprintf("%%-%ds", padding)
return fmt.Sprintf(template, s)
},
"exposed": func(*cobra.Command) *flag.FlagSet {
exposed := flag.NewFlagSet("exposed", flag.ContinueOnError)
if len(templater.Exposed) > 0 {
for _, name := range templater.Exposed {
if flag := c.Flags().Lookup(name); flag != nil {
exposed.AddFlag(flag)
}
}
}
return exposed
},
"flagsUsages": func(f *flag.FlagSet) string {
x := new(bytes.Buffer)
f.VisitAll(func(flag *flag.Flag) {
format := "--%s=%s: %s\n"
if flag.Value.Type() == "string" {
format = "--%s='%s': %s\n"
}
if len(flag.Shorthand) > 0 {
format = " -%s, " + format
} else {
format = " %s " + format
}
fmt.Fprintf(x, format, flag.Shorthand, flag.Name, flag.DefValue, flag.Usage)
})
return x.String()
},
})
template.Must(t.Parse(templater.UsageTemplate))
return t.Execute(c.Out(), c)
}
}
func UseCliTemplates(cmd *cobra.Command) {
cmd.SetHelpTemplate(CliHelpTemplate())
templater := &Templater{UsageTemplate: CliUsageTemplate()}
cmd.SetUsageFunc(templater.UsageFunc())
}
func UseAdminTemplates(cmd *cobra.Command) {
cmd.SetHelpTemplate(AdminHelpTemplate())
templater := &Templater{UsageTemplate: AdminUsageTemplate()}
cmd.SetUsageFunc(templater.UsageFunc())
}
func UseMainTemplates(cmd *cobra.Command) {
cmd.SetHelpTemplate(MainHelpTemplate())
templater := &Templater{UsageTemplate: MainUsageTemplate()}
cmd.SetUsageFunc(templater.UsageFunc())
}
func UseOptionsTemplates(cmd *cobra.Command) {
cmd.SetHelpTemplate(OptionsHelpTemplate())
templater := &Templater{UsageTemplate: OptionsUsageTemplate()}
cmd.SetUsageFunc(templater.UsageFunc())
}