refactor
This commit is contained in:
64
cmd/ots/root.go
Normal file
64
cmd/ots/root.go
Normal file
@@ -0,0 +1,64 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
var (
|
||||
// Global flags
|
||||
jsonLog bool
|
||||
logLevel string
|
||||
)
|
||||
|
||||
// rootCmd represents the base command when called without any subcommands
|
||||
var rootCmd = &cobra.Command{
|
||||
Use: "ots",
|
||||
Short: "OpenTimestamps CLI tool",
|
||||
Long: `A command-line interface for OpenTimestamps operations.
|
||||
It allows creating, verifying and upgrading timestamps for files.`,
|
||||
PersistentPreRun: setupLogging,
|
||||
}
|
||||
|
||||
func init() {
|
||||
// Global flags for all commands
|
||||
rootCmd.PersistentFlags().BoolVar(&jsonLog, "json", false, "Use JSON format for logging")
|
||||
rootCmd.PersistentFlags().StringVar(&logLevel, "log-level", "info", "Log level: debug, info, warn, error")
|
||||
|
||||
// Add subcommands
|
||||
rootCmd.AddCommand(createCmd)
|
||||
rootCmd.AddCommand(verifyCmd)
|
||||
rootCmd.AddCommand(upgradeCmd)
|
||||
rootCmd.AddCommand(infoCmd)
|
||||
}
|
||||
|
||||
// setupLogging configures the global logger based on the flags
|
||||
func setupLogging(cmd *cobra.Command, args []string) {
|
||||
loggerOptions := slog.HandlerOptions{}
|
||||
|
||||
switch strings.ToLower(logLevel) {
|
||||
case "debug":
|
||||
loggerOptions.Level = slog.LevelDebug
|
||||
case "info":
|
||||
loggerOptions.Level = slog.LevelInfo
|
||||
case "warn":
|
||||
loggerOptions.Level = slog.LevelWarn
|
||||
case "error":
|
||||
loggerOptions.Level = slog.LevelError
|
||||
default:
|
||||
loggerOptions.Level = slog.LevelInfo
|
||||
}
|
||||
|
||||
var logHandler slog.Handler
|
||||
if jsonLog {
|
||||
logHandler = slog.NewJSONHandler(os.Stdout, &loggerOptions)
|
||||
} else {
|
||||
logHandler = slog.NewTextHandler(os.Stdout, &loggerOptions)
|
||||
}
|
||||
|
||||
logger := slog.New(logHandler)
|
||||
slog.SetDefault(logger)
|
||||
}
|
||||
Reference in New Issue
Block a user