gf icon indicating copy to clipboard operation
gf copied to clipboard

os/gcmd: Command can't get args, for all args are parsed as SubCommand, if SubCommand not found, return error.

Open yuanboshe opened this issue 1 year ago • 1 comments

Go version

go 1.22

GoFrame version

2.7.2

Can this bug be reproduced with the latest release?

Option Yes

What did you do?

package cmd

import (
	"context"
	"fmt"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gcmd"
)

var (
	Main = gcmd.Command{
		Name:   "main",
		Usage:  "main",
		Brief:  "...",
		Func: func(ctx context.Context, parser *gcmd.Parser) (err error) {
			fmt.Println("main")
			g.Dump(parser.GetArgAll())
			println("-----")
			g.Dump(parser.GetOptAll())

			return nil
		},
	}
)

then go run main.go abc

### What did you see happen?

error...

### What did you expect to see?

print the args

yuanboshe avatar Jul 22 '24 06:07 yuanboshe

If you want to call a subcommand, add the implementation of the subcommand and you can use it normally

Main.AddCommand(&gcmd.Command{
Name: "abc",
}) 

fengshunli avatar Jul 23 '24 04:07 fengshunli

If you want to call a subcommand, add the implementation of the subcommand and you can use it normally

Main.AddCommand(&gcmd.Command{
Name: "abc",
}) 

Not subcommand, just pass the args from command line into Func, need get the args with parser.GetArgAll().

yuanboshe avatar Aug 29 '24 12:08 yuanboshe

Complete running codes:

package main

import (
	"context"
	"fmt"

	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gcmd"
)

var (
	Main = gcmd.Command{
		Name:  "main",
		Usage: "main",
		Brief: "...",
		Func: func(ctx context.Context, parser *gcmd.Parser) (err error) {
			fmt.Println("main")
			g.Dump(parser.GetArgAll())
			println("-----")
			g.Dump(parser.GetOptAll())

			return nil
		},
	}
)

func main() {
	var ctx = context.Background()
	Main.Run(ctx)
}

gqcn avatar Sep 25 '24 06:09 gqcn

@gqcn ,找不到子命令时,应将其视为参数,不应该报错 image

wln32 avatar Sep 28 '24 23:09 wln32

Bot detected the issue body's language is not English, translate it automatically. 👯👭🏻🧑‍🤝‍🧑👫🧑🏿‍🤝‍🧑🏻👩🏾‍🤝‍👨🏿👬🏿


@gqcn, when a subcommand cannot be found, it should be treated as a parameter and no error should be reported. image

Issues-translate-bot avatar Sep 28 '24 23:09 Issues-translate-bot