Skip to content

Commit

Permalink
refactor: change NewCommander to singleton Program
Browse files Browse the repository at this point in the history
  • Loading branch information
WindomZ committed Mar 10, 2017
1 parent 99510bd commit 5d4fec9
Show file tree
Hide file tree
Showing 7 changed files with 59 additions and 52 deletions.
50 changes: 26 additions & 24 deletions command.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ type Command struct {
actor
usage string // api set usage
root bool // root command
clone bool // clone command
clone bool // clone command for new help message line
version string // version if root command
desc string // description
annotation map[string][]string // annotation, like 'try', 'examples', etc.
Expand All @@ -22,14 +22,18 @@ type Command struct {
errFunc ErrFunc // error function // TODO: not finish this
}

func newCommand(usage string, root bool, args ...interface{}) *Command {
func newCommand(root bool) *Command {
c := &Command{
usage: strings.TrimSpace(usage),
root: root,
root: root,
errFunc: func(err error, obj interface{}) {
fmt.Printf(" err: %v\n object: %#v\n", err, obj)
},
}
return c
}

func (c *Command) Usage(usage string, args ...interface{}) Commander {
c.usage = strings.TrimSpace(usage)
c.regexpNames()
c.regexpArguments()
if len(args) >= 1 {
Expand All @@ -52,11 +56,6 @@ func (c *Command) regexpArguments() {
c.arguments.Set(c.usage)
}

func (c *Command) Clone() *Command {
c.clone = true
return c
}

func (c Command) Valid() bool {
return len(c.names) != 0 && len(c.usage) != 0
}
Expand Down Expand Up @@ -98,18 +97,18 @@ func (c *Command) Action(action interface{}, keys ...[]string) Commander {

func (c *Command) Command(usage string, args ...interface{}) Commander {
if c.clone {
c.usage += " " + usage
c.regexpNames()
c.regexpArguments()
return c
}
cmd := newCommand(usage, false, args...)
if cmd.Valid() {
c.commands = append(c.commands, cmd)
} else if c.errFunc != nil {
c.errFunc(ErrCommand, cmd)
usage = c.usage + " " + usage
} else if c.Valid() {
cmd := newCommand(false)
cmd.Usage(usage, args...)
if cmd.Valid() {
c.commands = append(c.commands, cmd)
} else if c.errFunc != nil {
c.errFunc(ErrCommand, cmd)
}
return cmd
}
return cmd
return c.Usage(usage, args...)
}

func (c *Command) Option(usage string, args ...interface{}) Commander {
Expand All @@ -121,13 +120,16 @@ func (c *Command) Option(usage string, args ...interface{}) Commander {
return c
}

func (c *Command) line(usage string, args ...interface{}) *Command {
return newCommand(usage, c.root, args...).Clone()
func (c *Command) Line(usage string, args ...interface{}) *Command {
cmd := newCommand(c.root)
cmd.Usage(usage, args...)
cmd.clone = true
return cmd
}

func (c *Command) LineArgument(usage string, args ...interface{}) Commander {
usage = c.Name() + " " + usage
cmd := c.line(usage, args...)
cmd := c.Line(usage, args...)
if cmd.arguments.IsEmpty() {
return cmd
}
Expand All @@ -137,7 +139,7 @@ func (c *Command) LineArgument(usage string, args ...interface{}) Commander {
}

func (c *Command) LineOption(usage string, args ...interface{}) Commander {
cmd := c.line(c.usage, args...)
cmd := c.Line(c.usage, args...)
cmd.Option(usage, args...)
if cmd.options.IsEmpty() {
return cmd
Expand Down
3 changes: 2 additions & 1 deletion command_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ import (
)

func TestCommand_1(t *testing.T) {
c := newCommand("cmd <x>", true, "this is description").
c := newCommand(true).
Usage("cmd <x>", "this is description").
Option("-c, --config", "config description").
Option("-d, --drop", "drop description")

Expand Down
4 changes: 2 additions & 2 deletions commander.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ type Commander interface {
Parse(argv ...[]string) (*Context, error)
}

func NewCommander(usage string, args ...interface{}) Commander {
return newCommand(usage, true, args...)
func newCommander() Commander {
return newCommand(true)
}

func Parse(doc string, argv []string, help bool, version string,
Expand Down
35 changes: 17 additions & 18 deletions commander_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,27 +6,24 @@ import (
"testing"
)

func TestNewCommander(t *testing.T) {
c := NewCommander("hello")
assert.NotEmpty(t, c)
}

func TestCommander_1(t *testing.T) {
func TestCommander_Ping(t *testing.T) {
var sum int
var host string

cmd := NewCommander("test").
Program.Command("test").
Version("0.0.1").
Description("This is a test cli.")
cmd.Command("add <x> <y>").

Program.Command("add <x> <y>").
Description("addition operation").
Action(func(c *Context) error {
x, _ := c.Doc.GetInt("<x>")
y, _ := c.Doc.GetInt("<y>")
sum = x + y
return nil
})
cmd.Command("ping <host>").

Program.Command("ping <host>").
Action(func(c *Context) error {
host = c.Doc.GetString("<host>")
return nil
Expand All @@ -43,24 +40,25 @@ func TestCommander_1(t *testing.T) {
},
)

if _, err := cmd.Parse([]string{"test", "add", "10", "20"}); err != nil {
if _, err := Program.Parse([]string{"test", "add", "10", "20"}); err != nil {
t.Fatal(err)
}
if _, err := cmd.Parse([]string{"test", "ping", "127.0.0.1"}); err != nil {
if _, err := Program.Parse([]string{"test", "ping", "127.0.0.1"}); err != nil {
t.Fatal(err)
}

assert.Equal(t, sum, 30)
assert.Equal(t, host, "127.0.0.1")
}

func TestCommander_calculator(t *testing.T) {
func TestCommander_Calculator(t *testing.T) {
var result int

cmd := NewCommander("calculator_example").
Program.Command("calculator_example").
Version("0.0.1").
Description("simple calculator example")
cmd.LineArgument("<value> ( ( + | - | * | / ) <value> )...").

Program.LineArgument("<value> ( ( + | - | * | / ) <value> )...").
Action(func(c *Context) error {
if c.Contain("<function>") {
return nil
Expand All @@ -85,7 +83,8 @@ func TestCommander_calculator(t *testing.T) {
}
return nil
})
cmd.LineArgument("<function> <value> [( , <value> )]...").

Program.LineArgument("<function> <value> [( , <value> )]...").
Action(func(c *Context) error {
result = 0
switch c.Doc.GetString("<function>") {
Expand All @@ -100,19 +99,19 @@ func TestCommander_calculator(t *testing.T) {
return nil
})

if _, err := cmd.Parse([]string{"calculator_example",
if _, err := Program.Parse([]string{"calculator_example",
"1", "+", "2", "+", "3", "+", "4", "+", "5"}); err != nil {
t.Fatal(err)
}
assert.Equal(t, result, 15)

if _, err := cmd.Parse([]string{"calculator_example",
if _, err := Program.Parse([]string{"calculator_example",
"1", "+", "2", "*", "3", "/", "4", "-", "5"}); err != nil {
t.Fatal(err)
}
assert.Equal(t, result, -3)

if _, err := cmd.Parse([]string{"calculator_example",
if _, err := Program.Parse([]string{"calculator_example",
"sum", "10", ",", "20", ",", "30", ",", "40"}); err != nil {
t.Fatal(err)
}
Expand Down
8 changes: 3 additions & 5 deletions context.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
package commander

import "fmt"

// Context
type Context struct {
Args ContextArgs
Doc DocoptMap
Args ContextArgs `json:"arguments"`
Doc DocoptMap `json:"docopt"`
}

func newContext(args []string, d DocoptMap) *Context {
Expand All @@ -16,7 +14,7 @@ func newContext(args []string, d DocoptMap) *Context {
}

func (c Context) String() string {
return fmt.Sprintf("%#v", c)
return c.Doc.String()
}

func (c Context) Contain(key string) bool {
Expand Down
8 changes: 6 additions & 2 deletions context_args.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,11 @@ func (c ContextArgs) Get(index int) string {
return ""
}

func (c ContextArgs) String(offsets ...int) string {
func (c ContextArgs) String() string {
return strings.Join(c, " ")
}

func (c ContextArgs) StringSeparator(sep string, offsets ...int) string {
var offset int = 0
if len(offsets) != 0 {
offset = offsets[0]
Expand All @@ -29,5 +33,5 @@ func (c ContextArgs) String(offsets ...int) string {
if offset < 0 {
offset = 0
}
return strings.Join(c[offset:], " | ")
return strings.Join(c[offset:], sep)
}
3 changes: 3 additions & 0 deletions program.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
package commander

var Program Commander = newCommander()

0 comments on commit 5d4fec9

Please sign in to comment.