Skip to content

Commit

Permalink
refactor: replace message.Info, message.Note and message.Success with…
Browse files Browse the repository at this point in the history
… context logger

Signed-off-by: Philip Laine <philip.laine@gmail.com>
  • Loading branch information
phillebaba committed Aug 29, 2024
1 parent ea28ea2 commit 7058e2c
Show file tree
Hide file tree
Showing 17 changed files with 43 additions and 61 deletions.
3 changes: 2 additions & 1 deletion src/cmd/initialize.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import (
"github.com/zarf-dev/zarf/src/cmd/common"
"github.com/zarf-dev/zarf/src/config"
"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"
"github.com/zarf-dev/zarf/src/pkg/packager/sources"
Expand Down Expand Up @@ -127,7 +128,7 @@ func downloadInitPackage(ctx context.Context, cacheDirectory string) (string, er
// 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)
logging.FromContextOrDiscard(ctx).Info("Downloading init package will require an internet connection")

// Prompt the user if --confirm not specified
if !confirmDownload {
Expand Down
5 changes: 3 additions & 2 deletions src/cmd/internal.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import (
"github.com/zarf-dev/zarf/src/internal/agent"
"github.com/zarf-dev/zarf/src/internal/gitea"
"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/types"
)
Expand Down Expand Up @@ -67,7 +68,7 @@ var httpProxyCmd = &cobra.Command{
var genCLIDocs = &cobra.Command{
Use: "gen-cli-docs",
Short: lang.CmdInternalGenerateCliDocsShort,
RunE: func(_ *cobra.Command, _ []string) error {
RunE: func(cmd *cobra.Command, _ []string) error {
// Don't include the datestamp in the output
rootCmd.DisableAutoGenTag = true

Expand Down Expand Up @@ -161,7 +162,7 @@ tableOfContents: false
if err := doc.GenMarkdownTreeCustom(rootCmd, "./site/src/content/docs/commands", prependTitle, linkHandler); err != nil {
return err
}
message.Success(lang.CmdInternalGenerateCliDocsSuccess)
logging.FromContextOrDiscard(cmd.Context()).Info("Successfully createed the CLI documentation")
return nil
},
}
Expand Down
18 changes: 9 additions & 9 deletions src/cmd/tools/crane.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
package tools

import (
"context"
"errors"
"fmt"
"os"
Expand All @@ -20,6 +21,7 @@ import (
"github.com/zarf-dev/zarf/src/config/lang"
"github.com/zarf-dev/zarf/src/internal/packager/images"
"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/transform"
"github.com/zarf-dev/zarf/src/types"
Expand Down Expand Up @@ -239,13 +241,15 @@ func pruneImages(cmd *cobra.Command, _ []string) error {
if tunnel != nil {
message.Notef(lang.CmdToolsRegistryTunnel, registryEndpoint, zarfState.RegistryInfo.Address)
defer tunnel.Close()
return tunnel.Wrap(func() error { return doPruneImagesForPackages(zarfState, zarfPackages, registryEndpoint) })
return tunnel.Wrap(func() error { return doPruneImagesForPackages(ctx, zarfState, zarfPackages, registryEndpoint) })
}

return doPruneImagesForPackages(zarfState, zarfPackages, registryEndpoint)
return doPruneImagesForPackages(ctx, zarfState, zarfPackages, registryEndpoint)
}

func doPruneImagesForPackages(zarfState *types.ZarfState, zarfPackages []types.DeployedPackage, registryEndpoint string) error {
func doPruneImagesForPackages(ctx context.Context, zarfState *types.ZarfState, zarfPackages []types.DeployedPackage, registryEndpoint string) error {
log := logging.FromContextOrDiscard(ctx)

authOption := images.WithPushAuth(zarfState.RegistryInfo)

spinner := message.NewProgressSpinner(lang.CmdToolsRegistryPruneLookup)
Expand Down Expand Up @@ -320,11 +324,7 @@ func doPruneImagesForPackages(zarfState *types.ZarfState, zarfPackages []types.D
spinner.Success()

if len(imageDigestsToPrune) > 0 {
message.Note(lang.CmdToolsRegistryPruneImageList)

for digestRef := range imageDigestsToPrune {
message.Info(digestRef)
}
log.Info("Pruning images with digests from the registry", "digests", imageDigestsToPrune)

confirm := config.CommonOptions.Confirm

Expand Down Expand Up @@ -353,7 +353,7 @@ func doPruneImagesForPackages(zarfState *types.ZarfState, zarfPackages []types.D
spinner.Success()
}
} else {
message.Note(lang.CmdToolsRegistryPruneNoImages)
log.Info("Tehere are no images to prune")
}

return nil
Expand Down
18 changes: 10 additions & 8 deletions src/cmd/tools/zarf.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import (
"github.com/zarf-dev/zarf/src/internal/packager/helm"
"github.com/zarf-dev/zarf/src/internal/packager/template"
"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/packager/sources"
"github.com/zarf-dev/zarf/src/pkg/pki"
Expand Down Expand Up @@ -127,7 +128,7 @@ var updateCredsCmd = &cobra.Command{
confirm := config.CommonOptions.Confirm

if confirm {
message.Note(lang.CmdToolsUpdateCredsConfirmProvided)
logging.FromContextOrDiscard(ctx).Info("Confirm flag specified, continuing without prompting")
} else {
prompt := &survey.Confirm{
Message: lang.CmdToolsUpdateCredsConfirmContinue,
Expand Down Expand Up @@ -204,12 +205,13 @@ var clearCacheCmd = &cobra.Command{
Use: "clear-cache",
Aliases: []string{"c"},
Short: lang.CmdToolsClearCacheShort,
RunE: func(_ *cobra.Command, _ []string) error {
message.Notef(lang.CmdToolsClearCacheDir, config.GetAbsCachePath())
RunE: func(cmd *cobra.Command, _ []string) error {
log := logging.FromContextOrDiscard(cmd.Context())
log.Info("Using cache directory", "path", config.GetAbsCachePath())
if err := os.RemoveAll(config.GetAbsCachePath()); err != nil {
return fmt.Errorf("unable to clear the cache directory %s: %w", config.GetAbsCachePath(), err)
}
message.Successf(lang.CmdToolsClearCacheSuccess, config.GetAbsCachePath())
log.Info("Successfully cleared the cache", "path", config.GetAbsCachePath())
return nil
},
}
Expand Down Expand Up @@ -237,7 +239,7 @@ var generatePKICmd = &cobra.Command{
Aliases: []string{"pki"},
Short: lang.CmdToolsGenPkiShort,
Args: cobra.ExactArgs(1),
RunE: func(_ *cobra.Command, args []string) error {
RunE: func(cmd *cobra.Command, args []string) error {
pki, err := pki.GeneratePKI(args[0], subAltNames...)
if err != nil {
return err
Expand All @@ -251,7 +253,7 @@ var generatePKICmd = &cobra.Command{
if err := os.WriteFile("tls.key", pki.Key, helpers.ReadWriteUser); err != nil {
return err
}
message.Successf(lang.CmdToolsGenPkiSuccess, args[0])
logging.FromContextOrDiscard(cmd.Context()).Info("Successfully created a chain of trust", "host", args[0])
return nil
},
}
Expand All @@ -260,7 +262,7 @@ var generateKeyCmd = &cobra.Command{
Use: "gen-key",
Aliases: []string{"key"},
Short: lang.CmdToolsGenKeyShort,
RunE: func(_ *cobra.Command, _ []string) error {
RunE: func(cmd *cobra.Command, _ []string) error {
// Utility function to prompt the user for the password to the private key
passwordFunc := func(bool) ([]byte, error) {
// perform the first prompt
Expand Down Expand Up @@ -323,7 +325,7 @@ var generateKeyCmd = &cobra.Command{
return err
}

message.Successf(lang.CmdToolsGenKeySuccess, prvKeyFileName, pubKeyFileName)
logging.FromContextOrDiscard(cmd.Context()).Info("Generated key pair", "private key", prvKeyFileName, "public key", pubKeyFileName)
return nil
},
}
Expand Down
12 changes: 1 addition & 11 deletions src/config/lang/english.go
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,6 @@ $ zarf init --artifact-push-password={PASSWORD} --artifact-push-username={USERNA
CmdInitErrValidateArtifact = "the 'artifact-push-username' and 'artifact-push-token' flags must be provided if the 'artifact-url' flag is provided"

CmdInitPullAsk = "It seems the init package could not be found locally, but can be pulled from oci://%s"
CmdInitPullNote = "Note: This will require an internet connection."
CmdInitPullConfirm = "Do you want to pull this init package?"
CmdInitPullErrManual = "pull the init package manually and place it in the current working directory"

Expand Down Expand Up @@ -183,8 +182,7 @@ $ zarf init --artifact-push-password={PASSWORD} --artifact-push-username={USERNA
"This command starts up a http proxy that can be used by running pods to transform queries " +
"that conform to Gitea / Gitlab repository and package URLs in the airgap."

CmdInternalGenerateCliDocsShort = "Creates auto-generated markdown of all the commands for the CLI"
CmdInternalGenerateCliDocsSuccess = "Successfully created the CLI documentation"
CmdInternalGenerateCliDocsShort = "Creates auto-generated markdown of all the commands for the CLI"

CmdInternalConfigSchemaShort = "Generates a JSON schema for the zarf.yaml configuration"

Expand Down Expand Up @@ -417,8 +415,6 @@ $ zarf tools registry digest reg.example.com/stefanprodan/podinfo:6.4.0

CmdToolsRegistryPruneShort = "Prunes images from the registry that are not currently being used by any Zarf packages."
CmdToolsRegistryPruneFlagConfirm = "Confirm the image prune action to prevent accidental deletions"
CmdToolsRegistryPruneImageList = "The following image digests will be pruned from the registry:"
CmdToolsRegistryPruneNoImages = "There are no images to prune"
CmdToolsRegistryPruneLookup = "Looking up images within package definitions"
CmdToolsRegistryPruneCatalog = "Cataloging images in the registry"
CmdToolsRegistryPruneCalculate = "Calculating images to prune"
Expand Down Expand Up @@ -482,15 +478,12 @@ zarf tools yq e '.a.b = "cool"' -i file.yaml
CmdToolsHelmLong = "Subset of the Helm CLI that includes the repo and dependency commands for managing helm charts destined for the air gap."

CmdToolsClearCacheShort = "Clears the configured git and image cache directory"
CmdToolsClearCacheDir = "Cache directory set to: %s"
CmdToolsClearCacheSuccess = "Successfully cleared the cache from %s"
CmdToolsClearCacheFlagCachePath = "Specify the location of the Zarf artifact cache (images and git repositories)"

CmdToolsDownloadInitShort = "Downloads the init package for the current Zarf version into the specified directory"
CmdToolsDownloadInitFlagOutputDirectory = "Specify a directory to place the init package in."

CmdToolsGenPkiShort = "Generates a Certificate Authority and PKI chain of trust for the given host"
CmdToolsGenPkiSuccess = "Successfully created a chain of trust for %s"
CmdToolsGenPkiFlagAltName = "Specify Subject Alternative Names for the certificate"

CmdToolsGenKeyShort = "Generates a cosign public/private keypair that can be used to sign packages"
Expand All @@ -499,7 +492,6 @@ zarf tools yq e '.a.b = "cool"' -i file.yaml
CmdToolsGenKeyPromptExists = "File %s already exists. Overwrite? "
CmdToolsGenKeyErrUnableGetPassword = "unable to get password for private key: %s"
CmdToolsGenKeyErrPasswordsNotMatch = "passwords do not match"
CmdToolsGenKeySuccess = "Generated key pair and written to %s and %s"

CmdToolsSbomShort = "Generates a Software Bill of Materials (SBOM) for the given package"

Expand Down Expand Up @@ -573,7 +565,6 @@ $ zarf tools update-creds artifact --artifact-push-username={USERNAME} --artifac
# NOTE: Not specifying a pull username/password will keep the previous pull username/password.
`
CmdToolsUpdateCredsConfirmFlag = "Confirm updating credentials without prompting"
CmdToolsUpdateCredsConfirmProvided = "Confirm flag specified, continuing without prompting."
CmdToolsUpdateCredsConfirmContinue = "Continue with these changes?"
CmdToolsUpdateCredsUnableUpdateRegistry = "Unable to update Zarf Registry values: %s"
CmdToolsUpdateCredsUnableUpdateAgent = "Unable to update Zarf Agent TLS secrets: %s"
Expand All @@ -595,7 +586,6 @@ $ zarf tools update-creds artifact --artifact-push-username={USERNAME} --artifac
// These are only seen in the Kubernetes logs.
const (
AgentInfoWebhookAllowed = "Webhook [%s - %s] - Allowed: %t"
AgentInfoPort = "Server running in port: %s"
AgentWarnNotOCIType = "Skipping HelmRepo mutation because the type is not OCI: %s"
AgentWarnSemVerRef = "Detected a semver OCI ref (%s) - continuing but will be unable to guarantee against collisions if multiple OCI artifacts with the same name are brought in from different registries"
AgentErrBadRequest = "could not read request body: %s"
Expand Down
3 changes: 0 additions & 3 deletions src/internal/agent/hooks/argocd-repository.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import (
"github.com/zarf-dev/zarf/src/config/lang"
"github.com/zarf-dev/zarf/src/internal/agent/operations"
"github.com/zarf-dev/zarf/src/pkg/cluster"
"github.com/zarf-dev/zarf/src/pkg/message"
"github.com/zarf-dev/zarf/src/pkg/transform"
"github.com/zarf-dev/zarf/src/types"
v1 "k8s.io/api/admission/v1"
Expand Down Expand Up @@ -57,8 +56,6 @@ func mutateRepositorySecret(ctx context.Context, r *v1.AdmissionRequest, cluster
return nil, err
}

message.Infof("Using the url of (%s) to mutate the ArgoCD Repository Secret", state.GitServer.Address)

secret := corev1.Secret{}
if err = json.Unmarshal(r.Object.Raw, &secret); err != nil {
return nil, fmt.Errorf(lang.ErrUnmarshal, err)
Expand Down
1 change: 0 additions & 1 deletion src/internal/agent/http/admission/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,6 @@ func (h *Handler) Serve(hook operations.Hook) http.HandlerFunc {
return
}

message.Infof(lang.AgentInfoWebhookAllowed, r.URL.Path, review.Request.Operation, result.Allowed)
w.WriteHeader(http.StatusOK)
//nolint: errcheck // ignore
w.Write(jsonResponse)
Expand Down
5 changes: 2 additions & 3 deletions src/internal/agent/start.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,11 @@ import (
"github.com/prometheus/client_golang/prometheus/promhttp"
"golang.org/x/sync/errgroup"

"github.com/zarf-dev/zarf/src/config/lang"
"github.com/zarf-dev/zarf/src/internal/agent/hooks"
agentHttp "github.com/zarf-dev/zarf/src/internal/agent/http"
"github.com/zarf-dev/zarf/src/internal/agent/http/admission"
"github.com/zarf-dev/zarf/src/pkg/cluster"
"github.com/zarf-dev/zarf/src/pkg/message"
"github.com/zarf-dev/zarf/src/pkg/logging"
)

// Heavily influenced by https://github.com/douglasmakey/admissioncontroller and
Expand Down Expand Up @@ -93,7 +92,7 @@ func startServer(ctx context.Context, port string, mux *http.ServeMux) error {
}
return nil
})
message.Infof(lang.AgentInfoPort, httpPort)
logging.FromContextOrDiscard(ctx).Info("server running", "port", httpPort)
err := g.Wait()
if err != nil {
return err
Expand Down
3 changes: 1 addition & 2 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/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 @@ -96,7 +95,7 @@ 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())
logging.FromContextOrDiscard(ctx).Error("Failling back to the host git, failed to clone the repo with Zarf", "error", err, "repository", gitURLNoRef)
err := r.gitCloneFallback(ctx, gitURLNoRef, ref, shallow)
if err != nil {
return nil, err
Expand Down
4 changes: 2 additions & 2 deletions src/pkg/lint/lint.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,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/message"
"github.com/zarf-dev/zarf/src/pkg/logging"
"github.com/zarf-dev/zarf/src/pkg/packager/composer"
"github.com/zarf-dev/zarf/src/pkg/utils"
"github.com/zarf-dev/zarf/src/types"
Expand Down Expand Up @@ -43,7 +43,7 @@ func Validate(ctx context.Context, createOpts types.ZarfCreateOptions) error {
findings = append(findings, schemaFindings...)

if len(findings) == 0 {
message.Successf("0 findings for %q", pkg.Metadata.Name)
logging.FromContextOrDiscard(ctx).Info("No findings found", "package", pkg.Metadata.Name)
return nil
}
PrintFindings(findings, SevWarn, createOpts.BaseDir, pkg.Metadata.Name)
Expand Down
5 changes: 0 additions & 5 deletions src/pkg/message/message.go
Original file line number Diff line number Diff line change
Expand Up @@ -156,11 +156,6 @@ func Infof(format string, a ...any) {
}
}

// Success prints a success message.
func Success(message string) {
Successf("%s", message)
}

// Successf prints a success message with a given format.
func Successf(format string, a ...any) {
message := Paragraph(format, a...)
Expand Down
4 changes: 2 additions & 2 deletions src/pkg/packager/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import (
"github.com/defenseunicorns/pkg/helpers/v2"
"github.com/zarf-dev/zarf/src/config"
"github.com/zarf-dev/zarf/src/pkg/layout"
"github.com/zarf-dev/zarf/src/pkg/message"
"github.com/zarf-dev/zarf/src/pkg/logging"
"github.com/zarf-dev/zarf/src/pkg/packager/creator"
)

Expand All @@ -27,7 +27,7 @@ func (p *Packager) Create(ctx context.Context) error {
return fmt.Errorf("unable to access directory %q: %w", p.cfg.CreateOpts.BaseDir, err)
}

message.Note(fmt.Sprintf("Using build directory %s", p.cfg.CreateOpts.BaseDir))
logging.FromContextOrDiscard(ctx).Info("Using build directory", "path", p.cfg.CreateOpts.BaseDir)

pc := creator.NewPackageCreator(p.cfg.CreateOpts, cwd)

Expand Down
4 changes: 2 additions & 2 deletions src/pkg/packager/deploy.go
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ func (p *Packager) Deploy(ctx context.Context) error {
}

// Notify all the things about the successful deployment
message.Successf("Zarf deployment complete")
logging.FromContextOrDiscard(ctx).Info("Zarf deployment complete")

err = p.printTablesForDeployment(ctx, deployedComponents)
if err != nil {
Expand Down Expand Up @@ -257,7 +257,7 @@ func (p *Packager) deployInitComponent(ctx context.Context, component v1alpha1.Z
}

if hasExternalRegistry && (isSeedRegistry || isInjector || isRegistry) {
message.Notef("Not deploying the component (%s) since external registry information was provided during `zarf init`", component.Name)
logging.FromContextOrDiscard(ctx).Info("Skipping deploying the component since external registyr information was provided during init", "component", component.Name)
return nil, nil
}

Expand Down
3 changes: 2 additions & 1 deletion src/pkg/packager/dev.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"runtime"

"github.com/defenseunicorns/pkg/helpers/v2"
"github.com/saferwall/pe/log"
"github.com/zarf-dev/zarf/src/config"
"github.com/zarf-dev/zarf/src/pkg/layout"
"github.com/zarf-dev/zarf/src/pkg/message"
Expand Down Expand Up @@ -95,7 +96,7 @@ func (p *Packager) DevDeploy(ctx context.Context) error {
}

// Notify all the things about the successful deployment
message.Successf("Zarf dev deployment complete")
log.Info("Zarf dev deployment complete")

message.HorizontalRule()
message.Title("Next steps:", "")
Expand Down
Loading

0 comments on commit 7058e2c

Please sign in to comment.