github.com/awslabs/clencli@v0.0.0-20210514234156-7ecf17182a20/cobra/cmd/root.go (about) 1 /* 2 Copyright © 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 Licensed under the Apache License, Version 2.0 (the "License"); 4 you may not use this file except in compliance with the License. 5 You may obtain a copy of the License at 6 7 http://www.apache.org/licenses/LICENSE-2.0 8 9 Unless required by applicable law or agreed to in writing, software 10 distributed under the License is distributed on an "AS IS" BASIS, 11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 See the License for the specific language governing permissions and 13 limitations under the License. 14 */ 15 16 package cmd 17 18 import ( 19 "fmt" 20 "os" 21 22 "github.com/spf13/cobra" 23 24 "github.com/awslabs/clencli/cobra/aid" 25 "github.com/awslabs/clencli/cobra/controller" 26 27 "github.com/spf13/viper" 28 ) 29 30 var rootCmd = controller.RootCmd() 31 32 // Execute adds all child commands to the root command and sets flags appropriately. 33 // This is called by main.main(). It only needs to happen once to the rootCmd. 34 func Execute() { 35 if err := rootCmd.Execute(); err != nil { 36 fmt.Println(err) 37 os.Exit(1) 38 } 39 } 40 41 func init() { 42 cobra.OnInitialize(initConfig) 43 44 rootCmd.PersistentFlags().StringP("verbosity", "v", "error", "Valid log level:panic,fatal,error,warn,info,debug,trace).") 45 rootCmd.PersistentFlags().Bool("log", true, "Enable or disable logs (can be found at ./clencli/log.json). Log outputs will be redirected default output if disabled.") 46 rootCmd.PersistentFlags().String("log-file-path", "clencli/log.json", "Log file path. Requires log=true, ignored otherwise.") 47 } 48 49 // initConfig reads in config file and ENV variables if set. 50 func initConfig() { 51 app := aid.GetAppInfo() 52 viper.AddConfigPath(app.ConfigurationsDir) // global directory 53 viper.SetConfigName(app.ConfigurationsName) 54 viper.AutomaticEnv() // read in environment variables that match 55 56 // If a config file is found, read it in. 57 if err := viper.ReadInConfig(); err == nil { 58 fmt.Println("using config file:", viper.ConfigFileUsed()) 59 } 60 61 verbosity, err := rootCmd.Flags().GetString("verbosity") 62 if err != nil { 63 fmt.Printf("unable to read flag verbosity\n%v", err) 64 } 65 66 log, err := rootCmd.Flags().GetBool("log") 67 if err != nil { 68 fmt.Printf("unable to read flag err\n%v", err) 69 } 70 71 logFilePath, err := rootCmd.Flags().GetString("log-file-path") 72 if err != nil { 73 fmt.Printf("unable to read flag log-file-path\n%v", err) 74 } 75 76 if log && logFilePath != "" { 77 if err := aid.SetupLoggingLevel(verbosity); err == nil { 78 fmt.Printf("logging level: %s\n", verbosity) 79 } 80 81 if err := aid.SetupLoggingOutput(logFilePath); err == nil { 82 fmt.Printf("logging path: %s\n", logFilePath) 83 } 84 } 85 86 }