1/* 2Copyright © 2020 NAME HERE <EMAIL ADDRESS> 3 4Licensed under the Apache License, Version 2.0 (the "License"); 5you may not use this file except in compliance with the License. 6You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10Unless required by applicable law or agreed to in writing, software 11distributed under the License is distributed on an "AS IS" BASIS, 12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13See the License for the specific language governing permissions and 14limitations under the License. 15*/ 16package cmd 17 18import ( 19 "fmt" 20 "github.com/spf13/cobra" 21 "os" 22 23 homedir "github.com/mitchellh/go-homedir" 24 "github.com/spf13/viper" 25) 26 27var cfgFile string 28 29// rootCmd represents the base command when called without any subcommands 30var rootCmd = &cobra.Command{ 31 Use: "testproject", 32 Short: "A brief description of your application", 33 Long: `A longer description that spans multiple lines and likely contains 34examples and usage of using your application. For example: 35 36Cobra is a CLI library for Go that empowers applications. 37This application is a tool to generate the needed files 38to quickly create a Cobra application.`, 39 // Uncomment the following line if your bare application 40 // has an action associated with it: 41 // Run: func(cmd *cobra.Command, args []string) { }, 42} 43 44// Execute adds all child commands to the root command and sets flags appropriately. 45// This is called by main.main(). It only needs to happen once to the rootCmd. 46func Execute() { 47 if err := rootCmd.Execute(); err != nil { 48 fmt.Println(err) 49 os.Exit(1) 50 } 51} 52 53func init() { 54 cobra.OnInitialize(initConfig) 55 56 // Here you will define your flags and configuration settings. 57 // Cobra supports persistent flags, which, if defined here, 58 // will be global for your application. 59 60 rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.testproject.yaml)") 61 62 // Cobra also supports local flags, which will only run 63 // when this action is called directly. 64 rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") 65} 66 67// initConfig reads in config file and ENV variables if set. 68func initConfig() { 69 if cfgFile != "" { 70 // Use config file from the flag. 71 viper.SetConfigFile(cfgFile) 72 } else { 73 // Find home directory. 74 home, err := homedir.Dir() 75 if err != nil { 76 fmt.Println(err) 77 os.Exit(1) 78 } 79 80 // Search config in home directory with name ".testproject" (without extension). 81 viper.AddConfigPath(home) 82 viper.SetConfigName(".testproject") 83 } 84 85 viper.AutomaticEnv() // read in environment variables that match 86 87 // If a config file is found, read it in. 88 if err := viper.ReadInConfig(); err == nil { 89 fmt.Println("Using config file:", viper.ConfigFileUsed()) 90 } 91} 92