github.com/evanlouie/fabrikate@v0.17.4/cmd/root.go (about)

     1  package cmd
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  
     7  	"github.com/evanlouie/fabrikate/logger"
     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:   "fab",
    17  	Short: "Scalable GitOps for Kubernetes clusters",
    18  	Long:  "Scalable GitOps for Kubernetes clusters",
    19  
    20  	PersistentPreRunE: func(cmd *cobra.Command, args []string) (err error) {
    21  		verbose := cmd.Flag("verbose").Value.String()
    22  
    23  		if verbose == "true" {
    24  			logger.SetLevelDebug()
    25  		} else {
    26  			logger.SetLevelInfo()
    27  		}
    28  
    29  		return nil
    30  	},
    31  }
    32  
    33  // Execute adds all child commands to the root command and sets flags appropriately.
    34  // This is called by main.main(). It only needs to happen once to the rootCmd.
    35  func Execute() {
    36  	if err := rootCmd.Execute(); err != nil {
    37  		logger.Error(err)
    38  		os.Exit(1)
    39  	}
    40  }
    41  
    42  func init() {
    43  	cobra.OnInitialize(initConfig)
    44  
    45  	rootCmd.PersistentFlags().BoolP("verbose", "v", false, "Use verbose output logs")
    46  }
    47  
    48  // initConfig reads in config file and ENV variables if set.
    49  func initConfig() {
    50  	if cfgFile != "" {
    51  		// Use config file from the flag.
    52  		viper.SetConfigFile(cfgFile)
    53  	} else {
    54  		// Find home directory.
    55  		home, err := os.UserHomeDir()
    56  		if err != nil {
    57  			logger.Error(fmt.Sprintf("Getting home directory failed with: %s\n", err))
    58  			os.Exit(1)
    59  		}
    60  
    61  		// Search config in home directory with name ".fab" (without extension).
    62  		viper.AddConfigPath(home)
    63  		viper.SetConfigName(".fab")
    64  	}
    65  
    66  	viper.AutomaticEnv() // read in environment variables that match
    67  
    68  	// If a config file is found, read it in.
    69  	if err := viper.ReadInConfig(); err == nil {
    70  		logger.Debug(fmt.Sprintf("Using config file: %s\n", viper.ConfigFileUsed()))
    71  	}
    72  }