viper: Same flag name for different cobra commands does not work

I’m not sure if this is expected behaviour or not.

I have a decryptCmd and encryptCmd cobra commands.

They both have flag message.

func init() {
    RootCmd.AddCommand(encryptCmd)
    encryptCmd.Flags().StringP("message", "m", "teststring", "secret unencrypted base64")
    viper.BindPFlags(encryptCmd.Flags())
}
func init() {
    RootCmd.AddCommand(decryptCmd)
    decryptCmd.Flags().StringP("message", "m", "teststring", "base64 encrypted secret")
    viper.BindPFlags(decryptCmd.Flags())
}

Does viper.GetString() work globally across commands or is it command specific? Because when flags have the same name but for different commands then viper can not get the flag value consistently.

About this issue

  • Original URL
  • State: open
  • Created 10 years ago
  • Reactions: 47
  • Comments: 16

Commits related to this issue

Most upvoted comments

The issue is that init function is executed by go for each command automatically. The following solution allows to us to keep using the global viper, but only register the binds if a command is executed.

var sub1Cmd = &cobra.Command{
   PreRun: func(cmd *cobra.Command, args []string) {
		viper.BindPFlag("message", cmd.Flags().Lookup("message"))
   },
   ...
}

var sub2Cmd = &cobra.Command{
   PreRun: func(cmd *cobra.Command, args []string) {
		viper.BindPFlag("message", cmd.Flags().Lookup("message"))
   },
   ...
}

See https://github.com/spf13/cobra#prerun-and-postrun-hooks for more details.

I got bitten by this too. The documentation/readme should not encourage bad design by abusing init() functions like this. This doesn’t work because you are mutating Viper configuration and binding options to keys in viper’s state that are dynamically bound to the sub-command being executed. Doing it in init() seems wrong here.

I don’t call doing this in PreRiun() a “work-around” at all; but the correct way to bind viper flags (for lack of any other documented accepted way).

Bind your viper flags in PreRun() or Ruin() -- **NOT** init()`.

Just ran into this myself too thought I was going crazy, ended up using the workaround in https://github.com/mook-as/fissile/commit/ebd1ad311ea40b474688182d5ce9babd88d163e0 and everything is happy again.

Wrote a really fast example case for this while debugging it myself.

https://gist.github.com/gesquive/c36501fbd84ecab00d3ff2c9502020f9

Kind of crazy that this bug has been around for a year now.

This workaround is working for me. Bind the flag again in every subCmd

Run: func(cmd *cobra.Command, args []string) {
		
		// workaround for https://github.com/spf13/viper/issues/233
		viper.BindPFlag("user", cmd.Flags().Lookup("user"))

		user := viper.GetString("user")