這是來(lái)自的一個(gè)片段my-tool/cmd/root.gofunc 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) }代碼是從cobracli 的腳手架過(guò)程生成的,即通過(guò)~/go/cobra/init my-tool --pkg-name github.com/something/my-tool我試圖暫時(shí)傳遞該config標(biāo)志來(lái)檢查程序是否正在處理它:? go run main.go --config "test" 但是,盡管我希望該init()函數(shù)能夠調(diào)用cobra.OnInitialize(initConfig)并解析該標(biāo)志,如行所示: rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.my-tool.yaml)")最后在聲明中看到這兩條消息之一if: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) }相反,我得到的只是 root 命令的help消息;這是為什么?編輯:從我看來(lái),通過(guò)添加一些打印語(yǔ)句,initConfig()永遠(yuǎn)不會(huì)調(diào)用(出于某種原因),即好像cobra.OnInitialize(initConfig)沒(méi)有執(zhí)行任何操作。
cobra go cli 庫(kù)忽略標(biāo)志
開(kāi)心每一天1111
2023-08-07 19:11:12