JMS-34: App.Run() can now be run multiple times.

- Added a method for looking up commands
- Using some logic to make sure default flags are not added more than
  once
main
Jeremy Saenz 11 years ago
parent 02252ed208
commit e5c31ab592

@ -1,9 +1,9 @@
package cli
import (
"os"
"io/ioutil"
"fmt"
"io/ioutil"
"os"
)
type App struct {
@ -32,13 +32,13 @@ func NewApp() *App {
func (a *App) Run(arguments []string) {
// append help to commands
a.Commands = append(a.Commands, helpCommand)
// append version to flags
a.Flags = append(
a.Flags,
BoolFlag{"version", "print the version"},
helpFlag{"show help"},
)
if a.Command(helpCommand.Name) == nil {
a.Commands = append(a.Commands, helpCommand)
}
//append version/help flags
a.appendFlag(BoolFlag{"version", "print the version"})
a.appendFlag(helpFlag{"show help"})
// parse flags
set := flagSet(a.Name, a.Flags)
@ -59,14 +59,39 @@ func (a *App) Run(arguments []string) {
args := context.Args()
if len(args) > 0 {
name := args[0]
for _, c := range a.Commands {
if c.HasName(name) {
c.Run(context)
return
}
c := a.Command(name)
if c != nil {
c.Run(context)
return
}
}
// Run default Action
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"
"github.com/codegangsta/cli"
"os"
"testing"
)
func ExampleApp() {
@ -22,3 +23,42 @@ func ExampleApp() {
// Output:
// 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