Last active
June 22, 2023 16:50
-
-
Save gesquive/c36501fbd84ecab00d3ff2c9502020f9 to your computer and use it in GitHub Desktop.
test script for https://github.com/spf13/viper/issues/233
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"github.com/spf13/cobra" | |
"github.com/spf13/viper" | |
) | |
func main() { | |
var flagValue string | |
var cmdPing = &cobra.Command{ | |
Use: "ping", | |
Short: "ping command", | |
Long: `ping command`, | |
Run: func(cmd *cobra.Command, args []string) { | |
fmt.Println("ping called") | |
fmt.Printf("flag: %s\n", viper.GetString("flag")) | |
}, | |
} | |
var cmdPong = &cobra.Command{ | |
Use: "pong", | |
Short: "pong command", | |
Long: `pong command`, | |
Run: func(cmd *cobra.Command, args []string) { | |
fmt.Println("pong called") | |
fmt.Printf("flag: %s\n", viper.GetString("flag")) | |
}, | |
} | |
cmdPing.Flags().StringP("flag", "f", "", "testing flag") | |
cmdPong.Flags().StringP("flag", "f", "", "testing flag") | |
viper.BindPFlag("flag", cmdPing.Flags().Lookup("flag")) | |
viper.BindPFlag("flag", cmdPong.Flags().Lookup("flag")) | |
viper.SetDefault("flag", "") | |
var rootCmd = &cobra.Command{Use: "app"} | |
rootCmd.AddCommand(cmdPing, cmdPong) | |
rootCmd.Execute() | |
} |
This is a well known workaround, not a fix. It doesn't fix the fact that you cannot configure the command with flags as intended. There is unintended behavior when you use the BindPFlag function as intended.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The problem:
The
fixworkaround: