Created
August 11, 2017 22:15
-
-
Save jacobcase/2ce2e3b26f4b361521aea686016331e2 to your computer and use it in GitHub Desktop.
Viper doesn't dump CLI overrides for sub vipers
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 ( | |
"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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
here is
test.yaml
that needs to be in the same directory