forked from perkeep/perkeep
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cmdmain.go
270 lines (236 loc) · 5.96 KB
/
cmdmain.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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
/*
Copyright 2013 The Camlistore Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cmdmain
import (
"flag"
"fmt"
"io"
"log"
"os"
"path/filepath"
"sort"
"camlistore.org/pkg/buildinfo"
)
var (
FlagVersion = flag.Bool("version", false, "show version")
FlagHelp = flag.Bool("help", false, "print usage")
FlagVerbose = flag.Bool("verbose", false, "extra debug logging")
)
var (
// ExtraFlagRegistration allows to add more flags from
// other packages (with AddFlags) when Main starts.
ExtraFlagRegistration = func() {}
// PreExit is meant to dump additional stats and other
// verbiage before Main terminates.
PreExit = func() {}
// ExitWithFailure determines whether the command exits
// with a non-zero exit status.
ExitWithFailure bool
)
var ErrUsage = UsageError("invalid command")
type UsageError string
func (ue UsageError) Error() string {
return "Usage error: " + string(ue)
}
var (
// mode name to actual subcommand mapping
modeCommand = make(map[string]CommandRunner)
modeFlags = make(map[string]*flag.FlagSet)
// Indirections for replacement by tests
Stderr io.Writer = os.Stderr
Stdout io.Writer = os.Stdout
Stdin io.Reader = os.Stdin
Exit = realExit
// TODO: abstract out vfs operation. should never call os.Stat, os.Open, os.Create, etc.
// Only use fs.Stat, fs.Open, where vs is an interface type.
// TODO: switch from using the global flag FlagSet and use our own. right now
// running "go test -v" dumps the flag usage data to the global stderr.
)
func realExit(code int) {
os.Exit(code)
}
// CommandRunner is the type that a command mode should implement.
type CommandRunner interface {
Usage()
RunCommand(args []string) error
}
type exampler interface {
Examples() []string
}
type describer interface {
Describe() string
}
// RegisterCommand adds a mode to the list of modes for the main command.
// It is meant to be called in init() for each subcommand.
func RegisterCommand(mode string, makeCmd func(Flags *flag.FlagSet) CommandRunner) {
if _, dup := modeCommand[mode]; dup {
log.Fatalf("duplicate command %q registered", mode)
}
flags := flag.NewFlagSet(mode+" options", flag.ContinueOnError)
flags.Usage = func() {}
modeFlags[mode] = flags
modeCommand[mode] = makeCmd(flags)
}
type namedMode struct {
Name string
Command CommandRunner
}
// TODO(mpl): do we actually need this? I changed usage
// to simply iterate over all of modeCommand and it seems
// fine.
func allModes(startModes []string) <-chan namedMode {
ch := make(chan namedMode)
go func() {
defer close(ch)
done := map[string]bool{}
for _, name := range startModes {
done[name] = true
cmd := modeCommand[name]
if cmd == nil {
panic("bogus mode: " + name)
}
ch <- namedMode{name, cmd}
}
var rest []string
for name := range modeCommand {
if !done[name] {
rest = append(rest, name)
}
}
sort.Strings(rest)
for _, name := range rest {
ch <- namedMode{name, modeCommand[name]}
}
}()
return ch
}
func hasFlags(flags *flag.FlagSet) bool {
any := false
flags.VisitAll(func(*flag.Flag) {
any = true
})
return any
}
// Errorf prints to Stderr
func Errorf(format string, args ...interface{}) {
fmt.Fprintf(Stderr, format, args...)
}
func usage(msg string) {
cmdName := filepath.Base(os.Args[0])
if msg != "" {
Errorf("Error: %v\n", msg)
}
Errorf(`
Usage: ` + cmdName + ` [globalopts] <mode> [commandopts] [commandargs]
Modes:
`)
for mode, cmd := range modeCommand {
if des, ok := cmd.(describer); ok {
Errorf(" %s: %s\n", mode, des.Describe())
}
}
Errorf("\nExamples:\n")
for mode, cmd := range modeCommand {
if ex, ok := cmd.(exampler); ok {
Errorf("\n")
for _, example := range ex.Examples() {
Errorf(" %s %s %s\n", cmdName, mode, example)
}
}
}
Errorf(`
For mode-specific help:
` + cmdName + ` <mode> -help
Global options:
`)
flag.PrintDefaults()
Exit(1)
}
func help(mode string) {
cmdName := os.Args[0]
// We can skip all the checks as they're done in Main
cmd := modeCommand[mode]
cmdFlags := modeFlags[mode]
if des, ok := cmd.(describer); ok {
Errorf("%s\n", des.Describe())
}
Errorf("\n")
cmd.Usage()
if hasFlags(cmdFlags) {
cmdFlags.PrintDefaults()
}
if ex, ok := cmd.(exampler); ok {
Errorf("\nExamples:\n")
for _, example := range ex.Examples() {
Errorf(" %s %s %s\n", cmdName, mode, example)
}
}
}
// Main is meant to be the core of a command that has
// subcommands (modes), such as camput or camtool.
func Main() {
ExtraFlagRegistration()
flag.Parse()
args := flag.Args()
if *FlagVersion {
fmt.Fprintf(Stderr, "%s version: %s\n", os.Args[0], buildinfo.Version())
return
}
if *FlagHelp {
usage("")
}
if len(args) == 0 {
usage("No mode given.")
}
mode := args[0]
cmd, ok := modeCommand[mode]
if !ok {
usage(fmt.Sprintf("Unknown mode %q", mode))
}
cmdFlags := modeFlags[mode]
var cmdHelp bool
cmdFlags.BoolVar(&cmdHelp, "help", false, "Help for this mode.")
err := cmdFlags.Parse(args[1:])
if err != nil {
err = ErrUsage
} else {
if cmdHelp {
help(mode)
return
}
err = cmd.RunCommand(cmdFlags.Args())
}
if ue, isUsage := err.(UsageError); isUsage {
if isUsage {
Errorf("%s\n", ue)
}
cmd.Usage()
Errorf("\nGlobal options:\n")
flag.PrintDefaults()
if hasFlags(cmdFlags) {
Errorf("\nMode-specific options for mode %q:\n", mode)
cmdFlags.PrintDefaults()
}
Exit(1)
}
if *FlagVerbose {
PreExit()
}
if err != nil {
if !ExitWithFailure {
// because it was already logged if ExitWithFailure
log.Printf("Error: %v", err)
}
Exit(2)
}
}