If I must manually check the config viper got and set the flag of cmd? #1266
-
I used However, the config root: ~/path/to/my/repo I need to manually get the value with root.go is like this: func init() {
cobra.OnInitialize(initConfig)
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.gclone.yaml)")
rootCmd.PersistentFlags().StringVarP(&repoRoot, "root", "r", "", "--root")
cobra.CheckErr(viper.BindPFlag("root", rootCmd.PersistentFlags().Lookup("root")))
}
// initConfig reads in config file and ENV variables if set.
func initConfig() {
viper.Debug()
if cfgFile != "" {
// Use config file from the flag.
viper.SetConfigFile(cfgFile)
} else {
// Find home directory.
home, err := os.UserHomeDir()
cobra.CheckErr(err)
// Search config in home directory with name ".gclone" (without extension).
viper.AddConfigPath(home)
viper.SetConfigType("yaml")
viper.SetConfigName(".gclone")
}
viper.AutomaticEnv() // read in environment variables that match
// If a config file is found, read it in.
if err := viper.ReadInConfig(); err == nil {
fmt.Fprintln(os.Stderr, "Using config file:", viper.ConfigFileUsed())
}
} I have tried to use |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
OK, I know how to use it now. I thought the variable Thanks, anyway. |
Beta Was this translation helpful? Give feedback.
OK, I know how to use it now.
I thought the variable
var
incobra.Flags().StringPVar(&var,...)
would be set automatically...I got to know that I was wrong. Viper will automatically got the var but all var should be retrived through
viper.Get*()
manually.Thanks, anyway.