JMS #4: Parsing arguments for subcommands as well

main
Jeremy Saenz 11 years ago
parent 5bb6efd8bd
commit 87d3b81d55

@ -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
}
}

@ -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…
Cancel
Save