cobra icon indicating copy to clipboard operation
cobra copied to clipboard

Combining shorthand flags before command names does not work

Open nicula-stripe opened this issue 5 months ago • 4 comments

How to reproduce:

  • Compile the following source code which defines some commands & flags (go build ./mycli.go):
package main

import (
	"fmt"
	"os"

	"github.com/spf13/cobra"
)

var (
	aFlag bool
	bFlag bool
	cFlag string
)

func main() {
	// Define commands
	var rootCmd = &cobra.Command{
		Use: "mycli",
	}
	var firstCmd = &cobra.Command{
		Use: "first",
	}
	var secondCmd = &cobra.Command{
		Use: "second",
		Run: func(cmd *cobra.Command, args []string) {
			if aFlag {
				fmt.Println("flag A is set")
			}
			if bFlag {
				fmt.Println("flag B is set")
			}
			if cFlag != "" {
				fmt.Printf("flag C is set with value: %s\n", cFlag)
			}
		},
	}

	// Define flags
	rootCmd.PersistentFlags().BoolVarP(&aFlag, "set-A", "A", false, "Set the A flag")
	rootCmd.PersistentFlags().BoolVarP(&bFlag, "set-B", "B", false, "Set the B flag")
	rootCmd.PersistentFlags().StringVarP(&cFlag, "set-C", "C", "", "Set the C flag with a value")

	firstCmd.AddCommand(secondCmd)
	rootCmd.AddCommand(firstCmd)

	if err := rootCmd.Execute(); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}
  • Notice how this command does not work:
$ ./mycli -ABC elephant first second
Error: unknown command "elephant" for "mycli"
Run 'mycli --help' for usage.
unknown command "elephant" for "mycli"
  • However, those commands work:
$ ./mycli -ABC=elephant first second
flag A is set
flag B is set
flag C is set with value: elephant
$ ./mycli first second -ABC elephant
flag A is set
flag B is set
flag C is set with value: elephant

So why does ./mycli -ABC elephant first second not work? It seems like it should have no problem noticing that the last flag in the bundle, -C, takes an argument, and therefore not consider elephant as a command name, but as an argument to -C.

Is this a bug, a missing feature, or intended behavior?

Thanks!

nicula-stripe avatar Sep 11 '24 13:09 nicula-stripe