-
Notifications
You must be signed in to change notification settings - Fork 0
/
usage.go
78 lines (71 loc) · 1.57 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
package flaq
import (
"fmt"
"os"
"path/filepath"
"strconv"
)
func defaultUsage(flags *FlagSet) string {
usage := flags.UsageLine
if usage == "" {
usage = "Usage: " + filepath.Base(os.Args[0]) + " [options]\n"
}
usage += "\nOptions\n"
usages, maxUsageLen := make(map[*Flag]string), 0
sortedFlags := make([]*Flag, 0, len(flags.flags))
flags.VisitAll(func(f *Flag) {
if !f.Hidden {
usages[f] = flagUsage(f)
if len(usages[f]) > maxUsageLen {
maxUsageLen = len(usages[f])
}
for i := range sortedFlags {
if sortedFlags[i].Long+sortedFlags[i].Short > f.Long+f.Short {
sortedFlags = append(sortedFlags, nil)
copy(sortedFlags[i+1:], sortedFlags[i:])
sortedFlags[i] = f
return
}
}
sortedFlags = append(sortedFlags, f)
}
})
if maxUsageLen > 25 {
maxUsageLen = 25
}
for _, f := range sortedFlags {
usage += fmt.Sprintf(" %-"+strconv.Itoa(maxUsageLen)+"s %s\n", usages[f], f.Description)
}
return usage
}
// flagUsage returns the help usage for a given flag.
func flagUsage(f *Flag) string {
if f.Usage != "" {
return f.Usage
}
usage := " "
if f.Short != "" {
usage = "-" + f.Short
if f.Long != "" {
usage += ", "
}
}
if f.Long != "" {
usage += "--" + f.Long
}
if f.Arg != nil {
argName := f.Arg.Name
if argName == "" {
argName = "arg"
}
switch {
case f.Long != "" && f.Arg.Default != "":
usage += fmt.Sprintf("=<%s>", argName)
case f.Short != "" && f.Arg.Default != "":
usage += fmt.Sprintf("<%s>", argName)
default:
usage += fmt.Sprintf(" <%s>", argName)
}
}
return usage
}