-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhelp.go
350 lines (316 loc) · 9.88 KB
/
help.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
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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
// Copyright (C) 2020 Michael J. Fromberger. All Rights Reserved.
package command
import (
"bytes"
"flag"
"fmt"
"io"
"os"
"reflect"
"strings"
"text/tabwriter"
)
// HelpCommand constructs a standardized help command with optional topics.
// The caller is free to edit the resulting command, each call returns a
// separate value.
//
// As a special case, if there are arguments after the help command and the
// first is one of "-a", "-all", or "--all", that argument is discarded and the
// rendered help text includes unlisted commands and private flags.
func HelpCommand(topics []HelpTopic) *C {
cmd := &C{
Name: "help",
Usage: "[-a|--all] [topic/command]",
Help: `Print help for the specified command or topic.
With -a or --all, also show help for unlisted commands and private flags.`,
CustomFlags: true,
Run: func(env *Env) error {
if len(env.Args) >= 1 { // maybe: help -a foo
switch env.Args[0] {
case "-a", "-all", "--all":
env.HelpFlags(IncludeUnlisted | IncludePrivateFlags)
env.Args = env.Args[1:]
}
}
return RunHelp(env)
},
}
for _, topic := range topics {
cmd.Commands = append(cmd.Commands, topic.command())
}
return cmd
}
// A HelpTopic specifies a name and some help text for use in constructing help
// topic commands.
type HelpTopic struct {
Name string
Help string
}
func (h HelpTopic) command() *C { return &C{Name: h.Name, Help: h.Help} }
// HelpInfo records synthesized help details for a command.
type HelpInfo struct {
Name string
Synopsis string
Usage string
Help string
Flags string
// Help for subcommands (populated if requested)
Commands []HelpInfo
// Help for subtopics (populated if requested)
Topics []HelpInfo
}
// HelpFlags is a bit mask of flags for the HelpInfo method.
type HelpFlags int
func (h HelpFlags) wantCommands() bool { return h&IncludeCommands != 0 }
func (h HelpFlags) wantUnlisted() bool { return h&IncludeUnlisted != 0 }
func (h HelpFlags) wantPrivateFlags() bool { return h&IncludePrivateFlags != 0 }
const (
IncludeCommands HelpFlags = 1 << iota // include subcommands and help topics
IncludeUnlisted // include unlisted subcommands
IncludePrivateFlags // include private (hidden) flags
)
// HelpInfo returns help details for c.
//
// A command or subcommand with no Run function and no subcommands of its own
// is considered a help topic, and listed separately.
//
// Flags whose usage message has the case-sensitive prefix "PRIVATE:" are
// omitted from help listings unless [IncludePrivateFlags] is set.
// Subcommands marked as unlisted are omitted from help listings unless
// [IncludeUnlisted] is set.
func (c *C) HelpInfo(flags HelpFlags) HelpInfo {
help := strings.TrimSpace(c.Help)
prefix := " " + c.Name + " "
h := HelpInfo{
Name: c.Name,
Synopsis: strings.SplitN(help, "\n", 2)[0],
Help: help,
}
if u := c.usageLines(flags); len(u) != 0 {
h.Usage = "Usage:\n\n" + indent(prefix, prefix, strings.Join(u, "\n"))
}
if c.hasFlagsDefined(flags.wantPrivateFlags()) {
var buf bytes.Buffer
fmt.Fprintln(&buf, "Flags:")
writeFlagHelp(&buf, &c.Flags, flags.wantPrivateFlags())
h.Flags = strings.TrimSpace(buf.String())
}
if flags.wantCommands() {
for _, cmd := range c.Commands {
if cmd.Unlisted && !flags.wantUnlisted() {
continue
}
sh := cmd.HelpInfo(flags &^ IncludeCommands) // don't recur
if cmd.Runnable() || len(cmd.Commands) != 0 {
h.Commands = append(h.Commands, sh)
} else {
h.Topics = append(h.Topics, sh)
}
}
}
return h
}
func (c *C) hasFlagsDefined(wantPrivate bool) (ok bool) {
if !c.CustomFlags {
c.Flags.VisitAll(func(f *flag.Flag) {
if !strings.HasPrefix(f.Usage, flagPrivatePrefix) || wantPrivate {
ok = true
}
})
}
return
}
func (c *C) setFlags(env *Env, fs *flag.FlagSet) {
if c != nil && c.SetFlags != nil && !c.isFlagSet {
c.SetFlags(env, fs)
c.isFlagSet = true
}
}
// WriteUsage writes a usage summary to w.
func (h HelpInfo) WriteUsage(w io.Writer) {
if h.Usage != "" {
fmt.Fprint(w, h.Usage, "\n\n")
}
}
// WriteSynopsis writes a usage summary and command synopsis to w.
// If the command defines flags, the flag summary is also written.
func (h HelpInfo) WriteSynopsis(w io.Writer) {
h.WriteUsage(w)
if h.Synopsis == "" {
fmt.Fprint(w, "(no description available)\n\n")
} else {
fmt.Fprint(w, h.Synopsis+"\n\n")
}
if h.Flags != "" {
fmt.Fprint(w, h.Flags, "\n\n")
}
}
// WriteLong writes a complete help description to w, including a usage
// summary, full help text, flag summary, and subcommands.
func (h HelpInfo) WriteLong(w io.Writer) {
h.WriteUsage(w)
if h.Help == "" {
fmt.Fprint(w, "(no description available)\n\n")
} else {
fmt.Fprint(w, h.Help, "\n\n")
}
if h.Flags != "" {
fmt.Fprint(w, h.Flags, "\n\n")
}
if len(h.Commands) != 0 {
writeTopics(w, h.Name+" ", "Subcommands:", h.Commands)
}
if len(h.Topics) != 0 {
writeTopics(w, "", "Help topics:", h.Topics)
}
}
func writeTopics(w io.Writer, base, label string, topics []HelpInfo) {
fmt.Fprintln(w, label)
tw := tabwriter.NewWriter(w, 4, 8, 1, ' ', 0)
for _, cmd := range topics {
syn := cmd.Synopsis
if syn == "" {
syn = "(no description available)"
}
fmt.Fprint(tw, " ", base+cmd.Name, "\t:\t", syn, "\n")
}
tw.Flush()
fmt.Fprintln(w)
}
// runLongHelp is a run function that prints long-form help.
// The topics are additional help topics to include in the output.
func printLongHelp(env *Env, topics []HelpInfo) error {
ht := env.Command.HelpInfo(env.hflag | IncludeCommands)
ht.Topics = append(ht.Topics, topics...)
ht.WriteLong(env)
return ErrRequestHelp
}
// runShortHelp is a run function that prints synopsis help.
func printShortHelp(env *Env) error {
env.Command.HelpInfo(env.hflag).WriteSynopsis(env)
return ErrRequestHelp
}
// toStdout returns a copy of e in which output goes to stdout instead of
// whatever it is set to (stderr by default).
func (e *Env) toStdout() *Env {
cenv := *e // shallow copy
cenv.Log = os.Stdout
return &cenv
}
// RunHelp is a run function that implements long help. It displays the
// help for the enclosing command or subtopics of "help" itself.
func RunHelp(env *Env) error {
// Check whether the arguments describe the parent or one of its subcommands.
target := walkArgs(env.Parent.HelpFlags(env.hflag), env.Args)
if target == env.Parent {
// For the parent, include the help command's own topics.
return printLongHelp(target.toStdout(), env.Command.HelpInfo(env.hflag|IncludeCommands).Topics)
} else if target != nil {
return printLongHelp(target.toStdout(), nil)
}
// Otherwise, check whether the arguments name a help subcommand.
if ht := walkArgs(env, env.Args); ht != nil {
return printLongHelp(ht.toStdout(), nil)
}
// Otherwise the arguments request an unknown topic.
fmt.Fprintf(env, "Unknown help topic %q\n", strings.Join(env.Args, " "))
return ErrRequestHelp
}
func walkArgs(env *Env, args []string) *Env {
cur := env
for _, arg := range args {
// If no corresponding subcommand is found, or if the subtree starting
// with that command is unlisted and we weren't asked to show unlisted
// things, report no match.
next := cur.Command.FindSubcommand(arg)
if next == nil {
return nil
} else if next.Unlisted && !env.hflag.wantUnlisted() {
return nil // skip unlisted commands when not flagged on
}
// Populate flags so that the help text will include them.
next.setFlags(cur, &next.Flags)
cur = cur.newChild(next, nil)
}
return cur
}
const flagPrivatePrefix = "PRIVATE:"
// writeFlagHelp writes descriptive help about the flags defined in fs to w.
//
// This is essentially a copy of flag.FlagSet.PrintDefault, with changes:
//
// - Long flag names (> 1 character) are prefixed by "--" instead of "-".
// - Flags whose usage begins with "PRIVATE:" are omitted.
func writeFlagHelp(w *bytes.Buffer, fs *flag.FlagSet, wantPrivate bool) {
var errs []error
fs.VisitAll(func(f *flag.Flag) {
if u, ok := strings.CutPrefix(f.Usage, flagPrivatePrefix); ok {
if !wantPrivate {
return // don't display this flag
}
f.Usage = strings.TrimPrefix(u, " ")
}
tag := " -"
if len(f.Name) > 1 {
tag = " --"
}
fmt.Fprint(w, tag, f.Name)
name, usage := flag.UnquoteUsage(f)
if name != "" {
fmt.Fprint(w, " ", name)
}
if len(f.Name) == 1 && name == "" {
w.WriteString("\t")
} else {
w.WriteString("\n \t")
}
w.WriteString(strings.ReplaceAll(usage, "\n", "\n \t"))
if ok, err := isZeroValue(f, f.DefValue); err != nil {
errs = append(errs, err)
} else if !ok {
if isStringish(f) {
fmt.Fprintf(w, " (default %q)", f.DefValue)
} else {
fmt.Fprintf(w, " (default %v)", f.DefValue)
}
}
w.WriteString("\n")
})
if len(errs) != 0 {
for _, err := range errs {
fmt.Fprint(w, "\n", err)
}
}
}
// isStringish reports whether v has underlying string type.
func isStringish(f *flag.Flag) bool {
t := reflect.TypeOf(f.Value)
if t.Kind() == reflect.Ptr {
t = t.Elem()
}
return t.Kind() == reflect.String
}
// isZeroValue reports whether the string represents the zero value for a
// flag. Copied with minor changes frpm src/flag/flag.go.
func isZeroValue(f *flag.Flag, value string) (ok bool, err error) {
// Build a zero value of the flag's Value type, and see if the result of
// calling its String method equals the value passed in. This works unless
// the Value type is itself an interface type.
typ := reflect.TypeOf(f.Value)
var z reflect.Value
if typ.Kind() == reflect.Pointer {
typ = typ.Elem()
z = reflect.New(typ)
} else {
z = reflect.Zero(typ)
}
// Catch panics calling the String method, which shouldn't prevent the
// usage message from being printed, but that we should report to the
// user so that they know to fix their code.
defer func() {
if e := recover(); e != nil {
err = fmt.Errorf("panic calling String method on zero %v for flag %s: %v", typ, f.Name, e)
}
}()
return value == z.Interface().(flag.Value).String(), nil
}