-
Notifications
You must be signed in to change notification settings - Fork 0
/
usage.go
103 lines (84 loc) · 2.15 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
package flags
import (
"flag"
"fmt"
"sort"
)
type Flag struct {
flag *flag.Flag
name string
shorthand string
}
func (f *Flag) AddName(name string) {
if len(name) < len(f.flag.Name) {
f.shorthand = name
} else {
f.shorthand = f.flag.Name
f.name = name
}
}
func Usage(fs *flag.FlagSet) func() {
return func() {
flags := make(map[string]*Flag)
fs.VisitAll(func(f *flag.Flag) {
usageSha := Sha(f.Usage)
if exist, ok := flags[usageSha]; ok {
exist.AddName(f.Name)
} else {
flags[usageSha] = &Flag{
name: f.Name,
flag: f,
}
}
})
var (
maxTypeLen int
maxNameLen int
maxShorthandLen int
)
output := fs.Output()
if name := fs.Name(); len(name) > 0 {
fmt.Fprintf(output, "Usage of %s:\n", fs.Name())
} else {
fmt.Fprint(output, "Usage:\n")
}
items := make([]*Flag, 0, len(flags))
for _, item := range flags {
index := sort.Search(len(items), func(i int) bool {
return items[i].name > item.name
})
items = append(items, item)
copy(items[index+1:], items[index:])
items[index] = item
if length := len(item.name); length > maxNameLen {
maxNameLen = length
}
if length := len(item.shorthand); length > maxShorthandLen {
maxShorthandLen = length
}
flagType, _ := flag.UnquoteUsage(item.flag)
if length := len(flagType); length > maxTypeLen {
maxTypeLen = length
}
}
if maxShorthandLen > 0 {
maxShorthandLen += 3
}
for _, item := range items {
flagType, usage := flag.UnquoteUsage(item.flag)
if len(item.shorthand) > 0 {
fmt.Fprintf(output, fmt.Sprintf(" %%-%ds--%%-%ds %%-%ds %%s", maxShorthandLen, maxNameLen, maxTypeLen), fmt.Sprintf("-%s, ", item.shorthand), item.name, flagType, usage)
} else {
fmt.Fprintf(output, fmt.Sprintf(" %%-%ds--%%-%ds %%-%ds %%s", maxShorthandLen, maxNameLen, maxTypeLen), "", item.name, flagType, usage)
}
if defaultValue := item.flag.DefValue; len(defaultValue) > 0 {
if flagType == "string" {
fmt.Fprintf(output, " (default %q)", defaultValue)
} else {
fmt.Fprintf(output, " (default %v)", defaultValue)
}
}
fmt.Fprint(output, "\n")
}
}
}