-
Notifications
You must be signed in to change notification settings - Fork 2
/
usage.go
445 lines (408 loc) · 9.8 KB
/
usage.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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
package mcli
import (
"fmt"
"io"
"reflect"
"regexp"
"sort"
"strings"
"github.com/MakeNowJust/heredoc/v2"
)
func newUsagePrinter(app *App) *usagePrinter {
ctx := app.getParsingContext()
out := ctx.getFlagSet().Output()
return &usagePrinter{
app: app,
ctx: ctx,
out: out,
}
}
type usagePrinter struct {
app *App
ctx *parsingContext
out io.Writer
flagCount int
hasShortFlag bool
subCmds commands
globalFlagHelp []usageItem
cmdFlagHelp []usageItem
nonFlagHelp []usageItem
envVarsHelp []usageItem
}
func (p *usagePrinter) Do() {
ctx := p.ctx
out := p.out
if ctx.opts.customUsage != nil {
help := strings.TrimSpace(heredoc.Doc(ctx.opts.customUsage()))
fmt.Fprintf(out, "%s\n\n", help)
return
}
globalFlags := p.app.getGlobalFlags()
if !ctx.parsed && globalFlags != nil {
wrapArgs := &withGlobalFlagArgs{
GlobalFlags: globalFlags,
}
err := ctx.parseTags(reflect.ValueOf(wrapArgs).Elem())
if err != nil {
return
}
}
cmdName := ctx.name
cmds := p.app.cmds
p.subCmds = cmds.listSubCommandsToPrint(cmdName, ctx.showHidden)
p.printUsageLine()
p.printSubCommands()
p.countFlags()
p.splitAndFormatFlags()
p.printCmdFlags()
p.printArguments()
p.printGlobalFlags()
p.printEnvVariables()
p.printExamples()
p.printFooter()
}
func (p *usagePrinter) printUsageLine() {
usage := ""
ctx := p.ctx
out := p.out
cmd := ctx.cmd
cmdName := ctx.name
progName := getProgramName()
appDesc := strings.TrimSpace(p.app.Description)
if cmd != nil {
cmdOpts := newCmdOptions(cmd.cmdOpts...)
if cmd.isRoot {
if appDesc != "" {
usage += appDesc + "\n"
}
} else {
if cmd.AliasOf != "" {
usage += cmd.Description + "\n"
cmd = p.app.cmdMap[cmd.AliasOf]
cmdName = cmd.Name
}
if cmd.Description != "" {
usage += cmd.Description + "\n"
}
}
if cmdOpts.longDesc != "" {
if usage != "" {
usage += "\n"
}
usage += cmdOpts.longDesc + "\n"
}
} else if appDesc != "" {
usage += appDesc + "\n"
}
if usage != "" {
usage += "\n"
}
usage += "Usage:\n " + progName
if cmd != nil && cmd.isRoot {
usage += p.commandLineFlagAndSubCmdInfo("")
if len(p.app.cmds) > 0 {
usage += "\n " + progName + " <command> [flags] ..."
}
} else {
usage += p.commandLineFlagAndSubCmdInfo(cmdName)
}
fmt.Fprint(out, usage, "\n\n")
}
func (p *usagePrinter) commandLineFlagAndSubCmdInfo(cmdName string) string {
ctx := p.ctx
hasFlags := len(ctx.flags) > 0
hasNonflags := len(ctx.nonflags) > 0
hasSubCmds := len(p.subCmds) > 0
usage := ""
if cmdName != "" {
usage += " " + cmdName
}
if hasFlags {
usage += " [flags]"
}
if hasNonflags {
for _, f := range ctx.nonflags {
name := f.name
if f.isSlice() {
name += "..."
} else if f.isMap() {
name += "{...}"
}
if f.required {
usage += fmt.Sprintf(" <%s>", name)
} else {
usage += fmt.Sprintf(" [%s]", name)
}
}
}
if !hasFlags && !hasNonflags && hasSubCmds {
usage += " <command> ..."
}
return usage
}
func (p *usagePrinter) printSubCommands() {
ctx := p.ctx
out := p.out
if len(p.subCmds) > 0 {
parentCmdName := ctx.name
subCmds := p.subCmds
showHidden := ctx.showHidden
keepCmdOrder := p.app.Options.KeepCommandOrder
p.__printSubCommands(out, subCmds, parentCmdName, showHidden, keepCmdOrder)
}
}
func (p *usagePrinter) countFlags() {
flags := p.ctx.flags
showHidden := p.ctx.showHidden
for _, f := range flags {
if !f.hidden || showHidden {
p.flagCount++
p.hasShortFlag = p.hasShortFlag || f.short != ""
}
}
}
func (p *usagePrinter) splitAndFormatFlags() {
flags := p.ctx.flags
showHidden := p.ctx.showHidden
hasShortFlag := p.hasShortFlag
var (
globalFlagHelp []usageItem
cmdFlagHelp []usageItem
nonFlagHelp []usageItem
envVarsHelp []usageItem
)
if p.flagCount > 0 {
for _, f := range flags {
if f.hidden && !showHidden {
continue
}
usage := f.getUsage(hasShortFlag)
if f.isGlobal {
globalFlagHelp = append(globalFlagHelp, usage)
} else {
cmdFlagHelp = append(cmdFlagHelp, usage)
}
}
}
for _, f := range p.ctx.nonflags {
usage := f.getUsage(false)
nonFlagHelp = append(nonFlagHelp, usage)
}
for _, f := range p.ctx.envVars {
usage := f.getUsage(false)
envVarsHelp = append(envVarsHelp, usage)
}
p.globalFlagHelp = globalFlagHelp
p.cmdFlagHelp = cmdFlagHelp
p.nonFlagHelp = nonFlagHelp
p.envVarsHelp = envVarsHelp
}
func (p *usagePrinter) printCmdFlags() {
out := p.out
if len(p.cmdFlagHelp) > 0 {
fmt.Fprint(out, "Flags:\n")
printWithAlignment(out, p.cmdFlagHelp, 0)
fmt.Fprint(out, "\n")
}
}
func (p *usagePrinter) printArguments() {
out := p.out
if len(p.nonFlagHelp) > 0 {
fmt.Fprint(out, "Arguments:\n")
printWithAlignment(out, p.nonFlagHelp, 0)
fmt.Fprint(out, "\n")
}
}
func (p *usagePrinter) printGlobalFlags() {
out := p.out
if len(p.globalFlagHelp) > 0 {
fmt.Fprint(out, "Global Flags:\n")
printWithAlignment(out, p.globalFlagHelp, 0)
fmt.Fprint(out, "\n")
}
}
func (p *usagePrinter) printEnvVariables() {
out := p.out
padding := " "
if len(p.envVarsHelp) > 0 {
fmt.Fprint(out, "Environment Variables:\n")
for _, line := range p.envVarsHelp {
x, y := line.prefix, line.description
fmt.Fprintf(out, "%s\n", x)
if y != "" {
fmt.Fprintf(out, "%s%s\n", padding, strings.ReplaceAll(y, "\n", "\n"+padding))
}
}
fmt.Fprint(out, "\n")
}
}
var blankLineRE = regexp.MustCompile(`\n\s+\n`)
func (p *usagePrinter) printExamples() {
ctx := p.ctx
out := p.out
if ctx.opts.examples != "" {
examples := strings.ReplaceAll(ctx.opts.examples, "\n", "\n ")
examples = blankLineRE.ReplaceAllString(examples, "\n\n")
fmt.Fprint(out, "Examples:\n ")
fmt.Fprintf(out, "%s\n\n", examples)
}
}
func (p *usagePrinter) printFooter() {
ctx := p.ctx
out := p.out
if ctx.opts.helpFooter != nil {
footer := strings.TrimSpace(ctx.opts.helpFooter())
fmt.Fprintf(out, "%s\n\n", footer)
} else if p.app.HelpFooter != "" {
footer := strings.TrimSpace(p.app.HelpFooter)
fmt.Fprintf(out, "%s\n\n", footer)
}
}
func (p *usagePrinter) __printSubCommands(out io.Writer, cmds commands, parentCmdName string, showHidden, keepCmdOrder bool) {
if len(cmds) == 0 {
return
}
if keepCmdOrder {
sort.Slice(cmds, func(i, j int) bool {
return cmds[i].idx < cmds[j].idx
})
}
cmdGroups, hasCategories := cmds.groupByCategory()
if hasCategories {
p.__printGroupedSubCommands(out, cmdGroups, showHidden)
return
}
var cmdLines []usageItem
prefix := []string{""}
preName := ""
for _, cmd := range cmds {
cmdName := trimPrefix(cmd.Name, parentCmdName)
if cmdName == "" || (cmd.Hidden && !showHidden) {
continue
}
if preName != "" && cmdName != preName {
if strings.HasPrefix(cmdName, preName) {
prefix = append(prefix, preName)
} else {
for i := len(prefix) - 1; i > 0; i-- {
if !strings.HasPrefix(cmdName, prefix[i]) {
prefix = prefix[:i]
}
}
}
}
leafCmdName := trimPrefix(cmdName, prefix[len(prefix)-1])
if cmd.isCompletion && leafCmdName != cmdName {
continue
}
name := strings.Repeat(" ", len(prefix)) + leafCmdName
description := cmd.Description
if cmd.Hidden {
name += " (HIDDEN)"
}
cmdLines = append(cmdLines, usageItem{
prefix: name,
description: description,
})
preName = cmdName
}
fmt.Fprint(out, "Commands:\n")
printWithAlignment(out, cmdLines, 0)
fmt.Fprint(out, "\n")
}
func (p *usagePrinter) __printGroupedSubCommands(out io.Writer, cmdGroups []*categoryCommands, showHidden bool) {
type groupCmdLines struct {
category string
cmdLines []usageItem
}
sort.Slice(cmdGroups, func(i, j int) bool {
idx1 := p.app.categoryIdx[cmdGroups[i].category]
idx2 := p.app.categoryIdx[cmdGroups[j].category]
if idx1 > 0 && idx2 > 0 {
return idx1 < idx2
}
return idx1 > 0
})
var groupLines []*groupCmdLines
var cmdLines [][]usageItem
for _, grp := range cmdGroups {
var grpLines []usageItem
for _, cmd := range grp.commands {
cmdName := cmd.Name
if cmdName == "" || (cmd.Hidden && !showHidden) || cmd.level > 1 {
continue
}
name := " " + cmdName
description := cmd.Description
if cmd.Hidden {
name += " (HIDDEN)"
}
grpLines = append(grpLines, usageItem{
prefix: name,
description: description,
})
}
if len(grpLines) == 0 {
continue
}
groupLines = append(groupLines, &groupCmdLines{
category: grp.category,
cmdLines: grpLines,
})
cmdLines = append(cmdLines, grpLines)
}
maxPrefixLen := calcMaxPrefixLen(cmdLines)
for _, grp := range groupLines {
fmt.Fprint(out, addTrailingColon(grp.category)+"\n")
printWithAlignment(out, grp.cmdLines, maxPrefixLen)
fmt.Fprint(out, "\n")
}
}
func addTrailingColon(s string) string {
if !strings.HasSuffix(s, ":") {
s += ":"
}
return s
}
const (
__MaxPrefixLen = 30
__MinPrefixLen = 6
)
func printWithAlignment(out io.Writer, lines []usageItem, maxPrefixLen int) {
if maxPrefixLen <= 0 {
maxPrefixLen = calcMaxPrefixLen([][]usageItem{lines})
}
padding := strings.Repeat(" ", maxPrefixLen+4)
newlineWithPadding := "\n" + padding
for _, line := range lines {
x, y := line.prefix, line.description
fmt.Fprint(out, x)
if y != "" {
if len(x) <= maxPrefixLen {
fmt.Fprint(out, strings.Repeat(" ", maxPrefixLen+4-len(x)))
fmt.Fprint(out, strings.ReplaceAll(y, "\n", newlineWithPadding))
} else {
fmt.Fprint(out, newlineWithPadding)
fmt.Fprint(out, strings.ReplaceAll(y, "\n", newlineWithPadding))
}
}
fmt.Fprint(out, "\n")
for _, a := range line.appendixes {
fmt.Fprintf(out, "%s%s\n", padding, a)
}
}
}
func calcMaxPrefixLen(lineGroups [][]usageItem) int {
maxPrefixLen := 0
for _, lines := range lineGroups {
for _, line := range lines {
if n := len(line.prefix); n > maxPrefixLen && n <= __MaxPrefixLen {
maxPrefixLen = n
}
}
}
if maxPrefixLen < __MinPrefixLen {
maxPrefixLen = __MinPrefixLen
}
return maxPrefixLen
}