/
command.go
159 lines (137 loc) · 4.28 KB
/
command.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
package guinea
import (
"errors"
"fmt"
"strings"
)
// ErrInvalidParms can be returned by a CommandFunction to automatically
// display help text.
var ErrInvalidParms = errors.New("invalid parameters")
type CommandFunction func(Context) error
// Command represents a single command which can be executed by the program.
type Command struct {
Run CommandFunction
Subcommands map[string]*Command
Options []Option
Arguments []Argument
ShortDescription string
Description string
}
// PrintHelp prints the return value of Help to the standard output.
func (c Command) PrintHelp(cmdName string) {
fmt.Printf(c.Help(cmdName))
}
// UsageString returns a short string containing the syntax of this command.
// Command name should be set to one of the return values of FindCommand.
func (c Command) UsageString(cmdName string) string {
rw := cmdName
if len(c.Subcommands) > 0 {
rw += " <subcommand>"
}
rw += " [<options>]"
for _, arg := range c.Arguments {
rw += fmt.Sprintf(" %s", arg)
}
return rw
}
// Help returns the full help text for this command The text contains the
// syntax of the command, a description, a list of accepted options and
// arguments and available subcommands. Command name should be set to one of
// the return values of FindCommand.
func (c Command) Help(cmdName string) string {
var rv string
usage := c.UsageString(cmdName)
rv += fmt.Sprintf("\n %s - %s\n", usage, c.ShortDescription)
if len(c.Options) > 0 {
rv += fmt.Sprintln("\nOPTIONS:")
for _, opt := range c.Options {
rv += fmt.Sprintf(" %-20s %s\n", opt, opt.Description)
}
}
if len(c.Arguments) > 0 {
rv += fmt.Sprintln("\nARGUMENTS:")
for _, arg := range c.Arguments {
rv += fmt.Sprintf(" %-20s %s\n", arg, arg.Description)
}
}
if len(c.Subcommands) > 0 {
rv += fmt.Sprintln("\nSUBCOMMANDS:")
for name, subCmd := range c.Subcommands {
rv += fmt.Sprintf(" %-20s %s\n", name, subCmd.ShortDescription)
}
rv += fmt.Sprintf("\n Try '%s <subcommand> --help'\n", cmdName)
}
if len(c.Description) > 0 {
rv += fmt.Sprintln("\nDESCRIPTION:")
desc := strings.Trim(c.Description, "\n")
for _, line := range strings.Split(desc, "\n") {
rv += fmt.Sprintf(" %s\n", line)
}
}
return rv
}
// Execute runs the command. Command name is used to generate the help texts
// and should usually be set to one of the return values of FindCommand. The
// array of the arguments provided for this subcommand is used to generate the
// context and should be set to one of the return values of FindCommand as
// well. The command will not be executed with an insufficient number of
// arguments so there is no need to check that in the run function.
func (c Command) Execute(cmdName string, cmdArgs []string) error {
context, err := makeContext(c, cmdArgs)
if err != nil {
c.PrintHelp(cmdName)
return err
}
// Is there a help flag and is it set?
if help, ok := context.Options["help"]; ok && help.Bool() {
c.PrintHelp(cmdName)
return nil
}
// Is the number of arguments sufficient?
if err := c.validateArgs(context.Arguments); err != nil {
c.PrintHelp(cmdName)
return err
}
// Is this command only used to hold subcommands?
if c.Run == nil {
c.PrintHelp(cmdName)
return nil
}
e := c.Run(*context)
if e == ErrInvalidParms {
c.PrintHelp(cmdName)
}
return e
}
func (c Command) validateArgs(cmdArgs []string) error {
if len(cmdArgs) < c.minNumberOfArguments() {
return ErrInvalidParms
}
max, err := c.maxNumberOfArguments()
if err == nil && len(cmdArgs) > max {
return ErrInvalidParms
}
return nil
}
// minNumberOfArguments returns the min number of arguments that can be passed
// to this command. This is equal to the number of required arguments.
func (c Command) minNumberOfArguments() int {
sum := 0
for _, argument := range c.Arguments {
if !argument.Optional {
sum++
}
}
return sum
}
// maxNumberOfArguments returns the max number of arguments that can be passed
// to this command or error to indicate that the number is unlimited (if there
// are arguments marked as "multiple" defined for this method).
func (c Command) maxNumberOfArguments() (int, error) {
for _, argument := range c.Arguments {
if argument.Multiple {
return 0, errors.New("unlimited number of arguments")
}
}
return len(c.Arguments), nil
}