-
Notifications
You must be signed in to change notification settings - Fork 33
/
helpfunc.go
72 lines (67 loc) · 1.83 KB
/
helpfunc.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
package goptions
import (
"io"
"sync"
"text/tabwriter"
"text/template"
)
// HelpFunc is the signature of a function responsible for printing the help.
type HelpFunc func(w io.Writer, fs *FlagSet)
// Generates a new HelpFunc taking a `text/template.Template`-formatted
// string as an argument. The resulting template will be executed with the FlagSet
// as its data.
func NewTemplatedHelpFunc(tpl string) HelpFunc {
var once sync.Once
var t *template.Template
return func(w io.Writer, fs *FlagSet) {
once.Do(func() {
t = template.Must(template.New("helpTemplate").Parse(tpl))
})
err := t.Execute(w, fs)
if err != nil {
panic(err)
}
}
}
const (
_DEFAULT_HELP = "\xffUsage: {{.Name}} [global options] {{with .Verbs}}<verb> [verb options]{{end}}\n" +
"\n" +
"Global options:\xff" +
"{{range .Flags}}" +
"\n\t" +
"\t{{with .Short}}" + "-{{.}}," + "{{end}}" +
"\t{{with .Long}}" + "--{{.}}" + "{{end}}" +
"\t{{.Description}}" +
"{{with .DefaultValue}}" +
" (default: {{.}})" +
"{{end}}" +
"{{if .Obligatory}}" +
" (*)" +
"{{end}}" +
"{{end}}" +
"\xff\n\n{{with .Verbs}}Verbs:\xff" +
"{{range .}}" +
"\xff\n {{.Name}}:\xff" +
"{{range .Flags}}" +
"\n\t" +
"\t{{with .Short}}" + "-{{.}}," + "{{end}}" +
"\t{{with .Long}}" + "--{{.}}" + "{{end}}" +
"\t{{.Description}}" +
"{{with .DefaultValue}}" +
" (default: {{.}})" +
"{{end}}" +
"{{if .Obligatory}}" +
" (*)" +
"{{end}}" +
"{{end}}" +
"{{end}}" +
"{{end}}" +
"\n"
)
// DefaultHelpFunc is a HelpFunc which renders the default help template and pipes
// the output through a text/tabwriter.Writer before flushing it to the output.
func DefaultHelpFunc(w io.Writer, fs *FlagSet) {
tw := tabwriter.NewWriter(w, 4, 4, 1, ' ', tabwriter.StripEscape|tabwriter.DiscardEmptyColumns)
NewTemplatedHelpFunc(_DEFAULT_HELP)(tw, fs)
tw.Flush()
}