-
Notifications
You must be signed in to change notification settings - Fork 68
Expand file tree
/
Copy pathcmd.go
More file actions
91 lines (77 loc) · 2.02 KB
/
cmd.go
File metadata and controls
91 lines (77 loc) · 2.02 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
package main
import (
"flag"
"fmt"
"log"
"os"
"slices"
)
// command is a subcommand handler and its flag set.
type command struct {
// flagSet is the flag set for the command.
flagSet *flag.FlagSet
// aliases for the command.
aliases []string
// handler is the function that is invoked to handle this command.
handler func(args []string) error
// flagSet.Usage function to invoke on e.g. -h flag. If nil, a default one is
// used.
usageFunc func()
}
// matches tells if the given name matches this command or one of its aliases.
func (c *command) matches(name string) bool {
if name == c.flagSet.Name() {
return true
}
return slices.Contains(c.aliases, name)
}
// commander represents a top-level command with subcommands.
type commander []*command
// run runs the command.
func (c commander) run(flagSet *flag.FlagSet, cmdName, usageText string, args []string) {
// Parse flags.
flagSet.Usage = func() {
_, _ = fmt.Fprint(flag.CommandLine.Output(), usageText)
}
if !flagSet.Parsed() {
_ = flagSet.Parse(args)
}
// Print usage if the command is "help".
if flagSet.Arg(0) == "help" || flagSet.NArg() == 0 {
flagSet.SetOutput(os.Stdout)
flagSet.Usage()
os.Exit(0)
}
// Configure default usage funcs for commands.
for _, cmd := range c {
if cmd.usageFunc != nil {
cmd.flagSet.Usage = cmd.usageFunc
continue
}
cmd.flagSet.Usage = func() {
_, _ = fmt.Fprintf(flag.CommandLine.Output(), "Usage of '%s %s':\n", cmdName, cmd.flagSet.Name())
cmd.flagSet.PrintDefaults()
}
}
// Find the subcommand to execute.
name := flagSet.Arg(0)
// Command is legacy, so lets execute the old way
for _, cmd := range c {
if !cmd.matches(name) {
continue
}
// Read global configuration now.
var err error
cfg, err = readConfig()
if err != nil {
log.Fatal("reading config: ", err)
}
exitCode, err := runLegacy(cmd, flagSet)
if err != nil {
log.Fatal(err)
}
os.Exit(exitCode)
}
log.Printf("%s: unknown subcommand %q", cmdName, name)
log.Fatalf("Run '%s help' for usage.", cmdName)
}