Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

When using a space to separate flags and values, the value in NoOptDefVal is always used #1962

Closed
galjoey opened this issue May 24, 2023 · 3 comments

Comments

@galjoey
Copy link

galjoey commented May 24, 2023

When using the option NoOptDefVal for flags to enable users to use a flag both as a switch and as a configuration, if the user provides the flag and value in the format --flag=value or -f=value NoOptDefVal works as expected, however when using a space to separate the flag and value the value is treated as missing even when supplied and the value in NoOptDefVal is applied instead.
Cobra Version: 1.7.0
OS: Windows 10

Assuming the below code:

func main() {
	execute := &cobra.Command{
		Use:   "execute",
		Short: "execute this test",
		Long:  "run the demo code to execute this test",
		Run:   func(cmd *cobra.Command, args []string) { fmt.Println(cmd.Flag("name").Value) },
	}
	execute.Flags().StringP("name", "n", "novalue", "specify the name")
	execute.Flag("name").NoOptDefVal = "noopt"

	execute.Execute()
}

When invoking the command go run cobra-demo -n=test the output is test as expected

When invoking the command go run cobra-demo -n test the output is noopt, however the expected output is test

@galjoey galjoey changed the title When using a space to separate flags and values, NoOptDefVal is used even when value is provided When using a space to separate flags and values, the value in NoOptDefVal is always used May 24, 2023
@jon4hz
Copy link

jon4hz commented Jun 9, 2023

I'm having the same issue with cobra v1.7.0 on linux.

@marckhouzam
Copy link
Collaborator

I believe this is correct behavior. When setting the NoOptDefVal field for a flag then only the = form can be used.

The NoOptDefVal field is used to specify a value when the flag is on the command line without any value. For example cobra-demo -n. But when this is enabled and the user provides cobra-demo -n test, how can cobra know if test is a value for the flag or an argument to the command? It cannot.

So, when NoOptDefVal is set, then only the = form can be used.

@marckhouzam
Copy link
Collaborator

Duplicate of #866

@marckhouzam marckhouzam marked this as a duplicate of #866 Jun 10, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants