forked from cloudfoundry/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
flags_usage.go
106 lines (77 loc) · 1.76 KB
/
flags_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
package flags
import (
"fmt"
"sort"
"strings"
)
func (c *flagContext) ShowUsage(leadingSpace int) string {
displayFlags := flags{}
for _, f := range c.cmdFlags {
if !f.Visible() {
continue
}
d := flagPresenter{
flagSet: f,
}
displayFlags = append(displayFlags, d)
}
return displayFlags.toString(strings.Repeat(" ", leadingSpace))
}
type flagPresenter struct {
flagSet FlagSet
}
func (p *flagPresenter) line(l int) string {
flagList := p.flagList()
usage := p.usage()
spaces := strings.Repeat(" ", 6+(l-len(flagList)))
return strings.TrimRight(fmt.Sprintf("%s%s%s", flagList, spaces, usage), " ")
}
func (p *flagPresenter) flagList() string {
f := p.flagSet
var parts []string
if f.GetName() != "" {
parts = append(parts, fmt.Sprintf("--%s", f.GetName()))
}
if f.GetShortName() != "" {
parts = append(parts, fmt.Sprintf("-%s", f.GetShortName()))
}
return strings.Join(parts, ", ")
}
func (p *flagPresenter) usage() string {
return p.flagSet.String()
}
func (p *flagPresenter) comparableString() string {
if p.flagSet.GetName() != "" {
return p.flagSet.GetName()
}
return p.flagSet.GetShortName()
}
type flags []flagPresenter
func (f flags) Len() int {
return len(f)
}
func (f flags) Less(i, j int) bool {
return (f[i].comparableString() < f[j].comparableString())
}
func (f flags) Swap(i, j int) {
f[i], f[j] = f[j], f[i]
}
func (f flags) toString(prefix string) string {
sort.Sort(f)
lines := make([]string, f.Len())
maxLength := f.maxLineLength()
for i, l := range f {
lines[i] = fmt.Sprintf("%s%s", prefix, l.line(maxLength))
}
return strings.Join(lines, "\n")
}
func (f flags) maxLineLength() int {
var l int
for _, x := range f {
lPrime := len(x.flagList())
if lPrime > l {
l = lPrime
}
}
return l
}