JMS #4: Parsing arguments for subcommands as well
This commit is contained in:
parent
5bb6efd8bd
commit
87d3b81d55
13
cli.go
13
cli.go
@ -19,17 +19,20 @@ var Flags []Flag
|
||||
// The action to execute when no subcommands are specified
|
||||
var Action = ShowHelp
|
||||
|
||||
func Run(args []string) {
|
||||
func Run(arguments []string) {
|
||||
|
||||
set := flagSet(Flags)
|
||||
set.Parse(args[1:])
|
||||
set.Parse(arguments[1:])
|
||||
|
||||
context := NewContext(set, set)
|
||||
if len(args) > 1 {
|
||||
name := args[1]
|
||||
args := context.Args()
|
||||
if len(args) > 0 {
|
||||
name := args[0]
|
||||
for _, c := range append(Commands, HelpCommand) {
|
||||
if c.Name == name || c.ShortName == name {
|
||||
c.Action(context)
|
||||
locals := flagSet(c.Flags)
|
||||
locals.Parse(args[1:])
|
||||
c.Action(NewContext(locals, set))
|
||||
return
|
||||
}
|
||||
}
|
||||
|
22
cli_test.go
22
cli_test.go
@ -33,6 +33,28 @@ func Test_FlagDefaults(t *testing.T) {
|
||||
Run([]string{"command"})
|
||||
}
|
||||
|
||||
func TestCommands(t *testing.T) {
|
||||
Flags = []Flag{
|
||||
StringFlag{"name", "jeremy", "a name to print"},
|
||||
}
|
||||
Commands = []Command{
|
||||
{
|
||||
Name: "print",
|
||||
Flags: []Flag{
|
||||
IntFlag{"age", 50, "the age of the person"},
|
||||
},
|
||||
Action: func(c *Context) {
|
||||
expect(t, c.GlobalString("name"), "jordie")
|
||||
expect(t, c.Int("age"), 21)
|
||||
},
|
||||
},
|
||||
}
|
||||
Action = func(c *Context) {
|
||||
t.Error("default action should not be called")
|
||||
}
|
||||
Run([]string{"command", "--name", "jordie", "print", "--age", "21"})
|
||||
}
|
||||
|
||||
/* Test Helpers */
|
||||
func expect(t *testing.T, a interface{}, b interface{}) {
|
||||
if a != b {
|
||||
|
Loading…
Reference in New Issue
Block a user