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
  • Loading branch information
phillebaba committed Jul 16, 2024
1 parent 891e96e commit 12c79d2
Show file tree
Hide file tree
Showing 8 changed files with 61 additions and 68 deletions.
50 changes: 21 additions & 29 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/defenseunicorns/zarf/src/config"
"github.com/defenseunicorns/zarf/src/config/lang"
"github.com/defenseunicorns/zarf/src/pkg/message"
"github.com/pterm/pterm"
)

// LogLevelCLI holds the log level as input from a command
var LogLevelCLI string
"github.com/defenseunicorns/zarf/src/pkg/message"
)

// 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 {

Check warning on line 21 in src/cmd/common/setup.go

View check run for this annotation

Codecov / codecov/patch

src/cmd/common/setup.go#L20-L21

Added lines #L20 - L21 were not covered by tests
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,

Check warning on line 32 in src/cmd/common/setup.go

View check run for this annotation

Codecov / codecov/patch

src/cmd/common/setup.go#L27-L32

Added lines #L27 - L32 were not covered by tests
}
lvl, ok := match[logLevel]
if !ok {
return errors.New("invalid log level, valid options are warn, info, debug, and trace")

Check warning on line 36 in src/cmd/common/setup.go

View check run for this annotation

Codecov / codecov/patch

src/cmd/common/setup.go#L34-L36

Added lines #L34 - L36 were not covered by tests
}
message.SetLogLevel(lvl)
message.Debug("Log level set to " + logLevel)

Check warning on line 39 in src/cmd/common/setup.go

View check run for this annotation

Codecov / codecov/patch

src/cmd/common/setup.go#L38-L39

Added lines #L38 - L39 were not covered by tests
}

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

if !config.SkipLogFile {
if !skipLogFile {

Check warning on line 48 in src/cmd/common/setup.go

View check run for this annotation

Codecov / codecov/patch

src/cmd/common/setup.go#L48

Added line #L48 was not covered by tests
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)

Check warning on line 52 in src/cmd/common/setup.go

View check run for this annotation

Codecov / codecov/patch

src/cmd/common/setup.go#L52

Added line #L52 was not covered by tests
}
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)

Check warning on line 56 in src/cmd/common/setup.go

View check run for this annotation

Codecov / codecov/patch

src/cmd/common/setup.go#L56

Added line #L56 was not covered by tests
}

pterm.SetDefaultOutput(io.MultiWriter(os.Stderr, logFile))
message.Notef("Saving log file to %s", f.Name())
}
return nil

Check warning on line 61 in src/cmd/common/setup.go

View check run for this annotation

Codecov / codecov/patch

src/cmd/common/setup.go#L61

Added line #L61 was not covered by tests
}
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 {

Check warning on line 39 in src/cmd/root.go

View check run for this annotation

Codecov / codecov/patch

src/cmd/root.go#L39

Added line #L39 was not covered by tests
// Skip for vendor-only commands
if common.CheckVendorOnlyFromPath(cmd) {
return
return nil

Check warning on line 42 in src/cmd/root.go

View check run for this annotation

Codecov / codecov/patch

src/cmd/root.go#L42

Added line #L42 was not covered by tests
}
// Don't log the help command

skipLogFile := SkipLogFile

Check warning on line 45 in src/cmd/root.go

View check run for this annotation

Codecov / codecov/patch

src/cmd/root.go#L45

Added line #L45 was not covered by tests

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

Check warning on line 50 in src/cmd/root.go

View check run for this annotation

Codecov / codecov/patch

src/cmd/root.go#L48-L50

Added lines #L48 - L50 were not covered by tests
}

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

Check warning on line 55 in src/cmd/root.go

View check run for this annotation

Codecov / codecov/patch

src/cmd/root.go#L55

Added line #L55 was not covered by tests
}

err := common.SetupCLI(LogLevelCLI, skipLogFile, NoColor)
if err != nil {
return err

Check warning on line 60 in src/cmd/root.go

View check run for this annotation

Codecov / codecov/patch

src/cmd/root.go#L58-L60

Added lines #L58 - L60 were not covered by tests
}
common.SetupCLI()
return nil

Check warning on line 62 in src/cmd/root.go

View check run for this annotation

Codecov / codecov/patch

src/cmd/root.go#L62

Added line #L62 was not covered by tests
},
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)

Check warning on line 112 in src/cmd/root.go

View check run for this annotation

Codecov / codecov/patch

src/cmd/root.go#L112

Added line #L112 was not covered by tests
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)

Check warning on line 114 in src/cmd/root.go

View check run for this annotation

Codecov / codecov/patch

src/cmd/root.go#L114

Added line #L114 was not covered by tests
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)

Check warning on line 116 in src/cmd/root.go

View check run for this annotation

Codecov / codecov/patch

src/cmd/root.go#L116

Added line #L116 was not covered by tests
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
17 changes: 3 additions & 14 deletions src/cmd/tools/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,26 +7,15 @@ package tools
import (
"fmt"

"github.com/defenseunicorns/zarf/src/cmd/common"
"github.com/defenseunicorns/zarf/src/config"
"github.com/defenseunicorns/zarf/src/config/lang"
"github.com/spf13/cobra"

"github.com/defenseunicorns/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 @@ -12,7 +12,6 @@ import (
"time"

"github.com/defenseunicorns/pkg/helpers/v2"
"github.com/defenseunicorns/zarf/src/config"
"github.com/fatih/color"
"github.com/pterm/pterm"
)
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

Check warning on line 103 in src/pkg/message/message.go

View check run for this annotation

Codecov / codecov/patch

src/pkg/message/message.go#L102-L103

Added lines #L102 - L103 were not covered by tests
}

// 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 == "" {

Check warning on line 283 in src/pkg/message/message.go

View check run for this annotation

Codecov / codecov/patch

src/pkg/message/message.go#L283

Added line #L283 was not covered by tests
return str
}
return fmt.Sprintf("\x1b[%dm%s\x1b[0m", attr, str)
Expand Down
3 changes: 1 addition & 2 deletions src/pkg/utils/yaml.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ import (
"regexp"
"strings"

"github.com/defenseunicorns/zarf/src/config"
"github.com/defenseunicorns/zarf/src/pkg/message"
"github.com/fatih/color"
goyaml "github.com/goccy/go-yaml"
Expand Down Expand Up @@ -93,7 +92,7 @@ func ColorPrintYAML(data any, hints map[string]string, spaceRootLists bool) {
outputYAML = strings.Replace(outputYAML, key, value, 1)
}

if config.NoColor {
if message.ColorEnabled() {

Check warning on line 95 in src/pkg/utils/yaml.go

View check run for this annotation

Codecov / codecov/patch

src/pkg/utils/yaml.go#L95

Added line #L95 was not covered by tests
// 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 12c79d2

Please sign in to comment.