Here is an snippet from my-tool/cmd/root.go
func Execute() {
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
func init() {
cobra.OnInitialize(initConfig)
// Here you will define your flags and configuration settings.
// Cobra supports persistent flags, which, if defined here,
// will be global for your application.
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.my-tool.yaml)")
// Cobra also supports local flags, which will only run
// when this action is called directly.
rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
// initConfig reads in config file and ENV variables if set.
func initConfig() {
if cfgFile != "" {
fmt.Println("Config file set")
// Use config file from the flag.
viper.SetConfigFile(cfgFile)
} else {
fmt.Println("Config file NOT set")
// Find home directory.
home, err := homedir.Dir()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
The code has been generated from the scaffolding process of cobra
cli, i.e. via ~/go/cobra/init my-tool --pkg-name github.com/something/my-tool
I am trying to tentatively pass the config
flag to check if the program is handling it:
▶ go run main.go --config "test"
However, though I 'd expect the init()
function to make the call to cobra.OnInitialize(initConfig)
and parse the flag as indicated by line:
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.my-tool.yaml)")
and finally to see one of those two messages in the if
statement:
func initConfig() {
if cfgFile != "" {
fmt.Println("Config file set")
// Use config file from the flag.
viper.SetConfigFile(cfgFile)
} else {
fmt.Println("Config file NOT set")
// Find home directory.
home, err := homedir.Dir()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
instead, all I get is the root command's help
message; why is that?
edit: from what I see by adding some print statements, the initConfig()
is never called (for some reason), i.e. as if cobra.OnInitialize(initConfig)
does not do anything.