spf13 / cobra

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

Implement standard library compliant flag parsing #2192

Closed r10r closed 2 months ago

r10r commented 2 months ago

Hi there,

I'm a new cobra user who has used the standard libraries flag package in a lot of single command binaries. When implementing my first application with cobra I stumbled upon the flag parsing.

package main

import (
        "os"

        "github.com/spf13/cobra"
)

var myflag string

func NewRootCmd() *cobra.Command {
        return &cobra.Command{
                Run: func(cmd *cobra.Command, args []string) {
                        println(myflag)
                },
        }
}

var rootCmd = NewRootCmd()

func init() {
        rootCmd.PersistentFlags().StringVarP(&myflag, "myflag", "m", "", "just my flag")
}

func main() {
        err := rootCmd.Execute()
        if err != nil {
                os.Exit(1)
        }
}

Calling the application with a single dash will result in unexpected behaviour.

./test -myflag hello
yflag

Using the double dash gives the expected result

./test --myflag hello
hello

To me it happens quite often that I miss a dash when typing a long option without shell completion. The flag parsing from the library flag package is quite nice here and does not distinguish between a a single or a double dash.

One or two dashes may be used; they are equivalent.

See also https://pkg.go.dev/flag#hdr-Command_line_flag_syntax

Is it possible to introduce a setting in cobra to make the flag parsing (optionally) compliant with the flag package of the standard library ?

marckhouzam commented 2 months ago

Cobra supports multiple single letter flags strung together e.g., prog -abcd is equivalent to prog -a -b -c -d.

If you also have a long flag --abcd there would be ambiguity without the double --

r10r commented 2 months ago

@marckhouzam thanks for the explanation. i’ll see if I can add this to the FAQ