Skip to content

Commit

Permalink
add GetArgvAt method for Context. see issue #38
Browse files Browse the repository at this point in the history
  • Loading branch information
mkideal committed Aug 11, 2018
1 parent e4b3e26 commit 33e58ff
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 8 deletions.
22 changes: 17 additions & 5 deletions _examples/027-global-option/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,17 +47,29 @@ var sub = &cli.Command{
Desc: "subcommand",
Argv: func() interface{} { return new(subT) },
Fn: func(ctx *cli.Context) error {
ctx.JSON(ctx.RootArgv())
ctx.JSON(ctx.Argv())
ctx.String("\n")
ctx.JSONln(ctx.RootArgv())
ctx.JSONln(ctx.Argv())

var argv = &subT{}
var parentArgv = &rootT{}
if err := ctx.GetArgvList(argv, parentArgv); err != nil {
return err
}
ctx.JSON(parentArgv)
ctx.JSON(argv)
ctx.JSONln(parentArgv)
ctx.JSONln(argv)

argv = &subT{}
if err := ctx.GetArgvAt(argv, 0); err != nil {
return err
}
ctx.JSONln(argv)

parentArgv = &rootT{}
if err := ctx.GetArgvAt(parentArgv, 1); err != nil {
return err
}
ctx.JSONln(parentArgv)

return nil
},
}
6 changes: 3 additions & 3 deletions _examples/027-global-option/run.sh
Original file line number Diff line number Diff line change
Expand Up @@ -33,15 +33,15 @@ echo ===run sub command
echo

echo =case 1: read from file
./app sub
./app sub -w xxx
echo

echo =case 2: read from ENV variables
HOST=10.0.0.1 ./app sub
HOST=10.0.0.1 ./app sub -w xxx
echo

echo =case 3: read from command line
HOST=10.0.0.1 ./app sub -H 168.0.0.1
HOST=10.0.0.1 ./app sub -H 168.0.0.1 -w xxx
echo

echo
Expand Down
22 changes: 22 additions & 0 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package cli
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
Expand Down Expand Up @@ -143,6 +144,27 @@ func (ctx *Context) GetArgvList(curr interface{}, parents ...interface{}) error
return nil
}

func (ctx *Context) GetArgvAt(argv interface{}, i int) error {
if isEmptyArgvList(ctx.argvList) {
return argvError{isEmpty: true}
}
if argv == nil {
return errors.New("argv is nil")
}
if i >= len(ctx.argvList) {
return argvError{isOutOfRange: true}
}
if ctx.argvList[i] == nil {
return argvError{ith: i, msg: "source is nil"}
}

buf := bytes.NewBufferString("")
if err := json.NewEncoder(buf).Encode(ctx.argvList[i]); err != nil {
return err
}
return json.NewDecoder(buf).Decode(argv)
}

// IsSet determins whether `flag` is set
func (ctx *Context) IsSet(flag string, aliasFlags ...string) bool {
fl, ok := ctx.flagSet.flagMap[flag]
Expand Down

0 comments on commit 33e58ff

Please sign in to comment.