github.com/cosmos/cosmos-sdk@v0.50.10/server/cmd/execute.go (about)

     1  package cmd
     2  
     3  import (
     4  	"context"
     5  
     6  	cmtcli "github.com/cometbft/cometbft/libs/cli"
     7  	"github.com/rs/zerolog"
     8  	"github.com/spf13/cobra"
     9  
    10  	"github.com/cosmos/cosmos-sdk/client"
    11  	"github.com/cosmos/cosmos-sdk/client/flags"
    12  	"github.com/cosmos/cosmos-sdk/server"
    13  )
    14  
    15  // Execute executes the root command of an application. It handles creating a
    16  // server context object with the appropriate server and client objects injected
    17  // into the underlying stdlib Context. It also handles adding core CLI flags,
    18  // specifically the logging flags. It returns an error upon execution failure.
    19  func Execute(rootCmd *cobra.Command, envPrefix, defaultHome string) error {
    20  	// Create and set a client.Context on the command's Context. During the pre-run
    21  	// of the root command, a default initialized client.Context is provided to
    22  	// seed child command execution with values such as AccountRetriever, Keyring,
    23  	// and a CometBFT RPC. This requires the use of a pointer reference when
    24  	// getting and setting the client.Context. Ideally, we utilize
    25  	// https://github.com/spf13/cobra/pull/1118.
    26  	ctx := CreateExecuteContext(context.Background())
    27  
    28  	rootCmd.PersistentFlags().String(flags.FlagLogLevel, zerolog.InfoLevel.String(), "The logging level (trace|debug|info|warn|error|fatal|panic|disabled or '*:<level>,<key>:<level>')")
    29  	// NOTE: The default logger is only checking for the "json" value, any other value will default to plain text.
    30  	rootCmd.PersistentFlags().String(flags.FlagLogFormat, "plain", "The logging format (json|plain)")
    31  	rootCmd.PersistentFlags().Bool(flags.FlagLogNoColor, false, "Disable colored logs")
    32  
    33  	executor := cmtcli.PrepareBaseCmd(rootCmd, envPrefix, defaultHome)
    34  	return executor.ExecuteContext(ctx)
    35  }
    36  
    37  // CreateExecuteContext returns a base Context with server and client context
    38  // values initialized.
    39  func CreateExecuteContext(ctx context.Context) context.Context {
    40  	srvCtx := server.NewDefaultContext()
    41  	ctx = context.WithValue(ctx, client.ClientContextKey, &client.Context{})
    42  	ctx = context.WithValue(ctx, server.ServerContextKey, srvCtx)
    43  
    44  	return ctx
    45  }