-
Notifications
You must be signed in to change notification settings - Fork 0
/
option.go
466 lines (430 loc) · 14.2 KB
/
option.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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
package cli
import (
"errors"
"fmt"
"io"
"slices"
"github.com/FollowTheProcess/cli/internal/flag"
)
// NoShortHand should be passed as the "short" argument to [Flag] if the desired flag
// should be the long hand version only e.g. --count, not -c/--count.
const NoShortHand = flag.NoShortHand
// Flaggable is a type constraint that defines any type capable of being parsed as a command line flag.
//
// It's worth noting that the complete set of supported types is wider than this constraint appears
// as e.g. a [time.Duration] is actually just an int64 underneath, likewise a [net.IP] is actually just []byte.
type Flaggable flag.Flaggable
// Note: this must be a type alias (FlagCount = flag.Count), not a newtype (FlagCount flag.Count)
// otherwise parsing does not work correctly as the flag package does not know how to parse
// a new type declared here.
// FlagCount is a type used for a flag who's job is to increment a counter, e.g. a "verbosity"
// flag may be passed "-vvv" which should increase the verbosity level to 3.
type FlagCount = flag.Count
// Option is a functional option for configuring a [Command].
type Option interface {
// Apply the option to the config, returning an error if the
// option cannot be applied for whatever reason.
apply(*config) error
}
// option is a function adapter implementing the Option interface, analogous
// to http.HandlerFunc.
type option func(*config) error
// apply implements the Option interface for option.
func (o option) apply(cfg *config) error {
return o(cfg)
}
// config represents the internal configuration of a [Command].
type config struct {
stdin io.Reader
stdout io.Writer
stderr io.Writer
run func(cmd *Command, args []string) error
flags *flag.Set
versionFunc func(cmd *Command) error
parent *Command
argValidator ArgValidator
name string
short string
long string
version string
commit string
buildDate string
examples []example
args []string
positionalArgs []positionalArg
subcommands []*Command
helpCalled bool
versionCalled bool
}
// build builds an returns a Command from the config, applying validation
// to the whole thing.
func (c *config) build() *Command {
cmd := &Command{
stdin: c.stdin,
stdout: c.stdout,
stderr: c.stderr,
run: c.run,
flags: c.flags,
versionFunc: c.versionFunc,
parent: c.parent,
argValidator: c.argValidator,
name: c.name,
short: c.short,
long: c.long,
version: c.version,
commit: c.commit,
buildDate: c.buildDate,
examples: c.examples,
args: c.args,
positionalArgs: c.positionalArgs,
subcommands: c.subcommands,
helpCalled: c.helpCalled,
versionCalled: c.versionCalled,
}
// Loop through each subcommand and set this command as their immediate parent
for _, subcommand := range cmd.subcommands {
subcommand.parent = cmd
}
return cmd
}
// Stdin is an [Option] that sets the Stdin for a [Command].
//
// Successive calls will simply overwrite any previous calls. Without this option
// the command will default to [os.Stdin].
//
// // Set stdin to os.Stdin (the default anyway)
// cli.New("test", cli.Stdin(os.Stdin))
func Stdin(stdin io.Reader) Option {
f := func(cfg *config) error {
if stdin == nil {
return errors.New("cannot set Stdin to nil")
}
cfg.stdin = stdin
return nil
}
return option(f)
}
// Stdout is an [Option] that sets the Stdout for a [Command].
//
// Successive calls will simply overwrite any previous calls. Without this option
// the command will default to [os.Stdout].
//
// // Set stdout to a temporary buffer
// buf := &bytes.Buffer{}
// cli.New("test", cli.Stdout(buf))
func Stdout(stdout io.Writer) Option {
f := func(cfg *config) error {
if stdout == nil {
return errors.New("cannot set Stdout to nil")
}
cfg.stdout = stdout
return nil
}
return option(f)
}
// Stderr is an [Option] that sets the Stderr for a [Command].
//
// Successive calls will simply overwrite any previous calls. Without this option
// the command will default to [os.Stderr].
//
// // Set stderr to a temporary buffer
// buf := &bytes.Buffer{}
// cli.New("test", cli.Stderr(buf))
func Stderr(stderr io.Writer) Option {
f := func(cfg *config) error {
if stderr == nil {
return errors.New("cannot set Stderr to nil")
}
cfg.stderr = stderr
return nil
}
return option(f)
}
// Short is an [Option] that sets the one line usage summary for a [Command].
//
// The one line usage will appear in the help text as well as alongside
// subcommands when they are listed.
//
// Successive calls will simply overwrite any previous calls.
//
// cli.New("rm", cli.Short("Delete files and directories"))
func Short(short string) Option {
f := func(cfg *config) error {
if short == "" {
return errors.New("cannot set command short description to an empty string")
}
cfg.short = short
return nil
}
return option(f)
}
// Long is an [Option] that sets the full description for a [Command].
//
// The long description will appear in the help text for a command. Users
// are responsible for wrapping the text at a sensible width.
//
// Successive calls will simply overwrite any previous calls.
//
// cli.New("rm", cli.Long("... lots of text here"))
func Long(long string) Option {
f := func(cfg *config) error {
if long == "" {
return errors.New("cannot set command long description to an empty string")
}
cfg.long = long
return nil
}
return option(f)
}
// Example is an [Option] that adds an example to a [Command].
//
// Examples take the form of an explanatory comment and a command
// showing the command to the CLI, these will show up in the help text.
//
// For example, a program called "myrm" that deletes files and directories
// might have an example declared as follows:
//
// cli.Example("Delete a folder recursively without confirmation", "myrm ./dir --recursive --force")
//
// Which would show up in the help text like so:
//
// Examples:
// # Delete a folder recursively without confirmation
// $ myrm ./dir --recursive --force
//
// An arbitrary number of examples can be added to a [Command], and calls to [Example] are additive.
func Example(comment, command string) Option {
f := func(cfg *config) error {
if comment == "" {
return errors.New("example comment cannot be empty")
}
if command == "" {
return errors.New("example command cannot be empty")
}
cfg.examples = append(cfg.examples, example{comment: comment, command: command})
return nil
}
return option(f)
}
// Run is an [Option] that sets the run function for a [Command].
//
// The run function is the actual implementation of your command i.e. what you
// want it to do when invoked.
//
// Successive calls overwrite previous ones.
func Run(run func(cmd *Command, args []string) error) Option {
f := func(cfg *config) error {
if run == nil {
return errors.New("cannot set Run to nil")
}
cfg.run = run
return nil
}
return option(f)
}
// OverrideArgs is an [Option] that sets the arguments for a [Command], overriding
// any arguments parsed from the command line.
//
// Without this option, the command will default to os.Args[1:], this option is particularly
// useful for testing.
//
// Successive calls override previous ones.
//
// // Override arguments for testing
// cli.New("test", cli.OverrideArgs([]string{"test", "me"}))
func OverrideArgs(args []string) Option {
f := func(cfg *config) error {
if args == nil {
return errors.New("cannot set Args to nil")
}
cfg.args = args
return nil
}
return option(f)
}
// Version is an [Option] that sets the version for a [Command].
//
// Without this option, the command defaults to a version of "dev".
//
// cli.New("test", cli.Version("v1.2.3"))
func Version(version string) Option {
f := func(cfg *config) error {
cfg.version = version
return nil
}
return option(f)
}
// Commit is an [Option] that sets the commit hash for a binary built with CLI. It is particularly
// useful for embedding rich version info into a binary using [ldflags].
//
// Without this option, the commit hash is simply omitted from the version info
// shown when -v/--version is called.
//
// If set to a non empty string, the commit hash will be shown.
//
// cli.New("test", cli.Commit("b43fd2c"))
//
// [ldflags]: https://www.digitalocean.com/community/tutorials/using-ldflags-to-set-version-information-for-go-applications
func Commit(commit string) Option {
f := func(cfg *config) error {
cfg.commit = commit
return nil
}
return option(f)
}
// BuildDate is an [Option] that sets the build date for a binary built with CLI. It is particularly
// useful for embedding rich version info into a binary using [ldflags]
//
// Without this option, the build date is simply omitted from the version info
// shown when -v/--version is called.
//
// If set to a non empty string, the build date will be shown.
//
// cli.New("test", cli.BuildDate("2024-07-06T10:37:30Z"))
//
// [ldflags]: https://www.digitalocean.com/community/tutorials/using-ldflags-to-set-version-information-for-go-applications
func BuildDate(date string) Option {
f := func(cfg *config) error {
cfg.buildDate = date
return nil
}
return option(f)
}
// VersionFunc is an [Option] that allows for a custom implementation of the -v/--version flag.
//
// A [Command] will have a default implementation of this function that prints a default
// format of the version info to [os.Stderr].
//
// This option is particularly useful if you want to inject ldflags in at build time for
// e.g commit hash.
func VersionFunc(fn func(cmd *Command) error) Option {
f := func(cfg *config) error {
if fn == nil {
return errors.New("cannot set VersionFunc to nil")
}
cfg.versionFunc = fn
return nil
}
return option(f)
}
// SubCommands is an [Option] that attaches 1 or more subcommands to the command being configured.
//
// Sub commands must have unique names, any duplicates will result in an error.
//
// This option is additive and can be called as many times as desired, subcommands are
// effectively appended on every call.
func SubCommands(builders ...Builder) Option {
// Note: In Cobra the AddCommand method has to protect against a command adding itself
// as a subcommand, this is impossible in cli due to the functional options pattern, the
// root command will not exist as a variable inside the call to cli.New.
f := func(cfg *config) error {
// Add the subcommands to the command this is being called on
for _, builder := range builders {
subcommand, err := builder()
if err != nil {
return fmt.Errorf("could not build subcommand: %w", err)
}
cfg.subcommands = append(cfg.subcommands, subcommand)
}
// Any duplicates in the list of subcommands (by name) is an error
if name, found := anyDuplicates(cfg.subcommands...); found {
return fmt.Errorf("subcommand %q already defined", name)
}
return nil
}
return option(f)
}
// Allow is an [Option] that allows for validating positional arguments to a [Command].
//
// You provide a validator function that returns an error if it encounters invalid arguments, and it will
// be run for you, passing in the non-flag arguments to the [Command] that was called.
//
// Successive calls overwrite previous ones, use [Combine] to compose multiple validators.
//
// // No positional arguments allowed
// cli.New("test", cli.Allow(cli.NoArgs()))
func Allow(validator ArgValidator) Option {
f := func(cfg *config) error {
if validator == nil {
return errors.New("cannot set Allow to a nil ArgValidator")
}
cfg.argValidator = validator
return nil
}
return option(f)
}
// Flag is an [Option] that adds a flag to a [Command], storing its value in a variable.
//
// The variable is set when the flag is parsed during command execution. The value provided
// in the call to [Flag] is used as the default value.
//
// To add a long flag only (e.g. --delete with no -d option), pass [NoShortHand] for "short".
//
// // Add a force flag
// var force bool
// cli.New("rm", cli.Flag(&force, "force", 'f', false, "Force deletion without confirmation"))
func Flag[T Flaggable](p *T, name string, short rune, value T, usage string) Option {
f := func(cfg *config) error {
if _, ok := cfg.flags.Get(name); ok {
return fmt.Errorf("flag %q already defined", name)
}
f, err := flag.New(p, name, short, value, usage)
if err != nil {
return err
}
if err := flag.AddToSet(cfg.flags, f); err != nil {
return fmt.Errorf("could not add flag %q to command %q: %w", name, cfg.name, err)
}
return nil
}
return option(f)
}
// Arg is an [Option] that adds a named positional argument to a [Command].
//
// A named argument is given a name, description and a default value, a default of ""
// marks the argument as required.
//
// If an argument without a default is provided on the command line, the provided value is used, if
// it doesn't have a default and the value isn't given on the command line, [Command.Execute] will
// return an informative error saying which one is missing.
//
// This is the only [Option] for which the order of calls matter, each call to Arg effectively appends a
// named positional argument so the following:
//
// cli.New("cp", cli.Arg("src", "The file to copy", ""))
// cli.New("cp", cli.Arg("dest", "Where to copy to", ""))
//
// results in a command that will expect the following args *in order*
//
// cp src.txt dest.txt
//
// Arguments added to the command with Arg may be retrieved by name from within command logic with [Command.Arg].
func Arg(name, description, value string) Option {
// TODO(@FollowTheProcess): Not entirely happy with the "" meaning required
// I wonder if we should have Arg and ArgWithDefault?
f := func(cfg *config) error {
arg := positionalArg{
name: name,
description: description,
defaultValue: value,
}
cfg.positionalArgs = append(cfg.positionalArgs, arg)
return nil
}
return option(f)
}
// anyDuplicates checks the list of commands for ones with duplicate names, if a duplicate
// is found, it's name and true are returned, else "", false.
func anyDuplicates(cmds ...*Command) (string, bool) {
seen := make([]string, 0, len(cmds))
for _, cmd := range cmds {
if cmd == nil {
continue
}
if slices.Contains(seen, cmd.name) {
return cmd.name, true
}
seen = append(seen, cmd.name)
}
return "", false
}