Skip to content

Instantly share code, notes, and snippets.

@gesquive
Last active June 22, 2023 16:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gesquive/c36501fbd84ecab00d3ff2c9502020f9 to your computer and use it in GitHub Desktop.
Save gesquive/c36501fbd84ecab00d3ff2c9502020f9 to your computer and use it in GitHub Desktop.
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()
}
@miparnisari
Copy link

miparnisari commented Jun 21, 2023

The problem:

[21/06/23 4:08:58] ~/GitHub/demo (master) $ ./app  ping --flag hello
ping called
flag: hello
[21/06/23 4:08:59] ~/GitHub/demo (master) $ ./app  pong --flag hello
pong called
flag: 

The fix workaround:

package main

import (
	"fmt"

	"github.com/spf13/cobra"
	"github.com/spf13/viper"
)

func main() {
	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"))
		},
		PreRun: func(cmd *cobra.Command, args []string) {
			viper.BindPFlag("flag", cmd.Flags().Lookup("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"))
		},
		PreRun: func(cmd *cobra.Command, args []string) {
			viper.BindPFlag("flag", cmd.Flags().Lookup("flag"))
		},
	}

	cmdPing.Flags().StringP("flag", "f", "", "testing flag")
	cmdPong.Flags().StringP("flag", "f", "", "testing flag")

	viper.SetDefault("flag", "")

	var rootCmd = &cobra.Command{Use: "app"}
	rootCmd.AddCommand(cmdPing, cmdPong)
	rootCmd.Execute()
}

@gesquive
Copy link
Author

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