github.com/stellar/stellar-etl@v1.0.1-0.20240312145900-4874b6bf2b89/cmd/root.go (about)

     1  package cmd
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  
     7  	"github.com/mitchellh/go-homedir"
     8  	"github.com/spf13/cobra"
     9  	"github.com/spf13/viper"
    10  
    11  	"github.com/stellar/stellar-etl/internal/utils"
    12  )
    13  
    14  var cfgFile string
    15  
    16  var cmdLogger = utils.NewEtlLogger()
    17  
    18  // rootCmd represents the base command when called without any subcommands
    19  var rootCmd = &cobra.Command{
    20  	Use:   "stellar-etl",
    21  	Short: "Stellar Development Foundation ETL.",
    22  	Long:  `A tool to extract data from the historical record of the Stellar network.`,
    23  	// Uncomment the following line if your bare application
    24  	// has an action associated with it:
    25  	//	Run: func(cmd *cobra.Command, args []string) { },
    26  }
    27  
    28  // Execute adds all child commands to the root command and sets flags appropriately.
    29  // This is called by main.main(). It only needs to happen once to the rootCmd.
    30  func Execute() {
    31  	if err := rootCmd.Execute(); err != nil {
    32  		fmt.Println(err)
    33  		os.Exit(1)
    34  	}
    35  }
    36  
    37  func init() {
    38  	cobra.OnInitialize(initConfig)
    39  
    40  	// Here you will define your flags and configuration settings.
    41  	// Cobra supports persistent flags, which, if defined here,
    42  	// will be global for your application.
    43  
    44  	rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.stellar-etl.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 ".stellar-etl" (without extension).
    65  		viper.AddConfigPath(home)
    66  		viper.SetConfigName(".stellar-etl")
    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  }