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
|
// The action to execute when no subcommands are specified
|
||||||
var Action = ShowHelp
|
var Action = ShowHelp
|
||||||
|
|
||||||
func Run(args []string) {
|
func Run(arguments []string) {
|
||||||
|
|
||||||
set := flagSet(Flags)
|
set := flagSet(Flags)
|
||||||
set.Parse(args[1:])
|
set.Parse(arguments[1:])
|
||||||
|
|
||||||
context := NewContext(set, set)
|
context := NewContext(set, set)
|
||||||
if len(args) > 1 {
|
args := context.Args()
|
||||||
name := args[1]
|
if len(args) > 0 {
|
||||||
|
name := args[0]
|
||||||
for _, c := range append(Commands, HelpCommand) {
|
for _, c := range append(Commands, HelpCommand) {
|
||||||
if c.Name == name || c.ShortName == name {
|
if c.Name == name || c.ShortName == name {
|
||||||
c.Action(context)
|
locals := flagSet(c.Flags)
|
||||||
|
locals.Parse(args[1:])
|
||||||
|
c.Action(NewContext(locals, set))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
22
cli_test.go
22
cli_test.go
@ -33,6 +33,28 @@ func Test_FlagDefaults(t *testing.T) {
|
|||||||
Run([]string{"command"})
|
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 */
|
/* Test Helpers */
|
||||||
func expect(t *testing.T, a interface{}, b interface{}) {
|
func expect(t *testing.T, a interface{}, b interface{}) {
|
||||||
if a != b {
|
if a != b {
|
||||||
|
Loading…
Reference in New Issue
Block a user