You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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
The text was updated successfully, but these errors were encountered:
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
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.
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:
When invoking the command
go run cobra-demo -n=test
the output istest
as expectedWhen invoking the command
go run cobra-demo -n test
the output isnoopt
, however the expected output istest
The text was updated successfully, but these errors were encountered: