-
Notifications
You must be signed in to change notification settings - Fork 0
/
help.go
135 lines (102 loc) · 2.18 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
package cli
import (
"bytes"
"fmt"
"nikand.dev/go/cli/flag"
"tlog.app/go/errors"
)
var HelpFlag = &Flag{
Name: "help,h",
Usage: "=[hidden]",
Description: "print command help end exit",
Action: defaultHelp,
}
func defaultHelp(f *Flag, arg string, args []string) (rest []string, err error) {
c := f.CurrentCommand.(*Command)
_, v, rest, err := flag.ParseArg(arg, args, false, true)
if err != nil {
return
}
hidden := v == "hidden"
b := new(bytes.Buffer)
// full := FullName(c.Parent)
// if full != nil {
// fmt.Fprintf(b, "%s ", strings.Join(full, " "))
// }
fmt.Fprintf(b, "%s", c.Name)
if c.Usage != "" {
fmt.Fprintf(b, " %s", c.Usage)
} else if c.Args != nil {
fmt.Fprintf(b, " [flags_and_args]")
} else {
fmt.Fprintf(b, " [flags]")
}
if c.Description != "" {
fmt.Fprintf(b, " - %s", c.Description)
}
fmt.Fprintf(b, "\n")
if c.Help != "" {
fmt.Fprintf(b, "\n%s\n", c.Help)
}
if len(c.Commands) != 0 {
cnt := 0
for _, sub := range c.Commands {
if sub.Hidden && !hidden {
continue
}
cnt++
}
if cnt != 0 {
fmt.Fprintf(b, "\nSubcommands\n")
}
for _, sub := range c.Commands {
if sub.Hidden && !hidden {
continue
}
fmt.Fprintf(b, " %-20s", sub.Name)
if sub.Description != "" {
fmt.Fprintf(b, " - %s", sub.Description)
}
fmt.Fprintf(b, "\n")
}
}
for cc := c; cc != nil; cc = cc.Parent {
cnt := 0
for _, f := range cc.Flags {
if f.Hidden && !hidden || cc != c && f.Local {
continue
}
cnt++
}
if cnt == 0 {
continue
}
if cc == c {
fmt.Fprintf(b, "\nFlags\n")
} else {
fmt.Fprintf(b, "\nFlags of parent command %v\n", cc.MainName())
}
for _, f := range cc.Flags {
if f.Hidden && !hidden || cc != c && f.Local {
continue
}
name := f.Name
if f.Usage != "" {
name += f.Usage
}
fmt.Fprintf(b, " %-20s", name)
if f.Description != "" {
fmt.Fprintf(b, " - %s", f.Description)
}
if f.Value != nil && f.Value != "" {
fmt.Fprintf(b, " (default %v)", f.Value)
}
fmt.Fprintf(b, "\n")
}
}
_, err = b.WriteTo(c.Stdout)
if err != nil {
return nil, errors.Wrap(err, "write")
}
return nil, ErrExit
}