1 /* 2 Copyright © 2020 Chris Mellard chris.mellard@icloud.com 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 package cmd 17 18 import ( 19 "fmt" 20 "os" 21 22 "github.com/mitchellh/go-homedir" 23 "github.com/spf13/cobra" 24 "github.com/spf13/viper" 25 ) 26 27 var cfgFile string 28 29 // rootCmd represents the base command when called without any subcommands 30 var rootCmd = &cobra.Command{ 31 Use: "docker-credential-acr-env", 32 Short: "Docker Helper program for Azure Container Registry", 33 } 34 35 // Execute adds all child commands to the root command and sets flags appropriately. 36 // This is called by main.main(). It only needs to happen once to the rootCmd. 37 func Execute() { 38 if err := rootCmd.Execute(); err != nil { 39 fmt.Println(err) 40 os.Exit(1) 41 } 42 } 43 44 func init() { 45 cobra.OnInitialize(initConfig) 46 47 rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.docker-credential-acr-env.yaml)") 48 } 49 50 // initConfig reads in config file and ENV variables if set. 51 func initConfig() { 52 if cfgFile != "" { 53 // Use config file from the flag. 54 viper.SetConfigFile(cfgFile) 55 } else { 56 // Find home directory. 57 home, err := homedir.Dir() 58 if err != nil { 59 fmt.Println(err) 60 os.Exit(1) 61 } 62 63 // Search config in home directory with name ".docker-credential-acr-env" (without extension). 64 viper.AddConfigPath(home) 65 viper.SetConfigName(".docker-credential-acr-env") 66 } 67 68 viper.AutomaticEnv() // read in environment variables that match 69 70 // If a config file is found, read it in. 71 if err := viper.ReadInConfig(); err == nil { 72 fmt.Println("Using config file:", viper.ConfigFileUsed()) 73 } 74 } 75