-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.go
361 lines (316 loc) · 9.83 KB
/
app.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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
// Declaratively create heirarchical command line apps.
package warg
import (
"errors"
"fmt"
"log"
"os"
"runtime/debug"
"strings"
"go.bbkane.com/warg/command"
"go.bbkane.com/warg/config"
"go.bbkane.com/warg/flag"
"go.bbkane.com/warg/help"
"go.bbkane.com/warg/path"
"go.bbkane.com/warg/section"
"go.bbkane.com/warg/value"
"go.bbkane.com/warg/value/scalar"
)
// AppOpt let's you customize the app. Most AppOpts panic if incorrectly called
type AppOpt func(*App)
// An App contains your defined sections, commands, and flags
// Create a new App with New()
type App struct {
// Config()
configFlagName flag.Name
newConfigReader config.NewReader
configFlag *flag.Flag
globalFlags flag.FlagMap
// New Help()
name string
helpFlagName flag.Name
// Note that this can be ""
helpFlagAlias flag.Name
helpMappings []help.HelpFlagMapping
// rootSection holds the good stuff!
rootSection section.SectionT
skipValidation bool
version string
}
// OverrideHelpFlag customizes your --help. If you write a custom --help function, you'll want to add it to your app here!
func OverrideHelpFlag(
mappings []help.HelpFlagMapping,
defaultChoice string,
flagName flag.Name,
flagHelp flag.HelpShort,
flagOpts ...flag.FlagOpt,
) AppOpt {
return func(a *App) {
if !strings.HasPrefix(string(flagName), "-") {
log.Panicf("flagName should start with '-': %#v\n", flagName)
}
if _, alreadyThere := a.globalFlags[flagName]; alreadyThere {
log.Panicf("flag already exists: %#v\n", flagName)
}
defaultFound := false
helpValues := make([]string, len(mappings))
for i := range mappings {
helpValues[i] = mappings[i].Name
if helpValues[i] == defaultChoice {
defaultFound = true
}
}
if !defaultFound {
panic(fmt.Sprintf("default (%#v) not found in helpValues (%#v)", defaultChoice, helpValues))
}
helpFlag := flag.New(
flagHelp,
scalar.String(
scalar.Choices(helpValues...),
scalar.Default(defaultChoice),
),
flagOpts...,
)
a.globalFlags[flagName] = helpFlag
// This is used in parsing, so no need to strongly type it
a.helpFlagName = flagName
a.helpFlagAlias = helpFlag.Alias
a.helpMappings = mappings
}
}
// OverrideVersion lets you set a custom version string. The default is read from debug.BuildInfo
func OverrideVersion(version string) AppOpt {
return func(a *App) {
a.version = version
}
}
// ExistingGlobalFlag adds an existing flag to a Command. It panics if a flag with the same name exists
func ExistingGlobalFlag(name flag.Name, value flag.Flag) AppOpt {
return func(com *App) {
com.globalFlags.AddFlag(name, value)
}
}
// ExistingGlobalFlags adds existing flags to a Command. It panics if a flag with the same name exists
func ExistingGlobalFlags(flagMap flag.FlagMap) AppOpt {
return func(com *App) {
com.globalFlags.AddFlags(flagMap)
}
}
// GlobalFlag adds a flag to the app. It panics if a flag with the same name exists
func GlobalFlag(name flag.Name, helpShort flag.HelpShort, empty value.EmptyConstructor, opts ...flag.FlagOpt) AppOpt {
return ExistingGlobalFlag(name, flag.New(helpShort, empty, opts...))
}
// Use ConfigFlag in conjunction with flag.ConfigPath to allow users to override flag defaults with values from a config.
// This flag will be parsed and any resulting config will be read before other flag value sources.
func ConfigFlag(
// TODO: put the new stuff at the front to be consistent with OverrideHelpFlag
configFlagName flag.Name,
// TODO: can I make this nicer?
scalarOpts []scalar.ScalarOpt[path.Path],
newConfigReader config.NewReader,
helpShort flag.HelpShort,
flagOpts ...flag.FlagOpt,
) AppOpt {
return func(app *App) {
app.configFlagName = configFlagName
app.newConfigReader = newConfigReader
// TODO: need to have value opts here
configFlag := flag.New(helpShort, scalar.Path(scalarOpts...), flagOpts...)
app.configFlag = &configFlag
}
}
// SkipValidation skips (most of) the app's internal consistency checks when the app is created.
// If used, make sure to call app.Validate() in a test!
func SkipValidation() AppOpt {
return func(a *App) {
a.skipValidation = true
}
}
func debugBuildInfoVersion() string {
// If installed via `go install`, we'll be able to read runtime version info
info, ok := debug.ReadBuildInfo()
if !ok {
// This shouldn't happen with modern versions of Go
// unless someone strips the binary, and I don't support that
panic("unable to read build info")
}
// when run with `go run`, this will return "(devel)"
return info.Main.Version
}
// ColorFlag returns a flag indicating whether use user wants colored output.
// By convention, if this flag is named "--color", it will be respected by the different help commands. Usage:
//
// section.ExistingFlag("--color", warg.ColorFlag()),
func ColorFlag() flag.Flag {
return flag.New(
"Use ANSI colors",
scalar.String(
scalar.Choices("true", "false", "auto"),
scalar.Default("auto"),
),
)
}
func VersionCommand() command.Command {
return command.New(
"Print version",
func(ctx command.Context) error {
fmt.Fprintln(ctx.Stdout, ctx.Version)
return nil
},
)
}
// New builds a new App!
func New(name string, rootSection section.SectionT, opts ...AppOpt) App {
app := App{
name: name,
rootSection: rootSection,
configFlagName: "",
newConfigReader: nil,
configFlag: nil,
helpFlagName: "",
helpFlagAlias: "",
helpMappings: nil,
skipValidation: false,
version: "",
globalFlags: make(flag.FlagMap),
}
for _, opt := range opts {
opt(&app)
}
if app.helpFlagName == "" {
OverrideHelpFlag(
help.BuiltinHelpFlagMappings(),
"default",
"--help",
"Print help",
flag.Alias("-h"),
)(&app)
}
if app.version == "" {
OverrideVersion(debugBuildInfoVersion())(&app)
}
// validate or not and return
if app.skipValidation {
return app
}
err := app.Validate()
if err != nil {
panic(err)
}
return app
}
// MustRun runs the app.
// Any flag parsing errors will be printed to stderr and os.Exit(64) (EX_USAGE) will be called.
// Any errors on an Action will be printed to stderr and os.Exit(1) will be called.
func (app *App) MustRun(opts ...ParseOpt) {
pr, err := app.Parse(opts...)
if err != nil {
fmt.Fprintln(os.Stderr, err)
// https://unix.stackexchange.com/a/254747/185953
os.Exit(64)
}
err = pr.Action(pr.Context)
if err != nil {
fmt.Fprintln(pr.Context.Stderr, err)
os.Exit(1)
}
}
// Look up keys (meant for environment variable parsing) - fulfillable with os.LookupEnv or warg.LookupMap(map)
type LookupFunc func(key string) (string, bool)
// LookupMap loooks up keys from a provided map. Useful to mock os.LookupEnv when parsing
func LookupMap(m map[string]string) LookupFunc {
return func(key string) (string, bool) {
val, exists := m[key]
return val, exists
}
}
// validateFlags2 checks that global and command flag names and aliases start with "-" and are unique.
// It does not need to check the following scenarios:
//
// - global flag names don't collide with global flag names (app will panic when adding the second global flag) - TOOD: ensure there's a test for this
// - command flag names in the same command don't collide with each other (app will panic when adding the second command flag) TODO: ensure there's a test for this
// - command flag names/aliases don't collide with command flag names/aliases in other commands (since only one command will be run, this is not a problem)
func validateFlags2(
globalFlags flag.FlagMap,
comFlags flag.FlagMap,
) error {
nameCount := make(map[flag.Name]int)
for name, fl := range globalFlags {
nameCount[name]++
if fl.Alias != "" {
nameCount[fl.Alias]++
}
}
for name, fl := range comFlags {
nameCount[name]++
if fl.Alias != "" {
nameCount[fl.Alias]++
}
}
var errs []error
for name, count := range nameCount {
if !strings.HasPrefix(string(name), "-") {
errs = append(errs, fmt.Errorf("flag and alias names must start with '-': %#v", name))
}
if count > 1 {
errs = append(errs, fmt.Errorf("flag or alias name exists %d times: %v", count, name))
}
}
return errors.Join(errs...)
}
// Validate checks app for creation errors. It checks:
//
// - Sections and commands don't start with "-" (needed for parsing)
//
// - Flag names and aliases do start with "-" (needed for parsing)
//
// - Flag names and aliases don't collide
func (app *App) Validate() error {
// NOTE: we need to be able to validate before we parse, and we may not know the app name
// till after prsing so set the root path to "root"
rootPath := []section.Name{section.Name(app.name)}
it := app.rootSection.BreadthFirst(rootPath)
for it.HasNext() {
flatSec := it.Next()
// Sections don't start with "-"
secName := flatSec.Path[len(flatSec.Path)-1]
if strings.HasPrefix(string(secName), "-") {
return fmt.Errorf("section names must not start with '-': %#v", secName)
}
// Sections must not be leaf nodes
if flatSec.Sec.Sections.Empty() && flatSec.Sec.Commands.Empty() {
return fmt.Errorf("sections must have either child sections or child commands: %#v", secName)
}
{
// child section names should not clash with child command names
nameCount := make(map[string]int)
for name := range flatSec.Sec.Commands {
nameCount[string(name)]++
}
for name := range flatSec.Sec.Sections {
nameCount[string(name)]++
}
errs := []error{}
for name, count := range nameCount {
if count > 1 {
errs = append(errs, fmt.Errorf("command and section name clash: %s", name))
}
}
err := errors.Join(errs...)
if err != nil {
return fmt.Errorf("name collision: %w", err)
}
}
for name, com := range flatSec.Sec.Commands {
// Commands must not start wtih "-"
if strings.HasPrefix(string(name), "-") {
return fmt.Errorf("command names must not start with '-': %#v", name)
}
err := validateFlags2(app.globalFlags, com.Flags)
if err != nil {
return err
}
}
}
return nil
}