Skip to content

Instantly share code, notes, and snippets.

@jacobcase
Created Aug 11, 2017
Embed
What would you like to do?
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

jacobcase commented Aug 11, 2017

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