diff --git a/os/gcmd/gcmd.go b/os/gcmd/gcmd.go index fcbefd8bf..08f55f44d 100644 --- a/os/gcmd/gcmd.go +++ b/os/gcmd/gcmd.go @@ -14,6 +14,11 @@ import ( "github.com/gogf/gf/v2/container/gvar" "github.com/gogf/gf/v2/internal/command" "github.com/gogf/gf/v2/internal/utils" + "github.com/gogf/gf/v2/os/gctx" +) + +const ( + CtxKeyParser gctx.StrKey = `GoFrameCommandParser` ) const ( diff --git a/os/gcmd/gcmd_command_help.go b/os/gcmd/gcmd_command_help.go index 1e482650e..4fd00faff 100644 --- a/os/gcmd/gcmd_command_help.go +++ b/os/gcmd/gcmd_command_help.go @@ -126,6 +126,9 @@ func (c *Command) Print() { } func (c *Command) defaultHelpFunc(ctx context.Context, parser *Parser) error { + // Add built-in help option, just for info only. + c.Options = append(c.Options, defaultHelpOption) + // Print command help info to stdout. c.Print() return nil } diff --git a/os/gcmd/gcmd_command_object.go b/os/gcmd/gcmd_command_object.go index afa97ab86..7f6a6abf8 100644 --- a/os/gcmd/gcmd_command_object.go +++ b/os/gcmd/gcmd_command_object.go @@ -185,6 +185,8 @@ func newCommandFromMethod(object interface{}, method reflect.Value) (command Com // Create function that has value return. command.FuncWithValue = func(ctx context.Context, parser *Parser) (out interface{}, err error) { + ctx = context.WithValue(ctx, CtxKeyParser, command) + defer func() { if exception := recover(); exception != nil { if v, ok := exception.(error); ok && gerror.HasStack(v) { @@ -209,8 +211,7 @@ func newCommandFromMethod(object interface{}, method reflect.Value) (command Com } } // Default values from struct tag. - err = mergeDefaultStructValue(data, inputObject.Interface()) - if err != nil { + if err = mergeDefaultStructValue(data, inputObject.Interface()); err != nil { return nil, err } // Construct input parameters. diff --git a/os/gcmd/gcmd_command_run.go b/os/gcmd/gcmd_command_run.go index 49fd508b3..df0429eed 100644 --- a/os/gcmd/gcmd_command_run.go +++ b/os/gcmd/gcmd_command_run.go @@ -23,9 +23,6 @@ func (c *Command) Run(ctx context.Context) error { // RunWithValue calls custom function that bound to this command with value output. func (c *Command) RunWithValue(ctx context.Context) (value interface{}, err error) { - // Add built-in help option, just for info only. - c.Options = append(c.Options, defaultHelpOption) - // Parse command arguments and options using default algorithm. parser, err := Parse(nil) if err != nil {