spf13 / cobra

A Commander for modern Go CLI interactions
https://cobra.dev
Apache License 2.0
38.2k stars 2.85k forks source link

When the value of PersistentFlags is the same as the name of the subcommand, it will have issue #1834

Closed yxxhero closed 2 years ago

yxxhero commented 2 years ago

I have a test subcommand and a Persistent Flag -e.

rootcmd -e test -l name=catalyst test

-e will be -l value.

what should I do to solve this issue?

Thanks very much.

marckhouzam commented 2 years ago

Could you post the code @yxxhero?

yxxhero commented 2 years ago
package main

import (
    "fmt"

    "github.com/spf13/cobra"
)

func main() {
    var env string
    var selector string

    var cmdEcho = &cobra.Command{
        Use: "test",
        Run: func(cmd *cobra.Command, args []string) {
            fmt.Println(env, selector)
        },
    }

    var rootCmd = &cobra.Command{Use: "app"}
    rootCmd.PersistentFlags().StringVarP(&env, "env", "e", "", "env")
    rootCmd.PersistentFlags().StringVarP(&selector, "selector", "l", "", "selector")

    rootCmd.AddCommand(cmdEcho)
    _ = rootCmd.Execute()
}
[root@devops gotest]# go run main.go -e test -l a=b test
-l 

@marckhouzam Thanks for your feedback. I think it is a bug.

yxxhero commented 2 years ago
[root@devops gotest]# go run main.go -e=test -l=a=b test
test a=b

this is work fine.

marckhouzam commented 2 years ago

Thanks @yxxhero I can reproduce the bug. I don't have time to debug right now, but we'll need to run the debugger on it. I suspect a problem in cobra.stripFlags()

marckhouzam commented 2 years ago

Actually, I just remembered this issue a duplicate of #1777 which has a PR posted.