Repository navigation
Expand file tree
/
Copy pathcommand.go
More file actions
876 lines (770 loc) · 28.2 KB
/
Copy pathcommand.go
File metadata and controls
876 lines (770 loc) · 28.2 KB
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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
package laravel
import (
"cmp"
"context"
"errors"
"flag"
"fmt"
"io"
"log/slog"
"os"
"os/signal"
"path/filepath"
"reflect"
"slices"
"strconv"
"strings"
"syscall"
"time"
"go.laravel.com/config"
"go.laravel.com/console"
"go.laravel.com/db"
"go.laravel.com/internal/callsite"
"go.laravel.com/internal/scope"
"go.laravel.com/internal/terminal"
"go.laravel.com/internal/values"
"go.laravel.com/web"
)
// Run builds an [App] from options and executes the command named on the
// command line, as [App.Run] does. It is the standard entry point for main:
//
// func main() {
// laravel.Run(bootstrap.Options())
// }
//
// Run closes the application after the command finishes, flushing any pending
// trace spans. If building the application or running the command fails, Run
// prints the error to stderr and exits with status 1 (or status 2 for invalid
// CLI usage). A command that returns a [*console.ExitError] exits with its
// status code, and a command interrupted by a signal exits with status 130.
func Run(options Options) {
app, err := New(options)
if err == nil {
err = app.Run(context.Background())
_ = app.Close()
}
if err == nil {
return
}
code := 1
if exit, ok := errors.AsType[*console.ExitError](err); ok {
code, err = exit.Code, exit.Err
}
if err != nil {
console.New(nil, os.Stdout, os.Stderr).Error(err.Error())
}
if panicked, ok := errors.AsType[*web.PanicError](err); ok {
_, _ = os.Stderr.Write(panicked.Stack)
}
os.Exit(code)
}
// Run parses [os.Args] and executes the requested command. When no command is
// given, it runs serve until ctx is canceled or the process receives SIGINT or
// SIGTERM.
//
// On SIGINT or SIGTERM, Run cancels the command's context so the command can
// finish in-flight work and return cleanly. A second signal terminates the
// process immediately.
//
// Run installs the application's logger as the default [slog] logger and
// exports .env variables into the process environment, so call it from main
// before starting other goroutines.
func (a *App) Run(ctx context.Context) error {
slog.SetDefault(a.kernel.Logger)
ctx = db.TrackWrites(ctx)
if err := config.ReadEnv(a.root).Export(); err != nil {
return err
}
return a.run(ctx, filepath.Base(os.Args[0]), os.Args[1:], console.New(os.Stdin, os.Stdout, os.Stderr))
}
// Call runs a command with explicit arguments (such as "migrate", "--force")
// using c for console I/O and returns the command's error. When args is empty,
// Call runs serve just as [App.Run] does. Unlike [App.Run], Call does not
// install signal handlers, so the command stops only when ctx is canceled.
func (a *App) Call(ctx context.Context, c *console.Console, args ...string) error {
return a.call(ctx, filepath.Base(os.Args[0]), args, c, false)
}
func (a *App) run(ctx context.Context, program string, args []string, c *console.Console) error {
return a.call(ctx, program, args, c, true)
}
// listen returns the command's context, which ends when the process gets
// SIGINT or SIGTERM, unless the command traps it. A second signal ends the
// process at once. The signals the command traps reach c.Signals. stop
// stops listening.
func (a *App) listen(ctx context.Context, command Command, c *console.Console) (signalled context.Context, stop func()) {
var trapped []os.Signal
if trapping, ok := command.(interface{ Signals() []os.Signal }); ok {
trapped = trapping.Signals()
}
stopping := slices.DeleteFunc([]os.Signal{os.Interrupt, syscall.SIGTERM}, func(s os.Signal) bool {
return slices.Contains(trapped, s)
})
signalled, cancel := context.WithCancel(ctx)
stop = cancel
if len(stopping) > 0 {
var release context.CancelFunc
signalled, release = signal.NotifyContext(ctx, stopping...)
// Once the first signal ends the context, a second ends the process.
context.AfterFunc(signalled, release)
stop = release
}
if len(trapped) > 0 {
received := make(chan os.Signal, 8)
signal.Notify(received, trapped...)
c.Signals = received
release := stop
stop = func() {
signal.Stop(received)
release()
}
}
return signalled, stop
}
// errInterrupted is a command that stopped because the process was told to
// stop. It exits with status 130 and prints nothing more.
var errInterrupted = console.Exit(130)
// call runs a command line. With listen, the command's context ends when
// the process gets SIGINT or SIGTERM, unless the command traps them, and
// the signals it traps reach c.Signals.
func (a *App) call(ctx context.Context, program string, args []string, c *console.Console, listen bool) (err error) {
ctx = a.Context(ctx)
name, args := commandName(args)
command := find(a.commands(program), name)
if command == nil {
return unknownCommand(program, name)
}
// Each run sets the options on a copy, so one run's options don't
// stay for the next, and tests may run a command at the same time.
command = fresh(command)
flags, global := declare(command)
rest, help, err := parse(program, command, flags, args)
if err != nil {
return err
}
switch {
case global.quiet && global.verbose > 0:
return rejectArguments(program, command, "argument `--quiet` can't be used with `--verbose`")
case global.quiet:
c.Verbosity = console.Quiet
case global.verbose > 0:
c.Verbosity = min(console.Verbosity(global.verbose), console.Debug)
}
if help {
_, err := io.WriteString(c.Stdout(), commandHelp(program, command, flags, terminal.Detect(c.Stdout()))+"\n")
return err
}
if global.noInteraction {
c.Input = nil
}
c.Args = rest
parent := ctx
if listen {
signalled, stop := a.listen(parent, command, c)
defer stop()
ctx = signalled
}
if !isLongRunning(command) {
ctx = values.WithEntry(ctx, slog.String("command", command.Name()))
}
var (
tickHost Host
stopTicks chan struct{}
ticking <-chan struct{}
)
if isLongRunning(command) && withTicks(command) {
tickHost = Host{Kind: HostCommand, Command: command.Name()}
ctx = withHost(ctx, tickHost)
stopTicks = make(chan struct{})
ticking = a.startTicks(stopTicks, tickHost)
}
started := time.Now()
ctx, span := a.startCommandSpan(ctx, command)
// A panic becomes a *web.PanicError, so it's reported and exits with
// status 1, as a returned error does.
err = runRecovered(ctx, func(ctx context.Context) error { return command.Run(ctx, c) })
if mistake, ok := errors.AsType[*console.UsageError](err); ok {
err = rejectArguments(program, command, "%s", mistake.Error())
}
if listen && errors.Is(err, context.Canceled) && ctx.Err() != nil && parent.Err() == nil {
err = errInterrupted
}
if stopTicks != nil {
close(stopTicks)
a.finishTicks(ctx, ticking, tickHost, c.Warnf)
} else {
a.waitForBackground(ctx, c.Warnf)
}
a.finishCommand(ctx, command, err, started)
endCommandSpan(span, err)
return err
}
// commandName returns the command that args name and the args without its
// name. The name is the first argument that isn't an option, or help when
// -h comes first. Before it, only the options every command accepts may
// come, so args that name no command, or give the command's own option or
// -- first, run serve.
func commandName(args []string) (name string, rest []string) {
for i, arg := range args {
if isHelp(arg) || !strings.HasPrefix(arg, "-") {
if isHelp(arg) {
arg = "help"
}
return arg, slices.Concat(args[:i], args[i+1:])
}
if option, _, _ := splitOption(arg); !isGlobal(option) {
break
}
}
return "serve", args
}
// printedKey marks the context of a command's failure report, whose error
// the console prints too, so the stderr and stdout log channels leave out
// the report's log line.
type printedKey struct{}
// finishCommand reports the command's failure and logs that the command
// finished, with its exit code and duration. A command that chose its exit
// status with a [console.ExitError], or that stopped because its context
// ended, didn't fail, so it isn't reported. A failure other than a panic is
// located where Run is declared.
func (a *App) finishCommand(ctx context.Context, command Command, err error, started time.Time) {
_, chose := errors.AsType[*console.ExitError](err)
stopped := ctx.Err() != nil && (errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded))
if err != nil && !chose && !stopped {
var attrs []any
if _, panicked := errors.AsType[*web.PanicError](err); !panicked {
if at := callsite.Method(reflect.TypeOf(command), "Run"); at != "" {
attrs = append(attrs, "location", at)
}
}
scope.Get[interface {
ReportFailure(ctx context.Context, err error, attrs ...any)
}](ctx, "laravel.App.Call").ReportFailure(context.WithValue(ctx, printedKey{}, true), err, attrs...)
}
a.kernel.Logger.DebugContext(ctx, "command finished",
"exit_code", exitCode(err),
"duration_ms", float64(time.Since(started).Microseconds())/1000,
)
}
// exitCode returns the status a command that returned err exits with.
func exitCode(err error) int {
if exit, ok := errors.AsType[*console.ExitError](err); ok {
return exit.Code
}
if err != nil {
return 1
}
return 0
}
// Command defines a CLI command invoked by name, like migrate. Register custom
// commands in [Options.Commands]:
//
// // PrunePosts deletes stale drafts.
// type PrunePosts struct {
// days int
// }
//
// func (*PrunePosts) Name() string { return "posts:prune" }
// func (*PrunePosts) Description() string { return "Delete drafts that nobody has edited in a while" }
//
// func (p *PrunePosts) Flags(flags *flag.FlagSet) {
// flags.IntVar(&p.days, "days", 30, "Delete drafts last edited more than this many `days` ago")
// }
//
// func (p *PrunePosts) Run(ctx context.Context, c *console.Console) error {
// deleted, err := db.Table("posts").WhereNull("published_at").
// Where("updated_at", "<", time.Now().AddDate(0, 0, -p.days)).Delete(ctx)
// c.Successf("Deleted %d drafts.", deleted)
//
// return err
// }
//
// Commands can opt into additional behavior by implementing optional methods:
//
// - Flags(flags *flag.FlagSet) declares CLI flags, usually bound to struct
// fields. Laravel parses them before Run, includes them in help output,
// and exits with status 2 on invalid flags. Every command reserves -q, -v,
// -vv, -vvv, -n, and -h, so do not declare flags with those names.
// - Arguments() []Argument describes positional arguments, which Run reads
// from [console.Console.Args]. Commands without this method accept no
// positional arguments.
// - Signals() []os.Signal traps the listed signals and delivers them on
// [console.Console.Signals] instead of canceling the command's context. A
// command that traps SIGINT or SIGTERM controls its own shutdown, even on
// a second Ctrl+C.
// - LongRunning() bool returning true omits the root trace span so
// long-lived workers do not create a single span lasting the lifetime of
// the process.
// - WithTicks() bool returning true (on a LongRunning command) runs the
// application's [Tick] tasks while the command executes, with
// [HostCommand] as the process host.
// - Aliases() []string lists alternate names for invoking the command, such
// as publish for posts:publish, which also appear in help output.
//
// When a Command is a pointer to a struct, Laravel runs each invocation on a
// fresh copy so flag values from one run never leak into the next.
type Command interface {
// Name returns the CLI command name, such as posts:prune. A colon groups
// commands with the same prefix in the list output.
Name() string
// Description returns the one-line summary shown in list and at the top of
// the command's help output.
Description() string
// Run executes the command. Its context is canceled when the process
// receives SIGINT or SIGTERM. Returning an error prints it and exits with
// status 1, except for [*console.ExitError] (which exits with its code),
// [*console.UsageError] (which also prints the command's usage and exits
// with status 2), and context cancellation caused by a signal (which
// exits with status 130 without printing).
Run(ctx context.Context, c *console.Console) error
}
// Argument describes a positional argument declared by a [Command]'s
// Arguments method.
type Argument struct {
// Name is the argument's placeholder name in help output, such as ID.
Name string
// Description explains what the argument represents.
Description string
// Required causes command parsing to fail when the caller omits the
// argument.
Required bool
// Many allows the final argument to accept one or more values, such as a
// list of IDs.
Many bool
}
type flagged interface {
Flags(flags *flag.FlagSet)
}
type withArguments interface {
Arguments() []Argument
}
// arguments returns the arguments the command describes.
func arguments(c Command) []Argument {
if described, ok := c.(withArguments); ok {
return described.Arguments()
}
return nil
}
// fresh returns a copy of the command when it is a pointer to a struct.
func fresh(c Command) Command {
v := reflect.ValueOf(c)
if v.Kind() != reflect.Pointer || v.IsNil() || v.Elem().Kind() != reflect.Struct {
return c
}
copied := reflect.New(v.Elem().Type())
copied.Elem().Set(v.Elem())
return copied.Interface().(Command)
}
// globalOptions are the options every command accepts.
type globalOptions struct {
quiet, noInteraction bool
// verbose counts the -v options, so -vv is 2.
verbose int
}
// A counterFlag is a bool option that counts each time it's given, by its
// step, as -v counts 1 and -vv counts 2.
type counterFlag struct {
n *int
step int
}
func (f counterFlag) String() string { return "" }
func (f counterFlag) IsBoolFlag() bool { return true }
// Set counts a bare or true option by the flag's step, and takes a number,
// as in --verbose=2, as the level itself.
func (f counterFlag) Set(value string) error {
if given, err := strconv.ParseBool(value); err == nil {
if given {
*f.n += f.step
}
return nil
}
level, err := strconv.Atoi(value)
if err != nil || level < 0 || level > 3 {
return errors.New("give no value, or a level from 0 to 3")
}
*f.n = level
return nil
}
// global are the names of the options every command accepts, which help
// lists apart from the command's own.
var global = []struct{ short, long, help string }{
{"q", "quiet", "Show errors only"},
{"v", "verbose", "Increase output detail (-v, -vv, -vvv)"},
{"n", "no-interaction", "Use prompt defaults without asking questions"},
{"h", "help", "Print help"},
}
func isGlobal(name string) bool {
return name == "vv" || name == "vvv" ||
slices.ContainsFunc(global, func(g struct{ short, long, help string }) bool { return g.short == name || g.long == name })
}
// declare returns the flag set with the command's options and the options
// every command accepts.
func declare(c Command) (*flag.FlagSet, *globalOptions) {
flags := flag.NewFlagSet(c.Name(), flag.ContinueOnError)
flags.SetOutput(io.Discard)
if declared, ok := c.(flagged); ok {
declared.Flags(flags)
}
options := &globalOptions{}
for _, name := range []string{"q", "quiet"} {
flags.BoolVar(&options.quiet, name, false, "")
}
for name, step := range map[string]int{"v": 1, "verbose": 1, "vv": 2, "vvv": 3} {
flags.Var(counterFlag{&options.verbose, step}, name, "")
}
for _, name := range []string{"n", "no-interaction"} {
flags.BoolVar(&options.noInteraction, name, false, "")
}
return flags, options
}
// checkFlags reports a command whose options can't be declared, or that
// declares one that every command has.
func checkFlags(c Command, from string) (err error) {
if _, ok := c.(flagged); !ok {
return nil
}
defer func() {
if recovered := recover(); recovered != nil {
err = fmt.Errorf("laravel: the options of the command %s from %s can't be declared: %v", c.Name(), from, recovered)
}
}()
flags := flag.NewFlagSet(c.Name(), flag.ContinueOnError)
flags.SetOutput(io.Discard)
fresh(c).(flagged).Flags(flags)
var errs []error
flags.VisitAll(func(f *flag.Flag) {
if isGlobal(f.Name) {
errs = append(errs, fmt.Errorf("laravel: the command %s from %s has the option %s, which every command has: give it another name", c.Name(), from, optionName(f.Name)))
}
})
return errors.Join(errs...)
}
// optionName returns an option as the command line writes it: -f for a
// one-letter option, and --force for the others.
func optionName(name string) string {
if len(name) == 1 {
return "-" + name
}
return "--" + name
}
// checkCommands returns the commands of the packages and the application,
// with the application's in place of a package's of the same name. The
// error names each command that can't be added.
func checkCommands(packages, application []Command, builtIn []Command) ([]Command, error) {
var commands []Command
add := func(from string, c Command, replace bool) error {
if c == nil {
return fmt.Errorf("laravel: %s has a nil command", from)
}
name := c.Name()
at := slices.IndexFunc(commands, func(other Command) bool { return other.Name() == name })
switch {
case badName(name):
return fmt.Errorf("laravel: %s has a command named %q: give it a name without spaces, such as posts:prune", from, name)
case find(builtIn, name) != nil:
return fmt.Errorf("laravel: %s has a command named %s, which is one of Laravel's: give it another name", from, name)
case at >= 0 && !replace:
return fmt.Errorf("laravel: %s has a command named %s, which another command already has", from, name)
case at < 0 && find(commands, name) != nil:
return fmt.Errorf("laravel: %s has a command named %s, which is another command's alias", from, name)
}
var taken []error
for _, alias := range aliases(c) {
if other := find(slices.Concat(builtIn, commands), alias); alias == name || badName(alias) || other != nil && other.Name() != name {
taken = append(taken, fmt.Errorf("laravel: %s has the command %s with the alias %q, which isn't a name of its own: give it another alias", from, name, alias))
}
}
if len(taken) > 0 {
return errors.Join(taken...)
}
if err := checkFlags(c, from); err != nil {
return err
}
if at >= 0 {
commands[at] = c
} else {
commands = append(commands, c)
}
return nil
}
var errs []error
for _, c := range packages {
errs = append(errs, add("a package", c, false))
}
fromPackages := len(commands)
for i, c := range application {
// The application's commands replace a package's, but not each
// other.
named := func(other Command) bool { return other != nil && c != nil && other.Name() == c.Name() }
replace := slices.IndexFunc(commands[:fromPackages], named) >= 0 && !slices.ContainsFunc(application[:i], named)
errs = append(errs, add("Options.Commands", c, replace))
}
return commands, errors.Join(errs...)
}
// badName reports whether name can't be typed as a command, such as one
// with a space.
func badName(name string) bool {
return name == "" || strings.ContainsAny(name, " \t") || strings.HasPrefix(name, "-")
}
// find returns the command that name or one of its aliases names.
func find(commands []Command, name string) Command {
for _, command := range commands {
if command.Name() == name || slices.Contains(aliases(command), name) {
return command
}
}
return nil
}
// aliases returns the other names the command runs by.
func aliases(c Command) []string {
if aliased, ok := c.(interface{ Aliases() []string }); ok {
return aliased.Aliases()
}
return nil
}
// A usageError is a mistake on the command line, for which Run exits with
// status 2.
type usageError struct {
message string
// usage is the usage line shown below the message. Empty shows none.
usage string
}
func (e usageError) Error() string {
text := e.message
if e.usage != "" {
text += "\n\nUsage: " + e.usage
}
return text + "\n\nFor more information, try `--help`."
}
// usage returns the error that exits with status 2 for a usage mistake.
func usage(err usageError) error {
return &console.ExitError{Code: 2, Err: err}
}
func unknownCommand(program, name string) error {
return usage(usageError{fmt.Sprintf("unknown command `%s`", name), program + " [OPTIONS] <COMMAND>"})
}
// parse sets the options in args and returns the arguments that aren't
// options. help reports whether args ask for the command's help. Options
// take one dash or two, as Go's flag package accepts them, and may come
// before or after the arguments. Everything after -- is an argument.
func parse(program string, c Command, flags *flag.FlagSet, args []string) (rest []string, help bool, err error) {
for i := 0; i < len(args); i++ {
arg := args[i]
if arg == "--" {
rest = append(rest, args[i+1:]...)
break
}
if isHelp(arg) {
for _, trailing := range args[i+1:] {
if trailing == "--" {
break
}
if !strings.HasPrefix(trailing, "-") || trailing == "-" {
continue
}
if name, value, hasValue := splitOption(trailing); name == "q" || name == "quiet" {
if !hasValue {
value = "true"
}
_ = flags.Set(name, value)
}
}
return nil, true, nil
}
if !strings.HasPrefix(arg, "-") || arg == "-" {
rest = append(rest, arg)
continue
}
name, value, hasValue := splitOption(arg)
f := flags.Lookup(name)
if f == nil {
given, _, _ := strings.Cut(arg, "=")
return nil, false, rejectArguments(program, c, "unexpected argument `%s`", given)
}
switch {
case isBool(f) && !hasValue:
value = "true"
case !hasValue && (i+1 == len(args) || strings.HasPrefix(args[i+1], "-")):
return nil, false, usage(usageError{message: fmt.Sprintf("argument `%s` requires a value", optionName(name))})
case !hasValue:
i++
value = args[i]
}
if err := flags.Set(name, value); err != nil {
return nil, false, usage(usageError{message: fmt.Sprintf("invalid value `%s` for `%s`\n%s", value, optionName(name), explain(f, err))})
}
}
described := arguments(c)
required := 0
for _, argument := range described {
if argument.Required {
required++
}
}
many := len(described) > 0 && described[len(described)-1].Many
switch {
case len(rest) < required:
return nil, false, rejectArguments(program, c, "missing required argument `<%s>`", described[len(rest)].Name)
case len(rest) > len(described) && !many:
return nil, false, rejectArguments(program, c, "unexpected argument `%s`", rest[len(described)])
}
return rest, false, nil
}
// rejectArguments returns the usage error, with the command's usage line,
// for arguments the command can't run with, such as a missing required
// argument or two options that can't be given together. A command that
// checks its own arguments returns it from Run, so the mistake exits with
// status 2 like a parse error.
func rejectArguments(program string, c Command, format string, args ...any) error {
return usage(usageError{fmt.Sprintf(format, args...), usageLine(program, c, terminal.Plain)})
}
func isBool(f *flag.Flag) bool {
b, ok := f.Value.(interface{ IsBoolFlag() bool })
return ok && b.IsBoolFlag()
}
// explain says what an option's value should have been. An option of the
// command's own type explains with its error.
func explain(f *flag.Flag, err error) string {
if getter, ok := f.Value.(flag.Getter); ok {
switch getter.Get().(type) {
case int, int64, uint, uint64:
return "expected a whole number"
case float64:
return "expected a number"
case bool:
return "expected true or false"
case time.Duration:
return "expected a duration, such as 90s or 5m"
}
}
return err.Error()
}
// splitOption splits a flag argument such as --verbose=2 into its name,
// value, and whether = was present.
func splitOption(arg string) (name, value string, hasValue bool) {
return strings.Cut(strings.TrimPrefix(strings.TrimPrefix(arg, "-"), "-"), "=")
}
// isHelp reports whether arg asks for help: -h, -help, or --help.
func isHelp(arg string) bool {
return arg == "-h" || arg == "-help" || arg == "--help"
}
// usageLine returns the command's usage line, such as app make:migration
// [OPTIONS] <NAME>.
func usageLine(program string, c Command, colors terminal.Colors) string {
line := terminal.Accent.Paint(program+" "+c.Name(), colors) + " " + terminal.Muted.Paint("[OPTIONS]", colors)
for _, argument := range arguments(c) {
line += " " + terminal.Muted.Paint(argumentName(argument), colors)
}
return line
}
// argumentName returns an argument as usage shows it: <NAME> when it is
// required, [NAME] when it isn't, and with ... when it takes many values.
func argumentName(argument Argument) string {
name := "[" + argument.Name + "]"
if argument.Required {
name = "<" + argument.Name + ">"
}
if argument.Many {
name += "..."
}
return name
}
// commandHelp returns the command's help: its description, usage,
// arguments, and options, each option's help on a line below it.
func commandHelp(program string, c Command, flags *flag.FlagSet, colors terminal.Colors) string {
heading := func(text string) string { return terminal.Bold(text, colors) }
accent := func(text string) string { return terminal.Accent.Paint(text, colors) }
var b strings.Builder
fmt.Fprintf(&b, "%s\n\n%s %s\n\n", c.Description(), heading("Usage:"), usageLine(program, c, colors))
if names := aliases(c); len(names) > 0 {
fmt.Fprintf(&b, "%s %s\n\n", heading("Aliases:"), strings.Join(names, ", "))
}
if described := arguments(c); len(described) > 0 {
b.WriteString(heading("Arguments:") + "\n")
for _, argument := range described {
fmt.Fprintf(&b, " %s\n %s\n\n", terminal.Muted.Paint(argumentName(argument), colors), argument.Description)
}
}
b.WriteString(heading("Options:") + "\n")
flags.VisitAll(func(f *flag.Flag) {
if isGlobal(f.Name) {
return
}
value, help := flag.UnquoteUsage(f)
name := " " + accent(optionName(f.Name))
if len(f.Name) == 1 {
name = " " + accent(optionName(f.Name))
}
if !isBool(f) && value != "" {
name += " " + terminal.Muted.Paint("<"+strings.ToUpper(value)+">", colors)
}
if !slices.Contains([]string{"", "0", "false", "0s", "[]"}, f.DefValue) {
help += "\n\n [default: " + f.DefValue + "]"
}
fmt.Fprintf(&b, "%s\n %s\n\n", name, help)
})
for i, option := range global {
fmt.Fprintf(&b, " %s, %s\n %s", accent("-"+option.short), accent("--"+option.long), option.help)
if i < len(global)-1 {
b.WriteString("\n\n")
}
}
return b.String()
}
// listing returns the commands' listing, which help and list show: the
// commands without a namespace first, then each namespace's commands
// under its name, in alphabetical order.
func listing(program string, commands []Command, colors terminal.Colors) string {
namespace := func(command Command) string {
namespace, _, found := strings.Cut(command.Name(), ":")
if !found {
return ""
}
return namespace
}
sorted := slices.Clone(commands)
slices.SortFunc(sorted, func(a, b Command) int {
return cmp.Or(cmp.Compare(namespace(a), namespace(b)), cmp.Compare(a.Name(), b.Name()))
})
options := make([]string, len(global))
width := 0
for i, option := range global {
options[i] = "-" + option.short + ", --" + option.long
width = max(width, len(options[i]))
}
for _, command := range commands {
width = max(width, len(command.Name()))
}
heading := func(text string) string { return terminal.Bold(text, colors) }
accent := func(text string) string { return terminal.Accent.Paint(text, colors) }
muted := func(text string) string { return terminal.Muted.Paint(text, colors) }
var b strings.Builder
fmt.Fprintf(&b, "Laravel for Go\n\n%s %s %s %s\n\n%s", heading("Usage:"), accent(program), muted("[OPTIONS]"), muted("<COMMAND>"), heading("Options:"))
for i, option := range global {
fmt.Fprintf(&b, "\n %s %s", accent(fmt.Sprintf("%-*s", width, options[i])), option.help)
}
b.WriteString("\n\n" + heading("Commands:"))
previous := ""
for _, command := range sorted {
if group := namespace(command); group != previous {
b.WriteString("\n\n" + heading(" "+group))
previous = group
}
fmt.Fprintf(&b, "\n %s %s", accent(fmt.Sprintf("%-*s", width, command.Name())), command.Description())
if names := aliases(command); len(names) > 0 {
fmt.Fprintf(&b, " [aliases: %s]", strings.Join(names, ", "))
}
}
return b.String()
}
// isLongRunning reports whether the command runs until something stops it,
// such as a worker, which has no span or command attribute of its own.
func isLongRunning(c Command) bool {
long, ok := c.(interface{ LongRunning() bool })
return ok && long.LongRunning()
}
// withTicks reports whether a long-running command runs the application's
// ticks while executing.
func withTicks(c Command) bool {
ticks, ok := c.(interface{ WithTicks() bool })
return ok && ticks.WithTicks()
}