makeshift/cmd/root.go

79 lines
1.6 KiB
Go

package cmd
import (
"fmt"
"os"
"slices"
"strings"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/spf13/cobra"
)
var (
host string
path string
outputPath string
rootPath string
logLevel string
profile string
plugins []string
timeout int
)
var rootCmd = cobra.Command{
Use: "configurator",
Short: "Extensible configuration builder to download files",
PersistentPreRun: func(cmd *cobra.Command, args []string) {
// set the logging level
level, err := strToLogLevel(logLevel)
if err != nil {
log.Error().Err(err).Msg("failed to convert log level argument")
os.Exit(1)
}
zerolog.SetGlobalLevel(level)
},
}
func Execute() {
// run the main program
if err := rootCmd.Execute(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
func init() {
// initialize the config a single time
rootCmd.PersistentFlags().StringVarP(&logLevel, "log-level", "l", "info", "Set the log level output")
}
func strToLogLevel(ll string) (zerolog.Level, error) {
levels := []string{"debug", "info", "warn", "disabled"}
if index := slices.Index(levels, ll); index >= 0 {
// handle special case to map index == 3 to zerolog.Disabled == 7
switch index {
case 3:
return zerolog.Disabled, nil
}
return zerolog.Level(index), nil
}
return -100, fmt.Errorf(
"invalid log level (options: %s)", strings.Join(levels, ", "),
) // use 'info' by default
}
func setenv(v *string, key string) {
t := os.Getenv(key)
if t != "" {
*v = t
}
}
// func setenv(cmd *cobra.Command, varname string, envvar string) {
// v := os.Getenv(envvar)
// if v != "" {
// cmd.Flags().Set(varname, v)
// }
// }