Skip to content

Commit

Permalink
refactor: replace message.Debug with context logger
Browse files Browse the repository at this point in the history
Signed-off-by: Philip Laine <philip.laine@gmail.com>
  • Loading branch information
phillebaba committed Aug 7, 2024
1 parent e9c756b commit 320bf7c
Show file tree
Hide file tree
Showing 36 changed files with 257 additions and 119 deletions.
8 changes: 4 additions & 4 deletions src/cmd/dev.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ var devDeployCmd = &cobra.Command{
pkgConfig.PkgOpts.SetVariables = helpers.TransformAndMergeMap(
v.GetStringMapString(common.VPkgDeploySet), pkgConfig.PkgOpts.SetVariables, strings.ToUpper)

pkgClient, err := packager.New(&pkgConfig)
pkgClient, err := packager.New(cmd.Context(), &pkgConfig)
if err != nil {
return err
}
Expand All @@ -78,7 +78,7 @@ var devGenerateCmd = &cobra.Command{
pkgConfig.CreateOpts.BaseDir = "."
pkgConfig.FindImagesOpts.RepoHelmChartPath = pkgConfig.GenerateOpts.GitPath

pkgClient, err := packager.New(&pkgConfig)
pkgClient, err := packager.New(cmd.Context(), &pkgConfig)
if err != nil {
return err
}
Expand Down Expand Up @@ -229,7 +229,7 @@ var devFindImagesCmd = &cobra.Command{
v.GetStringMapString(common.VPkgCreateSet), pkgConfig.CreateOpts.SetVariables, strings.ToUpper)
pkgConfig.PkgOpts.SetVariables = helpers.TransformAndMergeMap(
v.GetStringMapString(common.VPkgDeploySet), pkgConfig.PkgOpts.SetVariables, strings.ToUpper)
pkgClient, err := packager.New(&pkgConfig)
pkgClient, err := packager.New(cmd.Context(), &pkgConfig)
if err != nil {
return err
}
Expand Down Expand Up @@ -276,7 +276,7 @@ var devLintCmd = &cobra.Command{
pkgConfig.CreateOpts.SetVariables = helpers.TransformAndMergeMap(
v.GetStringMapString(common.VPkgCreateSet), pkgConfig.CreateOpts.SetVariables, strings.ToUpper)

pkgClient, err := packager.New(&pkgConfig)
pkgClient, err := packager.New(cmd.Context(), &pkgConfig)
if err != nil {
return err
}
Expand Down
2 changes: 1 addition & 1 deletion src/cmd/initialize.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ var initCmd = &cobra.Command{
pkgConfig.PkgOpts.SetVariables = helpers.TransformAndMergeMap(
v.GetStringMapString(common.VPkgDeploySet), pkgConfig.PkgOpts.SetVariables, strings.ToUpper)

pkgClient, err := packager.New(&pkgConfig, packager.WithSource(src))
pkgClient, err := packager.New(cmd.Context(), &pkgConfig, packager.WithSource(src))
if err != nil {
return err
}
Expand Down
23 changes: 12 additions & 11 deletions src/cmd/package.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (

"github.com/zarf-dev/zarf/src/cmd/common"
"github.com/zarf-dev/zarf/src/config/lang"
"github.com/zarf-dev/zarf/src/pkg/logging"
"github.com/zarf-dev/zarf/src/pkg/message"
"github.com/zarf-dev/zarf/src/pkg/packager/sources"
"github.com/zarf-dev/zarf/src/types"
Expand Down Expand Up @@ -54,7 +55,7 @@ var packageCreateCmd = &cobra.Command{
pkgConfig.CreateOpts.SetVariables = helpers.TransformAndMergeMap(
v.GetStringMapString(common.VPkgCreateSet), pkgConfig.CreateOpts.SetVariables, strings.ToUpper)

pkgClient, err := packager.New(&pkgConfig)
pkgClient, err := packager.New(cmd.Context(), &pkgConfig)
if err != nil {
return err
}
Expand Down Expand Up @@ -84,7 +85,7 @@ var packageDeployCmd = &cobra.Command{
pkgConfig.PkgOpts.SetVariables = helpers.TransformAndMergeMap(
v.GetStringMapString(common.VPkgDeploySet), pkgConfig.PkgOpts.SetVariables, strings.ToUpper)

pkgClient, err := packager.New(&pkgConfig)
pkgClient, err := packager.New(cmd.Context(), &pkgConfig)
if err != nil {
return err
}
Expand Down Expand Up @@ -112,7 +113,7 @@ var packageMirrorCmd = &cobra.Command{
return err
}
pkgConfig.PkgOpts.PackageSource = packageSource
pkgClient, err := packager.New(&pkgConfig)
pkgClient, err := packager.New(cmd.Context(), &pkgConfig)
if err != nil {
return err
}
Expand All @@ -136,11 +137,11 @@ var packageInspectCmd = &cobra.Command{
return err
}
pkgConfig.PkgOpts.PackageSource = packageSource
src, err := identifyAndFallbackToClusterSource()
src, err := identifyAndFallbackToClusterSource(cmd.Context())
if err != nil {
return err
}
pkgClient, err := packager.New(&pkgConfig, packager.WithSource(src))
pkgClient, err := packager.New(cmd.Context(), &pkgConfig, packager.WithSource(src))
if err != nil {
return err
}
Expand Down Expand Up @@ -208,11 +209,11 @@ var packageRemoveCmd = &cobra.Command{
return err
}
pkgConfig.PkgOpts.PackageSource = packageSource
src, err := identifyAndFallbackToClusterSource()
src, err := identifyAndFallbackToClusterSource(cmd.Context())
if err != nil {
return err
}
pkgClient, err := packager.New(&pkgConfig, packager.WithSource(src))
pkgClient, err := packager.New(cmd.Context(), &pkgConfig, packager.WithSource(src))
if err != nil {
return err
}
Expand Down Expand Up @@ -253,7 +254,7 @@ var packagePublishCmd = &cobra.Command{

pkgConfig.PublishOpts.PackageDestination = ref.String()

pkgClient, err := packager.New(&pkgConfig)
pkgClient, err := packager.New(cmd.Context(), &pkgConfig)
if err != nil {
return err
}
Expand All @@ -273,7 +274,7 @@ var packagePullCmd = &cobra.Command{
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
pkgConfig.PkgOpts.PackageSource = args[0]
pkgClient, err := packager.New(&pkgConfig)
pkgClient, err := packager.New(cmd.Context(), &pkgConfig)
if err != nil {
return err
}
Expand Down Expand Up @@ -311,10 +312,10 @@ func choosePackage(args []string) (string, error) {
}

// TODO: This code does not seem to do what it was intended.
func identifyAndFallbackToClusterSource() (sources.PackageSource, error) {
func identifyAndFallbackToClusterSource(ctx context.Context) (sources.PackageSource, error) {
identifiedSrc := sources.Identify(pkgConfig.PkgOpts.PackageSource)
if identifiedSrc == "" {
message.Debugf(lang.CmdPackageClusterSourceFallback, pkgConfig.PkgOpts.PackageSource)
logging.FromContextOrDiscard(ctx).Debug("package source does not satisfy any current sources, assuming it is a package deployed to a cluster", "source", pkgConfig.PkgOpts.PackageSource)
src, err := sources.NewClusterSource(&pkgConfig.PkgOpts)
if err != nil {
return nil, fmt.Errorf("unable to identify source from %s: %w", pkgConfig.PkgOpts.PackageSource, err)
Expand Down
6 changes: 6 additions & 0 deletions src/cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ package cmd
import (
"context"
"fmt"
"log/slog"
"os"
"slices"
"strings"
Expand All @@ -19,6 +20,7 @@ import (
"github.com/zarf-dev/zarf/src/config"
"github.com/zarf-dev/zarf/src/config/lang"
"github.com/zarf-dev/zarf/src/pkg/layout"
"github.com/zarf-dev/zarf/src/pkg/logging"
"github.com/zarf-dev/zarf/src/pkg/message"
"github.com/zarf-dev/zarf/src/types"
)
Expand Down Expand Up @@ -87,6 +89,10 @@ var rootCmd = &cobra.Command{

// Execute is the entrypoint for the CLI.
func Execute(ctx context.Context) {
handler := logging.NewPtermHandler()
log := slog.New(handler)
ctx = logging.NewContext(ctx, log)

cmd, err := rootCmd.ExecuteContextC(ctx)
if err == nil {
return
Expand Down
4 changes: 2 additions & 2 deletions src/cmd/tools/wait.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ var waitForCmd = &cobra.Command{
Long: lang.CmdToolsWaitForLong,
Example: lang.CmdToolsWaitForExample,
Args: cobra.MinimumNArgs(1),
RunE: func(_ *cobra.Command, args []string) error {
RunE: func(cmd *cobra.Command, args []string) error {
// Parse the timeout string
timeout, err := time.ParseDuration(waitTimeout)
if err != nil {
Expand All @@ -51,7 +51,7 @@ var waitForCmd = &cobra.Command{
}

// Execute the wait command.
if err := utils.ExecuteWait(waitTimeout, waitNamespace, condition, kind, identifier, timeout); err != nil {
if err := utils.ExecuteWait(cmd.Context(), waitTimeout, waitNamespace, condition, kind, identifier, timeout); err != nil {
return err
}
return err
Expand Down
5 changes: 2 additions & 3 deletions src/config/lang/english.go
Original file line number Diff line number Diff line change
Expand Up @@ -314,9 +314,8 @@ $ zarf package pull oci://ghcr.io/defenseunicorns/packages/dos-games:1.0.0 -a ar
$ zarf package pull oci://ghcr.io/defenseunicorns/packages/dos-games:1.0.0 -a skeleton`
CmdPackagePullFlagOutputDirectory = "Specify the output directory for the pulled Zarf package"

CmdPackageChoose = "Choose or type the package file"
CmdPackageClusterSourceFallback = "%q does not satisfy any current sources, assuming it is a package deployed to a cluster"
CmdPackageInvalidSource = "Unable to identify source from %q: %s"
CmdPackageChoose = "Choose or type the package file"
CmdPackageInvalidSource = "Unable to identify source from %q: %s"

// zarf dev (prepare is an alias for dev)
CmdDevShort = "Commands useful for developing packages"
Expand Down
11 changes: 7 additions & 4 deletions src/internal/git/repository.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import (
"github.com/go-git/go-git/v5/plumbing/transport"
"github.com/go-git/go-git/v5/plumbing/transport/http"

"github.com/zarf-dev/zarf/src/pkg/logging"
"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 @@ -146,6 +147,8 @@ func (r *Repository) Path() string {

// Push pushes the repository to the remote git server.
func (r *Repository) Push(ctx context.Context, address, username, password string) error {
log := logging.FromContextOrDiscard(ctx)

repo, err := git.PlainOpen(r.path)
if err != nil {
return fmt.Errorf("not a valid git repo or unable to open: %w", err)
Expand Down Expand Up @@ -194,11 +197,11 @@ 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...")
log.Debug("repository not yet available offling, skipping fetch")
} else if errors.Is(err, git.ErrForceNeeded) {
message.Debugf("Repo fetch requires force, skipping fetch...")
log.Debug("repositoy fetch requires force, skipping fetch")
} else if errors.Is(err, git.NoErrAlreadyUpToDate) {
message.Debugf("Repo already up-to-date, skipping fetch...")
log.Debug("repository already update-to date, skipping fetch")
} else if err != nil {
return fmt.Errorf("unable to fetch the git repo prior to push: %w", err)
}
Expand All @@ -216,7 +219,7 @@ func (r *Repository) Push(ctx context.Context, address, username, password strin
},
})
if errors.Is(err, git.NoErrAlreadyUpToDate) {
message.Debug("Repo already up-to-date")
logging.FromContextOrDiscard(ctx).Debug("Repository 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())
} else if err != nil {
Expand Down
3 changes: 1 addition & 2 deletions src/internal/packager/helm/chart.go
Original file line number Diff line number Diff line change
Expand Up @@ -195,8 +195,7 @@ func (h *Helm) RemoveChart(namespace string, name string, spinner *message.Spinn
// Establish a new actionConfig for the namespace.
_ = h.createActionConfig(namespace, spinner)
// Perform the uninstall.
response, err := h.uninstallChart(name)
message.Debug(response)
_, err := h.uninstallChart(name)
return err
}

Expand Down
7 changes: 5 additions & 2 deletions src/internal/packager/helm/post-render.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (
"github.com/defenseunicorns/pkg/helpers/v2"
"github.com/zarf-dev/zarf/src/config"
"github.com/zarf-dev/zarf/src/pkg/cluster"
"github.com/zarf-dev/zarf/src/pkg/logging"
"github.com/zarf-dev/zarf/src/pkg/message"
"github.com/zarf-dev/zarf/src/pkg/utils"
"github.com/zarf-dev/zarf/src/types"
Expand Down Expand Up @@ -208,6 +209,8 @@ func (r *renderer) adoptAndUpdateNamespaces(ctx context.Context) error {
}

func (r *renderer) editHelmResources(ctx context.Context, resources []releaseutil.Manifest, finalManifestsOutput *bytes.Buffer) error {
log := logging.FromContextOrDiscard(ctx)

dc, err := dynamic.NewForConfig(r.cluster.RestConfig)
if err != nil {
return err
Expand All @@ -232,7 +235,7 @@ func (r *renderer) editHelmResources(ctx context.Context, resources []releaseuti
if err := runtime.DefaultUnstructuredConverter.FromUnstructured(rawData.UnstructuredContent(), namespace); err != nil {
message.WarnErrf(err, "could not parse namespace %s", rawData.GetName())
} else {
message.Debugf("Matched helm namespace %s for zarf annotation", namespace.Name)
log.Debug("matched Helm namespace for Zarf annotation", "namespace", namespace.Name)
namespace.Labels = cluster.AdoptZarfManagedLabels(namespace.Labels)
// Add it to the stack
r.namespaces[namespace.Name] = namespace
Expand All @@ -252,7 +255,7 @@ func (r *renderer) editHelmResources(ctx context.Context, resources []releaseuti
}
if key, keyExists := labels[cluster.ZarfConnectLabelName]; keyExists {
// If there is a zarf-connect label
message.Debugf("Match helm service %s for zarf connection %s", rawData.GetName(), key)
log.Debug("match Helm service for Zarf connection", "service", rawData.GetName(), "connection", key)

// Add the connectString for processing later in the deployment
r.connectStrings[key] = types.ConnectString{
Expand Down
5 changes: 3 additions & 2 deletions src/internal/packager/helm/repo.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (
"github.com/zarf-dev/zarf/src/config"
"github.com/zarf-dev/zarf/src/config/lang"
"github.com/zarf-dev/zarf/src/internal/git"
"github.com/zarf-dev/zarf/src/pkg/logging"
"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 All @@ -39,7 +40,7 @@ func (h *Helm) PackageChart(ctx context.Context, cosignKeyPath string) error {
// check if the chart is a git url with a ref (if an error is returned url will be empty)
isGitURL := strings.HasSuffix(url, ".git")
if err != nil {
message.Debugf("unable to parse the url, continuing with %s", h.chart.URL)
logging.FromContextOrDiscard(ctx).Debug("continuing with original url as the url could not be parsed", "url", h.chart.URL, "error", err)
}

if isGitURL {
Expand Down Expand Up @@ -147,7 +148,7 @@ func (h *Helm) DownloadPublishedChart(ctx context.Context, cosignKeyPath string)

// Not returning the error here since the repo file is only needed if we are pulling from a repo that requires authentication
if err != nil {
message.Debugf("Unable to load the repo file at %q: %s", pull.Settings.RepositoryConfig, err.Error())
logging.FromContextOrDiscard(ctx).Debug("unable to load the repository file", "path", pull.Settings.RepositoryConfig, "error", err)
}

var username string
Expand Down
2 changes: 1 addition & 1 deletion src/internal/packager/images/pull.go
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,7 @@ func Pull(ctx context.Context, cfg PullConfig) (map[transform.Image]v1.Image, er

doneSaving := make(chan error)
updateText := fmt.Sprintf("Pulling %d images", imageCount)
go utils.RenderProgressBarForLocalDirWrite(cfg.DestinationDirectory, totalBytes.Load(), doneSaving, updateText, updateText)
go utils.RenderProgressBarForLocalDirWrite(ctx, cfg.DestinationDirectory, totalBytes.Load(), doneSaving, updateText, updateText)

toPull := maps.Clone(fetched)

Expand Down
2 changes: 0 additions & 2 deletions src/internal/packager/images/push.go
Original file line number Diff line number Diff line change
Expand Up @@ -113,8 +113,6 @@ func Push(ctx context.Context, cfg PushConfig) error {
return err
}

message.Debugf("push %s -> %s)", refInfo.Reference, offlineName)

if err = pushImage(img, offlineName); err != nil {
return err
}
Expand Down
6 changes: 4 additions & 2 deletions src/internal/packager/sbom/catalog.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
package sbom

import (
"context"
"embed"
"fmt"
"os"
Expand All @@ -27,6 +28,7 @@ import (
v1 "github.com/google/go-containerregistry/pkg/v1"
"github.com/zarf-dev/zarf/src/config"
"github.com/zarf-dev/zarf/src/pkg/layout"
"github.com/zarf-dev/zarf/src/pkg/logging"
"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 All @@ -48,7 +50,7 @@ var transformRegex = regexp.MustCompile(`(?m)[^a-zA-Z0-9\.\-]`)
var componentPrefix = "zarf-component-"

// Catalog catalogs the given components and images to create an SBOM.
func Catalog(componentSBOMs map[string]*layout.ComponentSBOM, imageList []transform.Image, paths *layout.PackagePaths) error {
func Catalog(ctx context.Context, componentSBOMs map[string]*layout.ComponentSBOM, imageList []transform.Image, paths *layout.PackagePaths) error {
imageCount := len(imageList)
componentCount := len(componentSBOMs)
builder := Builder{
Expand Down Expand Up @@ -103,7 +105,7 @@ func Catalog(componentSBOMs map[string]*layout.ComponentSBOM, imageList []transf
builder.spinner.Updatef("Creating component file SBOMs (%d of %d): %s", currComponent, componentCount, component)

if componentSBOMs[component] == nil {
message.Debugf("Component %s has invalid SBOM, skipping", component)
logging.FromContextOrDiscard(ctx).Debug("component has invalid SBOM, skipping", "component", component)
continue
}

Expand Down
Loading

0 comments on commit 320bf7c

Please sign in to comment.