Skip to content

Commit

Permalink
refactor: move setup CLI to only run once in root command
Browse files Browse the repository at this point in the history
Signed-off-by: Philip Laine <[email protected]>
  • Loading branch information
phillebaba committed Jul 19, 2024
1 parent 1e4399e commit d4c688a
Show file tree
Hide file tree
Showing 8 changed files with 61 additions and 67 deletions.
48 changes: 20 additions & 28 deletions src/cmd/common/setup.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,43 +5,38 @@
package common

import (
"errors"
"fmt"
"io"
"os"
"time"

"github.com/pterm/pterm"
"github.com/zarf-dev/zarf/src/config"
"github.com/zarf-dev/zarf/src/config/lang"

"github.com/zarf-dev/zarf/src/pkg/message"
)

// LogLevelCLI holds the log level as input from a command
var LogLevelCLI string

// SetupCLI sets up the CLI logging, interrupt functions, and more
func SetupCLI() {
match := map[string]message.LogLevel{
"warn": message.WarnLevel,
"info": message.InfoLevel,
"debug": message.DebugLevel,
"trace": message.TraceLevel,
}

if config.NoColor {
func SetupCLI(logLevel string, skipLogFile, noColor bool) error {
if noColor {
message.DisableColor()
}

printViperConfigUsed()

// No log level set, so use the default
if LogLevelCLI != "" {
if lvl, ok := match[LogLevelCLI]; ok {
message.SetLogLevel(lvl)
message.Debug("Log level set to " + LogLevelCLI)
} else {
message.Warn(lang.RootCmdErrInvalidLogLevel)
if logLevel != "" {
match := map[string]message.LogLevel{
"warn": message.WarnLevel,
"info": message.InfoLevel,
"debug": message.DebugLevel,
"trace": message.TraceLevel,
}
lvl, ok := match[logLevel]
if !ok {
return errors.New("invalid log level, valid options are warn, info, debug, and trace")
}
message.SetLogLevel(lvl)
message.Debug("Log level set to " + logLevel)
}

// Disable progress bars for CI envs
Expand All @@ -50,21 +45,18 @@ func SetupCLI() {
message.NoProgress = true
}

if !config.SkipLogFile {
if !skipLogFile {
ts := time.Now().Format("2006-01-02-15-04-05")

f, err := os.CreateTemp("", fmt.Sprintf("zarf-%s-*.log", ts))
if err != nil {
message.WarnErr(err, "Error creating a log file in a temporary directory")
return
return fmt.Errorf("could not create a log file in a the temporary directory: %w", err)
}
logFile, err := message.UseLogFile(f)
if err != nil {
message.WarnErr(err, "Error saving a log file to a temporary directory")
return
return fmt.Errorf("could not save a log file to the temporary directory: %w", err)
}

pterm.SetDefaultOutput(io.MultiWriter(os.Stderr, logFile))
message.Notef("Saving log file to %s", f.Name())
}
return nil
}
36 changes: 28 additions & 8 deletions src/cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,20 +26,40 @@ import (
var (
// Default global config for the packager
pkgConfig = types.PackagerConfig{}
// LogLevelCLI holds the log level as input from a command
LogLevelCLI string
// SkipLogFile is a flag to skip logging to a file
SkipLogFile bool
// NoColor is a flag to disable colors in output
NoColor bool
)

var rootCmd = &cobra.Command{
Use: "zarf COMMAND",
PersistentPreRun: func(cmd *cobra.Command, _ []string) {
PersistentPreRunE: func(cmd *cobra.Command, _ []string) error {
// Skip for vendor-only commands
if common.CheckVendorOnlyFromPath(cmd) {
return
return nil
}
// Don't log the help command

skipLogFile := SkipLogFile

// Dont write tool commands to file.
comps := strings.Split(cmd.CommandPath(), " ")
if len(comps) > 1 && comps[1] == "tools" {
skipLogFile = true
}

// Dont write help command to file.
if cmd.Parent() == nil {
config.SkipLogFile = true
skipLogFile = true
}

err := common.SetupCLI(LogLevelCLI, skipLogFile, NoColor)
if err != nil {
return err
}
common.SetupCLI()
return nil
},
Short: lang.RootCmdShort,
Long: lang.RootCmdLong,
Expand Down Expand Up @@ -89,11 +109,11 @@ func init() {

v := common.InitViper()

rootCmd.PersistentFlags().StringVarP(&common.LogLevelCLI, "log-level", "l", v.GetString(common.VLogLevel), lang.RootCmdFlagLogLevel)
rootCmd.PersistentFlags().StringVarP(&LogLevelCLI, "log-level", "l", v.GetString(common.VLogLevel), lang.RootCmdFlagLogLevel)
rootCmd.PersistentFlags().StringVarP(&config.CLIArch, "architecture", "a", v.GetString(common.VArchitecture), lang.RootCmdFlagArch)
rootCmd.PersistentFlags().BoolVar(&config.SkipLogFile, "no-log-file", v.GetBool(common.VNoLogFile), lang.RootCmdFlagSkipLogFile)
rootCmd.PersistentFlags().BoolVar(&SkipLogFile, "no-log-file", v.GetBool(common.VNoLogFile), lang.RootCmdFlagSkipLogFile)
rootCmd.PersistentFlags().BoolVar(&message.NoProgress, "no-progress", v.GetBool(common.VNoProgress), lang.RootCmdFlagNoProgress)
rootCmd.PersistentFlags().BoolVar(&config.NoColor, "no-color", v.GetBool(common.VNoColor), lang.RootCmdFlagNoColor)
rootCmd.PersistentFlags().BoolVar(&NoColor, "no-color", v.GetBool(common.VNoColor), lang.RootCmdFlagNoColor)
rootCmd.PersistentFlags().StringVar(&config.CommonOptions.CachePath, "zarf-cache", v.GetString(common.VZarfCache), lang.RootCmdFlagCachePath)
rootCmd.PersistentFlags().StringVar(&config.CommonOptions.TempDirectory, "tmpdir", v.GetString(common.VTmpDir), lang.RootCmdFlagTempDir)
rootCmd.PersistentFlags().BoolVar(&config.CommonOptions.Insecure, "insecure", v.GetBool(common.VInsecure), lang.RootCmdFlagInsecure)
Expand Down
15 changes: 2 additions & 13 deletions src/cmd/tools/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,25 +8,14 @@ import (
"fmt"

"github.com/spf13/cobra"
"github.com/zarf-dev/zarf/src/cmd/common"
"github.com/zarf-dev/zarf/src/config"

"github.com/zarf-dev/zarf/src/config/lang"
)

var toolsCmd = &cobra.Command{
Use: "tools",
Aliases: []string{"t"},
PersistentPreRun: func(cmd *cobra.Command, _ []string) {
config.SkipLogFile = true

// Skip for vendor-only commands
if common.CheckVendorOnlyFromPath(cmd) {
return
}

common.SetupCLI()
},
Short: lang.CmdToolsShort,
Short: lang.CmdToolsShort,
}

// Include adds the tools command to the root command.
Expand Down
7 changes: 2 additions & 5 deletions src/cmd/version.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,8 @@ var outputFormat string
var versionCmd = &cobra.Command{
Use: "version",
Aliases: []string{"v"},
PersistentPreRun: func(_ *cobra.Command, _ []string) {
config.SkipLogFile = true
},
Short: lang.CmdVersionShort,
Long: lang.CmdVersionLong,
Short: lang.CmdVersionShort,
Long: lang.CmdVersionLong,
RunE: func(_ *cobra.Command, _ []string) error {
if outputFormat == "" {
fmt.Println(config.CLIVersion)
Expand Down
6 changes: 0 additions & 6 deletions src/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,12 +60,6 @@ var (
// ZarfSeedPort is the NodePort Zarf uses for the 'seed registry'
ZarfSeedPort string

// SkipLogFile is a flag to skip logging to a file
SkipLogFile bool

// NoColor is a flag to disable colors in output
NoColor bool

CosignPublicKey string

// Timestamp of when the CLI was started
Expand Down
2 changes: 0 additions & 2 deletions src/config/lang/english.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,6 @@ const (
RootCmdDeprecatedDeploy = "Deprecated: Please use \"zarf package deploy %s\" to deploy this package. This warning will be removed in Zarf v1.0.0."
RootCmdDeprecatedCreate = "Deprecated: Please use \"zarf package create\" to create this package. This warning will be removed in Zarf v1.0.0."

RootCmdErrInvalidLogLevel = "Invalid log level. Valid options are: warn, info, debug, trace."

// zarf connect
CmdConnectShort = "Accesses services or pods deployed in the cluster"
CmdConnectLong = "Uses a k8s port-forward to connect to resources within the cluster referenced by your kube-context.\n" +
Expand Down
8 changes: 6 additions & 2 deletions src/pkg/message/message.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import (
"github.com/defenseunicorns/pkg/helpers/v2"
"github.com/fatih/color"
"github.com/pterm/pterm"
"github.com/zarf-dev/zarf/src/config"
)

// LogLevel is the level of logging to display.
Expand Down Expand Up @@ -99,6 +98,11 @@ func DisableColor() {
pterm.DisableColor()
}

// ColorEnabled returns true if color printing is enabled.
func ColorEnabled() bool {
return pterm.PrintColor
}

// ZarfCommand prints a zarf terminal command.
func ZarfCommand(format string, a ...any) {
Command("zarf "+format, a...)
Expand Down Expand Up @@ -276,7 +280,7 @@ func Table(header []string, data [][]string) {
// preventing future characters from taking on the given color
// returns string as normal if color is disabled
func ColorWrap(str string, attr color.Attribute) string {
if config.NoColor || str == "" {
if !ColorEnabled() || str == "" {
return str
}
return fmt.Sprintf("\x1b[%dm%s\x1b[0m", attr, str)
Expand Down
6 changes: 3 additions & 3 deletions src/pkg/utils/yaml.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,12 @@ import (
"github.com/goccy/go-yaml/lexer"
"github.com/goccy/go-yaml/printer"
"github.com/pterm/pterm"
"github.com/zarf-dev/zarf/src/config"
"github.com/zarf-dev/zarf/src/pkg/message"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
kubeyaml "k8s.io/apimachinery/pkg/util/yaml"
k8syaml "sigs.k8s.io/yaml"

"github.com/zarf-dev/zarf/src/pkg/message"
)

const yamlEscape = "\x1b"
Expand Down Expand Up @@ -93,7 +93,7 @@ func ColorPrintYAML(data any, hints map[string]string, spaceRootLists bool) {
outputYAML = strings.Replace(outputYAML, key, value, 1)
}

if config.NoColor {
if !message.ColorEnabled() {
// If no color is specified strip any color codes from the output - https://regex101.com/r/YFyIwC/2
ansiRegex := regexp.MustCompile(`\x1b\[(.*?)m`)
outputYAML = ansiRegex.ReplaceAllString(outputYAML, "")
Expand Down

0 comments on commit d4c688a

Please sign in to comment.