眼眸繁星
以下内容:var rootCmd = &cobra.Command{ //... PersistentPreRunE: writeConfig, //if --writeCfg, write viper config file and exit}func writeConfig(cmd *cobra.Command, args []string) error { if !writeCfg { return nil } cfg := viper.New() for k, v := range viper.AllSettings() { switch k { case "writecfg", "config", "dryrun": //do not propagate these default: //TODO: also check for zero values and exclude cfg.Set(k, v) } } if cfgFile == "" { filename := "." + os.Args[0] + ".yaml" home, err := os.UserHomeDir() cobra.CheckErr(err) cfgFile = filepath.Join(home, filename) } cfg.SetConfigFile(cfgFile) var err error if _, err = os.Stat(cfgFile); err != nil { err = os.WriteFile(cfgFile, nil, 0644) cobra.CheckErr(err) } err = cfg.WriteConfig() cobra.CheckErr(err) fmt.Println("config written successfully:") f, err := os.Open(cfgFile) cobra.CheckErr(err) defer f.Close() _, err = io.Copy(os.Stdout, f) cobra.CheckErr(err) os.Exit(0) return nil //unreachable}