Merge pull request #35 from codegangsta/JMS-34

JMS-34: App.Run() can now be run multiple times.
main
Jeremy Saenz 11 years ago
commit e3ea5e29b0

@ -1,9 +1,9 @@
package cli package cli
import ( import (
"os"
"io/ioutil"
"fmt" "fmt"
"io/ioutil"
"os"
) )
type App struct { type App struct {
@ -32,13 +32,13 @@ func NewApp() *App {
func (a *App) Run(arguments []string) { func (a *App) Run(arguments []string) {
// append help to commands // append help to commands
a.Commands = append(a.Commands, helpCommand) if a.Command(helpCommand.Name) == nil {
// append version to flags a.Commands = append(a.Commands, helpCommand)
a.Flags = append( }
a.Flags,
BoolFlag{"version", "print the version"}, //append version/help flags
helpFlag{"show help"}, a.appendFlag(BoolFlag{"version", "print the version"})
) a.appendFlag(helpFlag{"show help"})
// parse flags // parse flags
set := flagSet(a.Name, a.Flags) set := flagSet(a.Name, a.Flags)
@ -59,14 +59,39 @@ func (a *App) Run(arguments []string) {
args := context.Args() args := context.Args()
if len(args) > 0 { if len(args) > 0 {
name := args[0] name := args[0]
for _, c := range a.Commands { c := a.Command(name)
if c.HasName(name) { if c != nil {
c.Run(context) c.Run(context)
return return
}
} }
} }
// Run default Action // Run default Action
a.Action(context) a.Action(context)
} }
func (a *App) Command(name string) *Command {
for _, c := range a.Commands {
if c.HasName(name) {
return &c
}
}
return nil
}
func (a *App) hasFlag(flag Flag) bool {
for _, f := range a.Flags {
if flag == f {
return true
}
}
return false
}
func (a *App) appendFlag(flag Flag) {
if !a.hasFlag(flag) {
a.Flags = append(a.Flags, flag)
}
}

@ -4,6 +4,7 @@ import (
"fmt" "fmt"
"github.com/codegangsta/cli" "github.com/codegangsta/cli"
"os" "os"
"testing"
) )
func ExampleApp() { func ExampleApp() {
@ -22,3 +23,42 @@ func ExampleApp() {
// Output: // Output:
// Hello Jeremy // Hello Jeremy
} }
func TestApp_Run(t *testing.T) {
s := ""
app := cli.NewApp()
app.Action = func(c *cli.Context) {
s = s + c.Args()[0]
}
app.Run([]string{"command", "foo"})
app.Run([]string{"command", "bar"})
expect(t, s, "foobar")
}
var commandAppTests = []struct {
name string
expected bool
}{
{"foobar", true},
{"batbaz", true},
{"b", true},
{"f", true},
{"bat", false},
{"nothing", false},
}
func TestApp_Command(t *testing.T) {
app := cli.NewApp()
fooCommand := cli.Command{Name: "foobar", ShortName: "f"}
batCommand := cli.Command{Name: "batbaz", ShortName: "b"}
app.Commands = []cli.Command{
fooCommand,
batCommand,
}
for _, test := range commandAppTests {
expect(t, app.Command(test.name) != nil, test.expected)
}
}

Loading…
Cancel
Save