Skip to content

Commit

Permalink
wip: remove pkg/message based logging
Browse files Browse the repository at this point in the history
Signed-off-by: Kit Patella <[email protected]>
  • Loading branch information
mkcp committed Feb 27, 2025
1 parent f18a2a8 commit 97c89fa
Show file tree
Hide file tree
Showing 32 changed files with 52 additions and 228 deletions.
4 changes: 0 additions & 4 deletions src/cmd/destroy.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ import (
"github.com/zarf-dev/zarf/src/internal/packager/helm"
"github.com/zarf-dev/zarf/src/pkg/cluster"
"github.com/zarf-dev/zarf/src/pkg/logger"
"github.com/zarf-dev/zarf/src/pkg/message"
"github.com/zarf-dev/zarf/src/pkg/utils/exec"

"github.com/spf13/cobra"
Expand Down Expand Up @@ -62,7 +61,6 @@ func (o *destroyOptions) run(cmd *cobra.Command, _ []string) error {
// the scripts to remove k3s, we will still try to remove a locally installed k3s cluster
state, err := c.LoadZarfState(ctx)
if err != nil {
message.WarnErr(err, err.Error())
l.Warn(err.Error())
}

Expand All @@ -85,7 +83,6 @@ func (o *destroyOptions) run(cmd *cobra.Command, _ []string) error {
// Run the matched script
err := exec.CmdWithPrint(script)
if errors.Is(err, os.ErrPermission) {
message.Warnf(lang.CmdDestroyErrScriptPermissionDenied, script)
l.Warn("received 'permission denied' when trying to execute script. Please double-check you have the correct kube-context.", "script", script)

// Don't remove scripts we can't execute so the user can try to manually run
Expand All @@ -97,7 +94,6 @@ func (o *destroyOptions) run(cmd *cobra.Command, _ []string) error {
// Try to remove the script, but ignore any errors and debug log them
err = os.Remove(script)
if err != nil {
message.WarnErr(err, fmt.Sprintf("Unable to remove script. script=%s", script))
l.Warn("unable to remove script", "script", script, "error", err.Error())
}
}
Expand Down
7 changes: 3 additions & 4 deletions src/cmd/dev.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ import (
layout2 "github.com/zarf-dev/zarf/src/internal/packager2/layout"
"github.com/zarf-dev/zarf/src/pkg/lint"
"github.com/zarf-dev/zarf/src/pkg/logger"
"github.com/zarf-dev/zarf/src/pkg/message"
"github.com/zarf-dev/zarf/src/pkg/packager"
"github.com/zarf-dev/zarf/src/pkg/transform"
"github.com/zarf-dev/zarf/src/pkg/utils"
Expand Down Expand Up @@ -250,8 +249,9 @@ func (o *devPatchGitOptions) run(_ *cobra.Command, args []string) error {
// Perform git url transformation via regex
text := string(content)

// TODO(mkcp): Currently uses message for its log fn. Migrate to ctx and slog
processedText := transform.MutateGitURLsInText(message.Warnf, gitServer.Address, text, gitServer.PushUsername)
// FIXME(mkcp): Currently uses message for its log fn. Migrate to ctx and slog
l := logger.Default()
processedText := transform.MutateGitURLsInText(l.Warn, gitServer.Address, text, gitServer.PushUsername)

// Print the differences
// TODO(mkcp): Uses pterm to print text diffs. Decouple from pterm after we release logger.
Expand Down Expand Up @@ -309,7 +309,6 @@ func (o *devSha256SumOptions) run(cmd *cobra.Command, args []string) (err error)
var data io.ReadCloser

if helpers.IsURL(fileName) {
message.Warn(lang.CmdDevSha256sumRemoteWarning)
logger.From(cmd.Context()).Warn("this is a remote source. If a published checksum is available you should use that rather than calculating it directly from the remote link")

fileBase, err := helpers.ExtractBasePathFromURL(fileName)
Expand Down
2 changes: 0 additions & 2 deletions src/cmd/helm.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import (
"github.com/zarf-dev/zarf/src/cmd/helm"
"github.com/zarf-dev/zarf/src/config/lang"
"github.com/zarf-dev/zarf/src/pkg/logger"
"github.com/zarf-dev/zarf/src/pkg/message"
"helm.sh/helm/v3/pkg/action"
)

Expand All @@ -29,7 +28,6 @@ func newHelmCommand() *cobra.Command {
// The inclusion of Helm in this manner should be changed once https://github.com/helm/helm/pull/13617 is merged
cmd, err := helm.NewRootCmd(actionConfig, os.Stdout, helmArgs)
if err != nil {
message.Debug("Failed to initialize helm command", "error", err)
logger.Default().Debug("failed to initialize helm command", "error", err)
}
cmd.Short = lang.CmdToolsHelmShort
Expand Down
3 changes: 0 additions & 3 deletions src/cmd/initialize.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ import (
"github.com/zarf-dev/zarf/src/config"
"github.com/zarf-dev/zarf/src/config/lang"
"github.com/zarf-dev/zarf/src/pkg/logger"
"github.com/zarf-dev/zarf/src/pkg/message"
"github.com/zarf-dev/zarf/src/pkg/packager"
"github.com/zarf-dev/zarf/src/pkg/packager/sources"
"github.com/zarf-dev/zarf/src/pkg/utils"
Expand Down Expand Up @@ -186,8 +185,6 @@ func downloadInitPackage(ctx context.Context, cacheDirectory string) (string, er
url := zoci.GetInitPackageURL(config.CLIVersion)

// Give the user the choice to download the init-package and note that this does require an internet connection
message.Question(fmt.Sprintf(lang.CmdInitPullAsk, url))
message.Note(lang.CmdInitPullNote)
l.Info("the init package was not found locally, but can be pulled in connected environments", "url", fmt.Sprintf("oci://%s", url))

var confirmDownload bool
Expand Down
2 changes: 0 additions & 2 deletions src/cmd/internal.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ import (
"github.com/zarf-dev/zarf/src/internal/gitea"
"github.com/zarf-dev/zarf/src/pkg/cluster"
"github.com/zarf-dev/zarf/src/pkg/logger"
"github.com/zarf-dev/zarf/src/pkg/message"
)

func newInternalCommand(rootCmd *cobra.Command) *cobra.Command {
Expand Down Expand Up @@ -358,7 +357,6 @@ func (o *internalUpdateGiteaPVCOptions) run(cmd *cobra.Command, _ []string) erro
// There is a possibility that the pvc does not yet exist and Gitea helm chart should create it
helmShouldCreate, err := c.UpdateGiteaPVC(ctx, pvcName, o.rollback)
if err != nil {
message.WarnErr(err, lang.CmdInternalUpdateGiteaPVCErr)
logger.From(ctx).Warn("Unable to update the existing Gitea persistent volume claim", "error", err.Error())
}
fmt.Print(helmShouldCreate)
Expand Down
2 changes: 0 additions & 2 deletions src/cmd/kubectl.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import (
"github.com/spf13/cobra"
"github.com/zarf-dev/zarf/src/config/lang"
"github.com/zarf-dev/zarf/src/pkg/logger"
"github.com/zarf-dev/zarf/src/pkg/message"
kubeCLI "k8s.io/component-base/cli"
kubeCmd "k8s.io/kubectl/pkg/cmd"

Expand All @@ -32,7 +31,6 @@ func newKubectlCommand() *cobra.Command {

if err := kubeCLI.RunNoErrOutput(cmd); err != nil {
// @todo(jeff-mccoy) - Kubectl gets mad about being a subcommand.
message.Debug(err)
logger.Default().Debug(err.Error())
}
}
Expand Down
3 changes: 2 additions & 1 deletion src/cmd/package.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,15 @@ import (
"encoding/json"
"errors"
"fmt"
"github.com/zarf-dev/zarf/src/pkg/message"
"io"
"os"
"path/filepath"
"regexp"
"runtime"
"strings"

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

"github.com/AlecAivazis/survey/v2"
"github.com/defenseunicorns/pkg/helpers/v2"
goyaml "github.com/goccy/go-yaml"
Expand Down
44 changes: 23 additions & 21 deletions src/cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,8 @@ var (
LogLevelCLI string
// LogFormat holds the log format as input from a command
LogFormat string
// SkipLogFile is a flag to skip logging to a file
SkipLogFile bool
// NoColor is a flag to disable colors in output
NoColor bool
IsColorDisabled bool
// OutputWriter provides a default writer to Stdout for user-facing command output
OutputWriter = os.Stdout
)
Expand Down Expand Up @@ -82,14 +80,19 @@ func preRun(cmd *cobra.Command, _ []string) error {
return nil
}

// Configure logger and add it to cmd context.
l, err := setupLogger(LogLevelCLI, LogFormat, !NoColor)
// Configure logger and add it to cmd context. We flip NoColor because setLogger wants "isColor"
l, err := setupLogger(LogLevelCLI, LogFormat, !IsColorDisabled)
if err != nil {
return err
}
ctx := logger.WithContext(cmd.Context(), l)
cmd.SetContext(ctx)

// if --no-color is set, disable PTerm color in message prints
if IsColorDisabled {
pterm.DisableColor()
}

// Print out config location
err = PrintViperConfigUsed(cmd.Context())
if err != nil {
Expand Down Expand Up @@ -171,25 +174,27 @@ func init() {
return
}

v := getViper()
vpr := getViper()

// Logs
rootCmd.PersistentFlags().StringVarP(&LogLevelCLI, "log-level", "l", v.GetString(VLogLevel), lang.RootCmdFlagLogLevel)
rootCmd.PersistentFlags().StringVar(&LogFormat, "log-format", v.GetString(VLogFormat), "Select a logging format. Defaults to 'console'. Valid options are: 'console', 'json', 'dev'.")
rootCmd.PersistentFlags().StringVarP(&LogLevelCLI, "log-level", "l", vpr.GetString(VLogLevel), lang.RootCmdFlagLogLevel)
rootCmd.PersistentFlags().StringVar(&LogFormat, "log-format", vpr.GetString(VLogFormat), "Select a logging format. Defaults to 'console'. Valid options are: 'console', 'json', 'dev'.")
rootCmd.PersistentFlags().BoolVar(&IsColorDisabled, "no-color", vpr.GetBool(VNoColor), "Disable terminal color codes in logging and stdout prints.")

rootCmd.PersistentFlags().StringVarP(&config.CLIArch, "architecture", "a", v.GetString(VArchitecture), lang.RootCmdFlagArch)
rootCmd.PersistentFlags().StringVar(&config.CommonOptions.CachePath, "zarf-cache", v.GetString(VZarfCache), lang.RootCmdFlagCachePath)
rootCmd.PersistentFlags().StringVar(&config.CommonOptions.TempDirectory, "tmpdir", v.GetString(VTmpDir), lang.RootCmdFlagTempDir)
// Core functionality
rootCmd.PersistentFlags().StringVarP(&config.CLIArch, "architecture", "a", vpr.GetString(VArchitecture), lang.RootCmdFlagArch)
rootCmd.PersistentFlags().StringVar(&config.CommonOptions.CachePath, "zarf-cache", vpr.GetString(VZarfCache), lang.RootCmdFlagCachePath)
rootCmd.PersistentFlags().StringVar(&config.CommonOptions.TempDirectory, "tmpdir", vpr.GetString(VTmpDir), lang.RootCmdFlagTempDir)

// Security
rootCmd.PersistentFlags().BoolVar(&config.CommonOptions.Insecure, "insecure", v.GetBool(VInsecure), lang.RootCmdFlagInsecure)
rootCmd.PersistentFlags().MarkDeprecated("insecure", "please use --plain-http, --insecure-skip-tls-verify, or --skip-signature-validation instead.")
rootCmd.PersistentFlags().BoolVar(&config.CommonOptions.PlainHTTP, "plain-http", v.GetBool(VPlainHTTP), lang.RootCmdFlagPlainHTTP)
rootCmd.PersistentFlags().BoolVar(&config.CommonOptions.InsecureSkipTLSVerify, "insecure-skip-tls-verify", v.GetBool(VInsecureSkipTLSVerify), lang.RootCmdFlagInsecureSkipTLSVerify)
rootCmd.PersistentFlags().BoolVar(&config.CommonOptions.Insecure, "insecure", vpr.GetBool(VInsecure), lang.RootCmdFlagInsecure)
rootCmd.PersistentFlags().BoolVar(&config.CommonOptions.PlainHTTP, "plain-http", vpr.GetBool(VPlainHTTP), lang.RootCmdFlagPlainHTTP)
rootCmd.PersistentFlags().BoolVar(&config.CommonOptions.InsecureSkipTLSVerify, "insecure-skip-tls-verify", vpr.GetBool(VInsecureSkipTLSVerify), lang.RootCmdFlagInsecureSkipTLSVerify)
_ = rootCmd.PersistentFlags().MarkDeprecated("insecure", "please use --plain-http, --insecure-skip-tls-verify, or --skip-signature-validation instead.")
}

// setup Logger handles creating a logger and setting it as the global default.
func setupLogger(level, format string, color bool) (*slog.Logger, error) {
// setupLogger handles creating a logger and setting it as the global default.
func setupLogger(level, format string, isColor bool) (*slog.Logger, error) {
// If we didn't get a level from config, fallback to "info"
if level == "" {
level = "info"
Expand All @@ -202,15 +207,12 @@ func setupLogger(level, format string, color bool) (*slog.Logger, error) {
Level: sLevel,
Format: logger.Format(format),
Destination: logger.DestinationDefault,
Color: logger.Color(color),
Color: logger.Color(isColor),
}
l, err := logger.New(cfg)
if err != nil {
return nil, err
}
if !color {
pterm.DisableColor()
}
logger.SetDefault(l)
l.Debug("logger successfully initialized", "cfg", cfg)
return l, nil
Expand Down
1 change: 0 additions & 1 deletion src/cmd/table.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,6 @@ func PrintFindings(ctx context.Context, lintErr *lint.LintError) {
}

// Print table to our OutputWriter
message.Notef("Linting package %q at %s", findings[0].PackageNameOverride, packagePathFromUser)
logger.From(ctx).Info("linting package", "name", findings[0].PackageNameOverride, "path", packagePathFromUser)
message.TableWithWriter(OutputWriter, []string{"Type", "Path", "Message"}, lintData)
}
Expand Down
1 change: 1 addition & 0 deletions src/cmd/viper.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ const (

VLogLevel = "log_level"
VLogFormat = "log_format"
VNoColor = "no_color"

// Init config keys

Expand Down
1 change: 0 additions & 1 deletion src/config/lang/english.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,6 @@ const (
RootCmdFlagArch = "Architecture for OCI images and Zarf packages"
RootCmdFlagSkipLogFile = "Disable log file creation"
RootCmdFlagNoProgress = "Disable fancy UI progress bars, spinners, logos, etc"
RootCmdFlagNoColor = "Disable colors in output"
RootCmdFlagCachePath = "Specify the location of the Zarf cache directory"
RootCmdFlagTempDir = "Specify the temporary directory to use for intermediate files"
RootCmdFlagInsecure = "Allow access to insecure registries and disable other recommended security enforcements such as package checksum and signature validation. This flag should only be used if you have a specific reason and accept the reduced security posture."
Expand Down
6 changes: 0 additions & 6 deletions src/internal/git/repository.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ import (
"github.com/go-git/go-git/v5/plumbing/transport/http"

"github.com/zarf-dev/zarf/src/pkg/logger"
"github.com/zarf-dev/zarf/src/pkg/message"
"github.com/zarf-dev/zarf/src/pkg/transform"
"github.com/zarf-dev/zarf/src/pkg/utils"
)
Expand Down Expand Up @@ -97,7 +96,6 @@ func Clone(ctx context.Context, rootPath, address string, shallow bool) (*Reposi
}
repo, err := git.PlainCloneContext(ctx, r.path, false, cloneOpts)
if err != nil {
message.Notef("Falling back to host 'git', failed to clone the repo %q with Zarf: %s", gitURLNoRef, err.Error())
l.Info("falling back to host 'git', failed to clone the repo with Zarf", "url", gitURLNoRef, "error", err)
err := r.gitCloneFallback(ctx, gitURLNoRef, ref, shallow)
if err != nil {
Expand Down Expand Up @@ -198,13 +196,10 @@ func (r *Repository) Push(ctx context.Context, address, username, password strin
}
err = repo.FetchContext(ctx, fetchOptions)
if errors.Is(err, transport.ErrRepositoryNotFound) {
message.Debugf("Repo not yet available offline, skipping fetch...")
l.Debug("repo not yet available offline, skipping fetch")
} else if errors.Is(err, git.ErrForceNeeded) {
message.Debugf("Repo fetch requires force, skipping fetch...")
l.Debug("repo fetch requires force, skipping fetch")
} else if errors.Is(err, git.NoErrAlreadyUpToDate) {
message.Debugf("Repo already up-to-date, skipping fetch...")
l.Debug("repo already up-to-date, skipping fetch")
} else if err != nil {
return fmt.Errorf("unable to fetch the git repo prior to push: %w", err)
Expand All @@ -223,7 +218,6 @@ func (r *Repository) Push(ctx context.Context, address, username, password strin
},
})
if errors.Is(err, git.NoErrAlreadyUpToDate) {
message.Debug("Repo already up-to-date")
l.Debug("repo already up-to-date")
} else if errors.Is(err, plumbing.ErrObjectNotFound) {
return fmt.Errorf("unable to push repo due to likely shallow clone: %s", err.Error())
Expand Down
3 changes: 0 additions & 3 deletions src/internal/packager/helm/chart.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ import (

"github.com/zarf-dev/zarf/src/config"
"github.com/zarf-dev/zarf/src/internal/healthchecks"
"github.com/zarf-dev/zarf/src/pkg/message"
"github.com/zarf-dev/zarf/src/types"
)

Expand Down Expand Up @@ -218,7 +217,6 @@ func (h *Helm) RemoveChart(ctx context.Context, namespace string, name string) e
_ = h.createActionConfig(ctx, namespace)
// Perform the uninstall.
response, err := h.uninstallChart(name)
message.Debug(response)
logger.From(ctx).Debug("chart uninstalled", "response", response)
return err
}
Expand Down Expand Up @@ -439,7 +437,6 @@ func (h *Helm) migrateDeprecatedAPIs(ctx context.Context, latestRelease *release

// If the release was modified in the above loop, save it back to the cluster
if modified {
message.Warnf("Zarf detected deprecated APIs for the '%s' helm release. Attempting automatic upgrade.", latestRelease.Name)
logger.From(ctx).Warn("detected deprecated APIs for the helm release", "name", latestRelease.Name)

// Update current release version to be superseded (same as the helm mapkubeapis plugin)
Expand Down
4 changes: 0 additions & 4 deletions src/internal/packager/helm/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ import (
"github.com/zarf-dev/zarf/src/api/v1alpha1"
"github.com/zarf-dev/zarf/src/config"
"github.com/zarf-dev/zarf/src/pkg/cluster"
"github.com/zarf-dev/zarf/src/pkg/message"
"github.com/zarf-dev/zarf/src/pkg/variables"
"github.com/zarf-dev/zarf/src/types"
"helm.sh/helm/v3/pkg/action"
Expand Down Expand Up @@ -80,9 +79,6 @@ func NewClusterOnly(cfg *types.PackagerConfig, variableConfig *variables.Variabl

// NewFromZarfManifest generates a helm chart and config from a given Zarf manifest.
func NewFromZarfManifest(manifest v1alpha1.ZarfManifest, manifestPath, packageName, componentName string, mods ...Modifier) (h *Helm, err error) {
spinner := message.NewProgressSpinner("Starting helm chart generation %s", manifest.Name)
defer spinner.Stop()

// Generate a new chart.
tmpChart := new(chart.Chart)
tmpChart.Metadata = new(chart.Metadata)
Expand Down
5 changes: 1 addition & 4 deletions src/internal/packager/helm/post-render.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"bytes"
"context"
"fmt"
"github.com/zarf-dev/zarf/src/pkg/message"
"os"
"path/filepath"
"slices"
Expand All @@ -16,7 +17,6 @@ import (
"github.com/zarf-dev/zarf/src/config"
"github.com/zarf-dev/zarf/src/pkg/cluster"
"github.com/zarf-dev/zarf/src/pkg/logger"
"github.com/zarf-dev/zarf/src/pkg/message"
"github.com/zarf-dev/zarf/src/pkg/utils"
"github.com/zarf-dev/zarf/src/types"
"helm.sh/helm/v3/pkg/releaseutil"
Expand Down Expand Up @@ -142,7 +142,6 @@ func (r *renderer) adoptAndUpdateNamespaces(ctx context.Context) error {
// Refuse to adopt namespace if it is one of four initial Kubernetes namespaces.
// https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces/#initial-namespaces
if slices.Contains([]string{"default", "kube-node-lease", "kube-public", "kube-system"}, name) {
message.Warnf("Refusing to adopt the initial namespace: %s", name)
l.Warn("refusing to adopt initial namespace", "name", name)
} else {
// This is an existing namespace to adopt
Expand Down Expand Up @@ -200,10 +199,8 @@ func (r *renderer) editHelmResources(ctx context.Context, resources []releaseuti
namespace := &corev1.Namespace{}
// parse the namespace resource so it can be applied out-of-band by zarf instead of helm to avoid helm ns shenanigans
if err := runtime.DefaultUnstructuredConverter.FromUnstructured(rawData.UnstructuredContent(), namespace); err != nil {
message.WarnErrf(err, "could not parse namespace %s", rawData.GetName())
l.Warn("failed to parse namespace", "name", rawData.GetName(), "error", err)
} else {
message.Debugf("Matched helm namespace %s for zarf annotation", namespace.Name)
l.Debug("matched helm namespace for zarf annotation", "name", namespace.Name)
namespace.Labels = cluster.AdoptZarfManagedLabels(namespace.Labels)
// Add it to the stack
Expand Down
Loading

0 comments on commit 97c89fa

Please sign in to comment.