|
| 1 | +package cmd |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "os" |
| 6 | + |
| 7 | + homedir "github.com/mitchellh/go-homedir" |
| 8 | + "github.com/spf13/cobra" |
| 9 | + "github.com/spf13/viper" |
| 10 | +) |
| 11 | + |
| 12 | +var cfgFile string |
| 13 | + |
| 14 | +// rootCmd represents the base command when called without any subcommands |
| 15 | +var rootCmd = &cobra.Command{ |
| 16 | + Use: "h-cli", |
| 17 | + Short: "A brief description of your application", |
| 18 | + Long: `A longer description that spans multiple lines and likely contains |
| 19 | +examples and usage of using your application. For example: |
| 20 | +
|
| 21 | +Cobra is a CLI library for Go that empowers applications. |
| 22 | +This application is a tool to generate the needed files |
| 23 | +to quickly create a Cobra application.`, |
| 24 | + // Uncomment the following line if your bare application |
| 25 | + // has an action associated with it: |
| 26 | + // Run: func(cmd *cobra.Command, args []string) { }, |
| 27 | +} |
| 28 | + |
| 29 | +// Execute adds all child commands to the root command and sets flags appropriately. |
| 30 | +// This is called by main.main(). It only needs to happen once to the rootCmd. |
| 31 | +func Execute() { |
| 32 | + if err := rootCmd.Execute(); err != nil { |
| 33 | + fmt.Println(err) |
| 34 | + os.Exit(1) |
| 35 | + } |
| 36 | +} |
| 37 | + |
| 38 | +func init() { |
| 39 | + cobra.OnInitialize(initConfig) |
| 40 | + |
| 41 | + // Here you will define your flags and configuration settings. |
| 42 | + // Cobra supports persistent flags, which, if defined here, |
| 43 | + // will be global for your application. |
| 44 | + rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.h-cli.yaml)") |
| 45 | + |
| 46 | + // Cobra also supports local flags, which will only run |
| 47 | + // when this action is called directly. |
| 48 | + rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") |
| 49 | +} |
| 50 | + |
| 51 | +// initConfig reads in config file and ENV variables if set. |
| 52 | +func initConfig() { |
| 53 | + if cfgFile != "" { |
| 54 | + // Use config file from the flag. |
| 55 | + viper.SetConfigFile(cfgFile) |
| 56 | + } else { |
| 57 | + // Find home directory. |
| 58 | + home, err := homedir.Dir() |
| 59 | + if err != nil { |
| 60 | + fmt.Println(err) |
| 61 | + os.Exit(1) |
| 62 | + } |
| 63 | + |
| 64 | + // Search config in home directory with name ".h-cli" (without extension). |
| 65 | + viper.AddConfigPath(home) |
| 66 | + viper.SetConfigName(".h-cli") |
| 67 | + } |
| 68 | + |
| 69 | + viper.AutomaticEnv() // read in environment variables that match |
| 70 | + |
| 71 | + // If a config file is found, read it in. |
| 72 | + if err := viper.ReadInConfig(); err == nil { |
| 73 | + fmt.Println("Using config file:", viper.ConfigFileUsed()) |
| 74 | + } |
| 75 | +} |
0 commit comments