-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexecute.go
More file actions
376 lines (326 loc) · 9.11 KB
/
execute.go
File metadata and controls
376 lines (326 loc) · 9.11 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
package cli
import (
"context"
"fmt"
"os"
"reflect"
"strings"
)
// Execute runs the command with os.Args
func (c *Command) Execute() error {
return c.ExecuteContext(context.Background())
}
// ExecuteContext runs the command with a context
func (c *Command) ExecuteContext(ctx context.Context) error {
// Use os.Args[1:] (skip program name)
args := os.Args[1:]
return c.execute(ctx, args)
}
// ExecuteWithArgs runs the command with custom arguments (useful for testing)
func (c *Command) ExecuteWithArgs(args []string) error {
return c.execute(context.Background(), args)
}
// execute is the internal execution logic
func (c *Command) execute(ctx context.Context, args []string) error {
// First, find if there's a subcommand in the args (look at non-flag args only)
subcommandIndex := -1
var subcmd *Command
for i, arg := range args {
// Skip anything that looks like a flag
if strings.HasPrefix(arg, "-") {
continue
}
// Check if this is a known subcommand
if cmd, exists := c.subcommands[arg]; exists {
subcommandIndex = i
subcmd = cmd
break
}
// If it's not a flag and not a subcommand:
// - If we have subcommands defined BUT no arguments, this is an unknown command error
// - Otherwise, it's an argument - stop looking for subcommands
if len(c.subcommands) > 0 && len(c.args) == 0 {
return &CommandNotFoundError{
Name: arg,
Cmd: c,
}
}
break
}
// Check for help flag FIRST - before any parsing
if c.helpEnabled {
for _, arg := range args {
if arg == "--"+c.helpFlag || arg == "-"+c.helpShort {
// Find which command the help is for
targetCmd := c
for _, a := range args {
if !strings.HasPrefix(a, "-") {
if cmd, exists := targetCmd.subcommands[a]; exists {
targetCmd = cmd
} else {
break
}
}
}
targetCmd.showHelp()
return nil
}
}
}
// If we found a subcommand, delegate to it with remaining args
if subcommandIndex >= 0 {
// Collect args before and after subcommand
beforeSubcmd := args[:subcommandIndex]
afterSubcmd := args[subcommandIndex+1:]
// Get all flags for current command (including inherited)
allFlags := c.getAllFlags()
// Parse flags from BEFORE subcommand only (those belong to parent)
if len(beforeSubcmd) > 0 {
tempFS := NewFlagSet()
for _, flag := range allFlags {
tempFS.flags = append(tempFS.flags, flag)
}
remaining, err := tempFS.Parse(beforeSubcmd)
if err != nil {
return &FlagError{
Flag: "",
Msg: err.Error(),
Cmd: c,
}
}
// If there are remaining non-flag args before subcommand, that's an error
if len(remaining) > 0 {
return &CommandNotFoundError{
Name: remaining[0],
Cmd: c,
}
}
}
// Execute subcommand with args after the subcommand name
return subcmd.execute(ctx, afterSubcmd)
}
// No subcommand found, parse all flags and execute this command
allFlags := c.getAllFlags()
tempFS := NewFlagSet()
for _, flag := range allFlags {
tempFS.flags = append(tempFS.flags, flag)
}
remaining, err := tempFS.Parse(args)
if err != nil {
return &FlagError{
Flag: "",
Msg: err.Error(),
Cmd: c,
}
}
// Validate required flags
for _, flag := range allFlags {
if flag.IsRequired() && !flag.IsSet() {
return &FlagError{
Flag: flag.names[0],
Msg: "required flag not set",
Cmd: c,
}
}
}
// Validate argument count
nonFlagArgs := remaining
expectedArgs := len(c.args)
// Check if action is variadic
isVariadic := false
if c.action != nil {
actionValue := reflect.ValueOf(c.action)
actionType := actionValue.Type()
isVariadic = actionType.IsVariadic()
}
// Check if we have too many arguments (skip check for variadic)
if !isVariadic && len(nonFlagArgs) > expectedArgs {
return &ArgumentError{
Arg: "",
Msg: fmt.Sprintf("too many arguments: expected %d, got %d", expectedArgs, len(nonFlagArgs)),
Cmd: c,
}
}
// Execute this command's action
return c.executeAction(ctx, remaining)
} // executeAction executes the command's action with lifecycle hooks
func (c *Command) executeAction(ctx context.Context, args []string) error {
// Run PersistentPreRun hooks (from root to current)
var ancestors []*Command
current := c
for current != nil {
ancestors = append([]*Command{current}, ancestors...)
current = current.parent
}
for _, cmd := range ancestors {
if cmd.persistentPreRun != nil {
if err := cmd.persistentPreRun(ctx, c); err != nil {
// Still run post hooks on error
c.runPostHooks(ctx)
return err
}
}
}
// Run PreRun hook
if c.preRun != nil {
if err := c.preRun(ctx, c); err != nil {
// Run post hooks even on PreRun error
c.runPostHooks(ctx)
return err
}
}
// Execute action
var actionErr error
if c.action != nil {
actionErr = c.callAction(ctx, args)
}
// Always run post hooks (even if action failed)
c.runPostHooks(ctx)
return actionErr
}
// runPostHooks executes PostRun and PersistentPostRun hooks
func (c *Command) runPostHooks(ctx context.Context) {
// Run PostRun hook
if c.postRun != nil {
c.postRun(ctx, c) // Ignore errors in PostRun for now
}
// Run PersistentPostRun hooks (from current to root)
current := c
for current != nil {
if current.persistentPostRun != nil {
current.persistentPostRun(ctx, c) // Ignore errors
}
current = current.parent
}
}
// callAction invokes the action function with proper arguments
func (c *Command) callAction(ctx context.Context, args []string) error {
actionValue := reflect.ValueOf(c.action)
actionType := actionValue.Type()
// Build argument list
callArgs := []reflect.Value{
reflect.ValueOf(ctx),
reflect.ValueOf(c),
}
// Check if function is variadic
isVariadic := actionType.IsVariadic()
numParams := actionType.NumIn() - 2 // Subtract ctx and cmd
if isVariadic {
// For variadic functions, handle specially
// Add non-variadic arguments first (all params except the last variadic one)
numFixed := numParams - 1
for i := 0; i < numFixed; i++ {
if i >= len(args) {
// Check if this argument is required
if i < len(c.args) && c.args[i].Required {
return &ArgumentError{
Arg: c.args[i].Name,
Msg: "required argument missing",
Cmd: c,
}
}
// Use zero value for optional arguments
callArgs = append(callArgs, reflect.Zero(actionType.In(i+2)))
continue
}
// Convert string argument to expected type
argType := actionType.In(i + 2)
argValue, err := convertArgument(args[i], argType)
if err != nil {
argName := ""
if i < len(c.args) {
argName = c.args[i].Name
}
return &ArgumentError{
Arg: argName,
Msg: err.Error(),
Cmd: c,
}
}
callArgs = append(callArgs, argValue)
}
// Get the element type of the variadic parameter
sliceType := actionType.In(actionType.NumIn() - 1)
elemType := sliceType.Elem()
// Build a slice for variadic parameters
variadicCount := len(args) - numFixed
variadicSlice := reflect.MakeSlice(sliceType, variadicCount, variadicCount)
for i := 0; i < variadicCount; i++ {
argValue, err := convertArgument(args[numFixed+i], elemType)
if err != nil {
return &ArgumentError{
Arg: "",
Msg: err.Error(),
Cmd: c,
}
}
variadicSlice.Index(i).Set(argValue)
}
// Append the slice as a single argument
callArgs = append(callArgs, variadicSlice)
} else {
// Non-variadic function
for i := 0; i < numParams; i++ {
if i >= len(args) {
// Check if this argument is required
if i < len(c.args) && c.args[i].Required {
return &ArgumentError{
Arg: c.args[i].Name,
Msg: "required argument missing",
Cmd: c,
}
}
// Use zero value for optional arguments
callArgs = append(callArgs, reflect.Zero(actionType.In(i+2)))
continue
}
// Convert string argument to expected type
argType := actionType.In(i + 2)
argValue, err := convertArgument(args[i], argType)
if err != nil {
argName := ""
if i < len(c.args) {
argName = c.args[i].Name
}
return &ArgumentError{
Arg: argName,
Msg: err.Error(),
Cmd: c,
}
}
callArgs = append(callArgs, argValue)
}
}
// Call the action function
var results []reflect.Value
if isVariadic {
// For variadic functions, use CallSlice with the slice as the last argument
// CallSlice will expand the slice elements into individual variadic parameters
results = actionValue.CallSlice(callArgs)
} else {
results = actionValue.Call(callArgs)
}
// Check if there's an error return value
if len(results) > 0 && !results[0].IsNil() {
return results[0].Interface().(error)
}
return nil
}
// convertArgument converts a string argument to the target type
func convertArgument(arg string, targetType reflect.Type) (reflect.Value, error) {
// Use the same conversion logic as flag parsing
tempFS := NewFlagSet()
// Create a temporary variable of the target type
tempVar := reflect.New(targetType).Elem()
// Create a temporary flag
tempFlag := Flag{
names: []string{"temp"},
flagType: targetType,
value: tempVar,
}
// Parse the value
if err := tempFS.setValue(&tempFlag, arg); err != nil {
return reflect.Value{}, err
}
return tempVar, nil
}