I want to validate my int64
flag to make sure that its not being recognised as a octal number (the value must not start with 0
, if it does, I should be able to trim the leading 0
before assigning the value to the flag).
This is how I create the command:
var jobId int64
func newGetJobCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "job",
RunE: func(cmd *cobra.Command, args []string) error {
//some processing code here that accesses `job-id` flag value
return nil
},
}
flagSet := cmd.PersistentFlags()
flagSet.Int64Var(&jobId, "job-id", 0, "Job Id.")
return cmd
}
This job
is a sub command to get
command and its used like this:
my-cli get job --job-id 065
Expectation: the code is expecting jobId
to be 65, but because golang treats numbers leading with 0
to be octal, jobId when accessed in the code comes as 53 (which is the octal representation of 65).
I want to be able to somehow validate the input vale of job-id
flag and trim the leading zeros before it's accessed in the RunE
function.
workaround:
I have made jobId
as string and bind it like this: flagSet.StringVar(&jobId, "job-id", 0, "Job Id.")
, then later in my code I trim the leading zeros and parse it to an int64
. But this is not ideal because the command.Help()
help message now documents job-id
flag as a string, which is misleading because in reality it is supposed to be an int64