forked from codemodify/systemkit-clicmdflags
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommand.go
More file actions
65 lines (53 loc) · 1.45 KB
/
command.go
File metadata and controls
65 lines (53 loc) · 1.45 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
package clicmdflags
import (
"os"
"strings"
)
// Command -
type Command struct {
Name string
Description string
Examples []string
Flags interface{}
Handler func(command *Command)
Hidden bool
PassThrough bool
parentCommand *Command
subCommands []*Command
flagedForExecute bool
}
// AddCommand -
func (thisRef *Command) AddCommand(command *Command) {
command.parentCommand = thisRef
thisRef.subCommands = append(thisRef.subCommands, command)
}
// Execute -
func (thisRef *Command) Execute() error {
return thisRef.parseAndExecute(true)
}
// ParseFlags -
func (thisRef *Command) ParseFlags() error {
return thisRef.parseAndExecute(false)
}
// Execute -
func (thisRef *Command) parseAndExecute(execute bool) error {
// 1. start at root & populate all flags values for all commands
rootCommand := thisRef.getRootCommand()
rootCommand.flagedForExecute = true
argsToParse := os.Args[1:]
helpsIsWanted := strings.HasSuffix(strings.Join(argsToParse, " "), "help")
if err := rootCommand.flagNeededCommandsForExecuteAndPopulateTheirFlags(argsToParse); err != nil &&
!helpsIsWanted {
return err
}
// 2. find root and ask to parse flags
commandToExecute := thisRef.getLastSubcommandFlagedForExecute()
if commandToExecute != nil {
if execute && helpsIsWanted {
commandToExecute.showUsage()
} else if execute && commandToExecute.Handler != nil {
commandToExecute.Handler(commandToExecute)
}
}
return nil
}