improve package gcmd

This commit is contained in:
John Guo
2021-11-24 21:57:41 +08:00
parent c5541b484f
commit 332de30fba
4 changed files with 11 additions and 5 deletions

View File

@ -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 (

View File

@ -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
}

View File

@ -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.

View File

@ -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 {