diff --git a/_examples/027-global-option/main.go b/_examples/027-global-option/main.go index b99eaad..d185124 100644 --- a/_examples/027-global-option/main.go +++ b/_examples/027-global-option/main.go @@ -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 }, } diff --git a/_examples/027-global-option/run.sh b/_examples/027-global-option/run.sh index 033a40c..4c3d27b 100755 --- a/_examples/027-global-option/run.sh +++ b/_examples/027-global-option/run.sh @@ -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 diff --git a/context.go b/context.go index 0958c2c..d27f856 100644 --- a/context.go +++ b/context.go @@ -3,6 +3,7 @@ package cli import ( "bytes" "encoding/json" + "errors" "fmt" "io" "net/http" @@ -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]