Skip to content

Instantly share code, notes, and snippets.

@jacobcase
Created August 11, 2017 22:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jacobcase/2ce2e3b26f4b361521aea686016331e2 to your computer and use it in GitHub Desktop.
Save jacobcase/2ce2e3b26f4b361521aea686016331e2 to your computer and use it in GitHub Desktop.
Viper doesn't dump CLI overrides for sub vipers
package main
import (
"encoding/json"
"fmt"
"os"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
var RootCmd = &cobra.Command{
Use: "vipertest",
}
var SubCmd = &cobra.Command{
Use: "subcmd",
Run: subRun,
}
func init() {
RootCmd.AddCommand(SubCmd)
RootCmd.PersistentFlags().StringP("log-level", "l", "warn", "log level")
SubCmd.PersistentFlags().String("value1", "y", "")
SubCmd.PersistentFlags().String("value2", "", "")
SubCmd.PersistentFlags().StringSlice("value3", []string{}, "")
viper.BindPFlag("log_level", RootCmd.PersistentFlags().Lookup("log-level"))
viper.BindPFlag("subcmd.value1", SubCmd.PersistentFlags().Lookup("value1"))
viper.BindPFlag("subcmd.value2", SubCmd.PersistentFlags().Lookup("value2"))
cobra.OnInitialize(cfgInit)
}
func cfgInit() {
viper.SetConfigFile("./test.yaml")
err := viper.ReadInConfig()
if err != nil {
panic(err)
}
fmt.Printf("ALL SETTINGS JSON\n")
b, err := json.MarshalIndent(viper.AllSettings(), "", " ")
if err != nil {
fmt.Println(err)
os.Exit(0)
}
fmt.Println(string(b))
fmt.Printf("SUB SETTINGS JSON\n")
b, err = json.MarshalIndent(viper.Sub("subcmd").AllSettings(), "", " ")
if err != nil {
fmt.Println(err)
os.Exit(0)
}
fmt.Println(string(b))
}
func subRun(cmd *cobra.Command, args []string) {
os.Exit(0)
}
func main() {
if err := RootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(-1)
}
}
@jacobcase
Copy link
Author

here is test.yaml that needs to be in the same directory

log_level: info
subcmd:
  value1: a

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment