-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathusage.go
More file actions
225 lines (181 loc) · 5.65 KB
/
usage.go
File metadata and controls
225 lines (181 loc) · 5.65 KB
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
package cmder
import (
"bytes"
"cmp"
"flag"
"slices"
"strings"
"text/template"
"time"
)
// CobraUsageTemplate is a text template for rendering command usage information in a format similar to that of the
// popular [github.com/spf13/cobra] library.
const CobraUsageTemplate = `{{ trim .Command.HelpText }}
Usage:
{{ trim .Command.UsageLine }}
Examples:
{{ range (lines (trim .Command.ExampleText)) }} {{ . }}{{ end }}
{{- println -}}
{{- with (commands .) -}}
{{- println -}}
{{- println "Available Commands:" -}}
{{- range . -}}
{{- printf " %-13s %s\n" .Name .ShortHelpText -}}
{{- end -}}
{{- end -}}
{{- with (flags .) -}}
{{- println -}}
{{- println "Flags:" -}}
{{- $print_started := false -}}
{{- range . -}}
{{- if $print_started -}}
{{- println -}}
{{- end -}}
{{- $print_started = true -}}
{{- printf " " -}}
{{- range $index, $flg := . -}}
{{- if (ne $index 0) -}}
{{- printf ", " -}}
{{- end -}}
{{- if (eq (len $flg.Name) 1) -}}
{{- printf "-%s" .Name -}}
{{- else -}}
{{- printf "--%s" .Name -}}
{{- end -}}
{{- $name := (index (unquote $flg) 0) -}}
{{- if (and $name (eq (len $flg.Name) 1)) -}}
{{- printf " <%s>" $name -}}
{{- else if $name -}}
{{- printf "=<%s>" $name -}}
{{- end -}}
{{- end -}}
{{ with (index . 0).DefValue }}
{{- printf " (default %s)" . -}}
{{- end -}}
{{- println -}}
{{- printf " %s\n" (index (unquote (index . 0)) 1) -}}
{{- end -}}
{{- end -}}
{{- if (commands .) -}}
{{- println -}}
{{- printf "Use \"%s [command] --help\" for more information about a command.\n" .Command.Name -}}
{{- end -}}`
// StdFlagUsageTemplate is a text template for rendering command usage information in a minimal format similar to that
// of the [flag] library.
const StdFlagUsageTemplate = `usage: {{ .Command.UsageLine }}
{{ flagusage . }}`
// ErrShowUsage instructs cmder to render usage and exit (status 2).
var ErrShowUsage = flag.ErrHelp
// usage renders usage text for a [Command] using the default template [UsageTemplate]. Output is written to
// [UsageOutputWriter].
func usage(cmd command, ops *ExecuteOptions) error {
tmpl, err := template.New("usage").Funcs(template.FuncMap{
"commands": subcommands,
"flags": flags,
"flagusage": flagUsage,
"unquote": unquote,
"lower": strings.ToLower,
"upper": strings.ToUpper,
"split": strings.Split,
"replace": strings.ReplaceAll,
"join": strings.Join,
"contains": strings.Contains,
"trim": strings.TrimSpace,
"lines": strings.Lines,
}).Parse(ops.usageTemplate)
if err != nil {
return err
}
return tmpl.Execute(ops.usageWriter, cmd)
}
// subcommands returns a map of (visible) child subcommands for cmd.
func subcommands(cmd command) map[string]Command {
subcommands := map[string]Command{}
for name, c := range collectSubcommands(cmd.Command) {
if hidden, ok := c.(HiddenCommand); !ok || !hidden.Hidden() {
subcommands[name] = c
}
}
return subcommands
}
// flags organizes the flags of cmd and returns them.
//
// The flags of cmd are grouped by [flag.Value] equivalence. This allows flags to be grouped together in the rendered
// usage text when two flags are aliases of each other. This is often the case for short flags which are aliases of
// longer flags (e.g. '-a' is an alias of '--all').
//
// -a <string>, --addr=<string>
// -s <string>, --serial-number=<string>
//
// The resulting map entries are keyed by the flag group name, which is the longest flag name in the group. The map
// values are slices of (one or more) flags in the flag group, sorted by flag name length ('-a' before '--all').
func flags(cmd command) map[string][]*flag.Flag {
var collected []*flag.Flag
cmd.fs.VisitAll(func(f *flag.Flag) {
if !isHiddenFlag(f) {
collected = append(collected, f)
}
})
// sort flags by name length in descending order to ensure that keys in resulting map will use long names first
slices.SortFunc(collected, func(a, b *flag.Flag) int {
return cmp.Compare(len(b.Name), len(a.Name))
})
groups := map[string][]*flag.Flag{}
for len(collected) > 0 {
var flg *flag.Flag
// pop the head of the slice
flg, collected = collected[0], collected[1:]
// update groups
groups[flg.Name] = []*flag.Flag{flg}
// traverse the flags again and find (and remove) any which match flg
for i := len(collected) - 1; i >= 0; i-- {
other := collected[i]
if areSame(flg.Value, other.Value) {
groups[flg.Name] = append(groups[flg.Name], other)
collected = append(collected[:i], collected[i+1:]...)
}
}
// sort by length (then lexical order), this time ascending (-a before --all)
slices.SortFunc(groups[flg.Name], func(a, b *flag.Flag) int {
if c := cmp.Compare(len(a.Name), len(b.Name)); c != 0 {
return c
}
return cmp.Compare(a.Name, b.Name)
})
}
return groups
}
// flagUsage dumps the flag usage as rendered by the flag library. See [flag.FlagSet.PrintDefaults].
func flagUsage(cmd command) string {
out := cmd.fs.Output()
defer cmd.fs.SetOutput(out)
var buf bytes.Buffer
cmd.fs.SetOutput(&buf)
cmd.fs.PrintDefaults()
return buf.String()
}
// unquote calls [flag.UnquoteUsage] for the given [flag.Flag].
func unquote(flg *flag.Flag) []string {
if isBoolFlag(flg) {
return []string{"", flg.Usage}
}
name, usage := flag.UnquoteUsage(flg)
// if no backquoted names found, try to infer from [flag.Getter]
if name == "" {
if g, ok := flg.Value.(flag.Getter); ok {
switch g.Get().(type) {
case uint, uint64:
name = "uint"
case int, int64:
name = "int"
case float64:
name = "float"
case time.Duration:
name = "duration"
default:
name = "arg"
}
}
}
return []string{name, usage}
}