github.com/line/ostracon@v1.0.10-0.20230328032236-7f20145f065d/cmd/ostracon/commands/root.go (about)

     1  package commands
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  	"strings"
     7  
     8  	"github.com/spf13/cobra"
     9  	"github.com/spf13/viper"
    10  
    11  	cfg "github.com/line/ostracon/config"
    12  	"github.com/line/ostracon/libs/cli"
    13  	"github.com/line/ostracon/libs/log"
    14  )
    15  
    16  var (
    17  	config = cfg.DefaultConfig()
    18  	logger = log.NewOCLogger(log.NewSyncWriter(os.Stdout))
    19  )
    20  
    21  func init() {
    22  	registerFlagsRootCmd(RootCmd)
    23  }
    24  
    25  func registerFlagsRootCmd(cmd *cobra.Command) {
    26  	cmd.PersistentFlags().String("log_level", config.LogLevel, "log level")
    27  }
    28  
    29  // ParseConfig retrieves the default environment configuration,
    30  // sets up the Ostracon root and ensures that the root exists
    31  func ParseConfig() (*cfg.Config, error) {
    32  	conf := cfg.DefaultConfig()
    33  	err := viper.Unmarshal(conf)
    34  	if err != nil {
    35  		return nil, err
    36  	}
    37  	conf.SetRoot(conf.RootDir)
    38  	cfg.EnsureRoot(conf.RootDir)
    39  	if err := conf.ValidateBasic(); err != nil {
    40  		return nil, fmt.Errorf("error in config file: %v", err)
    41  	}
    42  	return conf, nil
    43  }
    44  
    45  // RootCmd is the root command for Ostracon core.
    46  var RootCmd = &cobra.Command{
    47  	Use:   "ostracon",
    48  	Short: "BFT state machine replication for applications in any programming languages",
    49  	PersistentPreRunE: func(cmd *cobra.Command, args []string) (err error) {
    50  		if cmd.Name() == VersionCmd.Name() {
    51  			return nil
    52  		}
    53  
    54  		config, err = ParseConfig()
    55  		if err != nil {
    56  			return err
    57  		}
    58  
    59  		if config.LogFormat == cfg.LogFormatJSON {
    60  			logger = log.NewOCJSONLogger(log.NewSyncWriter(os.Stdout))
    61  		}
    62  
    63  		logger, err = log.ParseLogLevel(config.LogLevel, logger, cfg.DefaultLogLevel)
    64  		if err != nil {
    65  			return err
    66  		}
    67  
    68  		if viper.GetBool(cli.TraceFlag) {
    69  			logger = log.NewTracingLogger(logger)
    70  		}
    71  
    72  		logger = logger.With("module", "main")
    73  		return nil
    74  	},
    75  }
    76  
    77  // deprecateSnakeCase is a util function for 0.34.1. Should be removed in 0.35
    78  func deprecateSnakeCase(cmd *cobra.Command, args []string) {
    79  	if strings.Contains(cmd.CalledAs(), "_") {
    80  		fmt.Println("Deprecated: snake_case commands will be replaced by hyphen-case commands in the next major release")
    81  	}
    82  }