-
Notifications
You must be signed in to change notification settings - Fork 0
/
cmd.go
191 lines (166 loc) · 4.27 KB
/
cmd.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
// Copyright 2017 Ed Marshall. All rights reserved.
// Use of this source code is governed by a GPL-style
// license that can be found in the LICENSE file.
package cmdr
import (
"flag"
"fmt"
"sort"
)
// Command defines a standard interface for retrieving a flagset for a
// subcommand, for running the command (if it matches), and for retrieving
// help text.
type Command interface {
// FlagSet returns a fully-populated flag set for the subcommand.
FlagSet() *flag.FlagSet
// Run is called with the remaining list of arguments after parsing
// the flag set, and performs the action tied to the command. An
// error can be returned if something goes wrong, which will be
// presented to the user.
Run([]string) error
// Help returns a one-line description of what this command does.
Help() string
// PositionalArguments returns an ordered array of any positional
// arguments that the command requires.
PositionalArguments() []Argument
}
// Argument defines a single positional argument
type Argument struct {
Name string
Description string
DefValue string
Optional bool
}
func (arg *Argument) String() string {
if arg.Optional {
return fmt.Sprintf("[%s]", arg.Name)
}
return fmt.Sprintf("%s", arg.Name)
}
// Global is our global flagset.
var Global = flag.NewFlagSet("_global", flag.ExitOnError)
// Commands are all defined subcommands and their flagsets.
var Commands = map[string]Command{}
// Help displays either a partial or full help text for our command
// and all subcommands.
func Help(full bool) error {
flag.Usage()
names := make([]string, len(Commands))
i := 0
for k := range Commands {
names[i] = k
i++
}
sort.Strings(names)
Global.PrintDefaults()
fmt.Println("\nSubcommands:")
for _, name := range names {
pArgs := Commands[name].PositionalArguments()
if full {
fmt.Printf("\n%s - %s\n", name, Commands[name].Help())
Commands[name].FlagSet().PrintDefaults()
if pArgs != nil {
for _, arg := range pArgs {
out := " " + arg.String()
if len(out) < 4 {
out += "\t"
} else {
out += "\n \t"
}
out += arg.Description
if !arg.Optional || arg.DefValue != "" {
out += " ("
if arg.DefValue != "" {
out += "default \"" + arg.DefValue + "\""
}
if !arg.Optional {
if arg.DefValue != "" {
out += ", "
}
out += "required"
}
out += ")"
}
fmt.Println(out)
}
}
} else {
out := " " + name
Commands[name].FlagSet().VisitAll(func(f *flag.Flag) {
out += " [-" + f.Name
name, _ := flag.UnquoteUsage(f)
if name != "" {
out += " " + name
}
out += "]"
})
if pArgs != nil {
for _, arg := range pArgs {
out += " " + arg.String()
}
}
out += "\n \t" + Commands[name].Help()
fmt.Println(out)
}
}
if len(Variables) > 0 {
out := "\nEnvironment variables:"
if full {
out += "\n"
}
for name, action := range Variables {
out += "\n " + name + "\n \t" + action.Help()
}
fmt.Println(out)
}
return nil
}
// ParsedCommand represents a post-parsed state for a command line.
type ParsedCommand struct {
args []string
cmd func([]string) error
}
// Run proxies to the Run() of the parsed command.
func (pc *ParsedCommand) Run() error {
return pc.cmd(pc.args)
}
// Parse takes a list of command-line arguments (typically os.Args), parses the
// global arguments, then checks to see if there is a subcommand to execute.
func Parse(args []string) *ParsedCommand {
ParseEnvironment()
var shortHelp bool
Global.BoolVar(&shortHelp, "help", false, "display this help and exit")
var longHelp bool
Global.BoolVar(&longHelp, "long-help", false, "display long-form help and exit")
if err := Global.Parse(args[1:]); err != nil {
panic(err)
}
args = Global.Args()
if longHelp {
return &ParsedCommand{
cmd: func(args []string) error {
return Help(true)
},
}
}
if shortHelp || len(args) < 1 {
return &ParsedCommand{
cmd: func(args []string) error {
return Help(false)
},
}
}
if cmd, ok := Commands[args[0]]; ok {
fs := cmd.FlagSet()
fs.Parse(args[1:])
return &ParsedCommand{
args: fs.Args(),
cmd: cmd.Run,
}
}
return &ParsedCommand{
cmd: func(_ []string) error {
return fmt.Errorf("No such subcommand: %s", args[0])
},
}
}