cobra icon indicating copy to clipboard operation
cobra copied to clipboard

cmd.Flags().Int64Var: Defaultvalue wasn't being set if pass an invalid value

Open shiywang opened this issue 9 years ago • 8 comments

I have a test here:

func TestBug(t *testing.T) {
	cmd := &cobra.Command{Run: func(cmd *cobra.Command, args []string) {}}
	var a int64
	cmd.Flags().Int64Var(&a, "test", 999, "default number is 999")
	cmd.Flags().Set("test", "no-int")
	cmd.Run(cmd, []string{})
	i, err := cmd.Flags().GetInt64("test")
	fmt.Printf("value is %d %v", i, err)  //return 0 instead of 999
}

when we set flag test to an non-integer value like no-int it should return defaultValue 999 instead of 0

shiywang avatar Oct 30 '17 10:10 shiywang

it should return

Why? Default value is used only if flag is not provided.

n10v avatar Oct 30 '17 12:10 n10v

Default value is used only if flag is not provided.

so if flag is provided but with invalid value, the behavior is that type's initial value ? which is 0 in this case ?

ok, it maybe not an usual case since most of command line probably already exit at that time, I just want to make sure that behavior is what we expected.

shiywang avatar Oct 30 '17 13:10 shiywang

I just want to make sure that behavior is what we expected.

It's expected and even more cmd.Flags().Set("test", "no-int") should return error.

n10v avatar Oct 30 '17 14:10 n10v

Curious here, because I think I'm running into a similar issue.

I have a flag, --tail which has a default of 10, but I want the default to only be if you pass --tail and not defaulted to that unless the command is passed.

How would this be accomplished given you are saying the default value is only used if the flag isn't provided?

nesl247 avatar Jan 23 '19 21:01 nesl247

@nesl247, setting NoOptDefVal should work.

https://github.com/spf13/pflag#setting-no-option-default-values-for-flags

krisbudhram avatar May 05 '19 00:05 krisbudhram

@krisbudhram I'll try that out, thanks.

nesl247 avatar May 05 '19 15:05 nesl247

This issue is being marked as stale due to a long period of inactivity

github-actions[bot] avatar Apr 13 '20 00:04 github-actions[bot]

The setting of an invalid value should return an error at this point; perhaps cobra was using an older version of pflag at the time. https://github.com/spf13/pflag/commit/4995a3e9cc2102264d261ecf6350a612ea05eb87

Closing as done. Feel free to reopen if you know this is still an issue that you feel needs looked into.

johnSchnake avatar Mar 08 '22 17:03 johnSchnake