package cmd import ( "fmt" "os" "github.com/mitchellh/go-homedir" "github.com/spf13/cobra" "github.com/spf13/viper" ) var RootCmd = &cobra.Command{ Use: "chenjian", Aliases: []string{"cj", "ccccjjjj"}, Short: "call me jack", Long: `A Fast and Flexible Static Site Generator built with love by spf13 and friends in Go. Complete documentation is available at https://o-my-chenjian.com`, Run: func(cmd *cobra.Command, args []string) { fmt.Printf("OK") }, } var cfgFile, projectBase, userLicense string func init() { cobra.OnInitialize(initConfig) // 在此可以定义自己的flag或者config设置,Cobra支持持久标签(persistent flag),它对于整个应用为全局 // 在StringVarP中需要填写`shorthand`,详细见pflag文档 RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (defalut in $HOME/.cobra.yaml)") RootCmd.PersistentFlags().StringVarP(&projectBase, "projectbase", "b", "", "base project directory eg. github.com/spf13/") RootCmd.PersistentFlags().StringP("author", "a", "YOUR NAME", "Author name for copyright attribution") RootCmd.PersistentFlags().StringVarP(&userLicense, "license", "l", "", "Name of license for the project (can provide `licensetext` in config)") RootCmd.PersistentFlags().Bool("viper", true, "Use Viper for configuration") // Cobra同样支持局部标签(local flag),并只在直接调用它时运行 RootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") // 使用viper可以绑定flag viper.BindPFlag("author", RootCmd.PersistentFlags().Lookup("author")) viper.BindPFlag("projectbase", RootCmd.PersistentFlags().Lookup("projectbase")) viper.BindPFlag("useViper", RootCmd.PersistentFlags().Lookup("viper")) viper.SetDefault("author", "NAME HERE ") viper.SetDefault("license", "apache") } func Execute() { RootCmd.Execute() } func initConfig() { // 勿忘读取config文件,无论是从cfgFile还是从home文件 if cfgFile != "" { viper.SetConfigName(cfgFile) } else { // 找到home文件 home, err := homedir.Dir() if err != nil { fmt.Println(err) os.Exit(1) } // 在home文件夹中搜索以“.cobra”为名称的config viper.AddConfigPath(home) viper.SetConfigName(".cobra") } // 读取符合的环境变量 viper.AutomaticEnv() if err := viper.ReadInConfig(); err != nil { fmt.Println("Can not read config:", viper.ConfigFileUsed()) } }