Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: remove use of message.Fatal in tools #2602

Merged
merged 3 commits into from
Jun 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion src/cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
"context"
"fmt"
"os"
"slices"
"strings"

"github.com/pterm/pterm"
Expand Down Expand Up @@ -67,8 +68,9 @@
if err == nil {
return
}
defaultPrintCmds := []string{"helm", "yq", "kubectl"}

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

View check run for this annotation

Codecov / codecov/patch

src/cmd/root.go#L71

Added line #L71 was not covered by tests
comps := strings.Split(cmd.CommandPath(), " ")
if len(comps) > 1 && comps[1] == "tools" {
if len(comps) > 1 && comps[1] == "tools" && slices.Contains(defaultPrintCmds, comps[2]) {

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

View check run for this annotation

Codecov / codecov/patch

src/cmd/root.go#L73

Added line #L73 was not covered by tests
cmd.PrintErrln(cmd.ErrPrefix(), err.Error())
} else {
pterm.Error.Println(err.Error())
Expand Down
60 changes: 29 additions & 31 deletions src/cmd/tools/archiver.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@

"github.com/defenseunicorns/zarf/src/config/lang"
"github.com/defenseunicorns/zarf/src/pkg/layout"
"github.com/defenseunicorns/zarf/src/pkg/message"
"github.com/mholt/archiver/v3"
"github.com/spf13/cobra"
)
Expand All @@ -32,12 +31,13 @@
Aliases: []string{"c"},
Short: lang.CmdToolsArchiverCompressShort,
Args: cobra.MinimumNArgs(2),
Run: func(_ *cobra.Command, args []string) {
RunE: func(_ *cobra.Command, args []string) error {

Check warning on line 34 in src/cmd/tools/archiver.go

View check run for this annotation

Codecov / codecov/patch

src/cmd/tools/archiver.go#L34

Added line #L34 was not covered by tests
sourceFiles, destinationArchive := args[:len(args)-1], args[len(args)-1]
err := archiver.Archive(sourceFiles, destinationArchive)
if err != nil {
message.Fatalf(err, lang.CmdToolsArchiverCompressErr, err.Error())
return fmt.Errorf("unable to perform compression: %w", err)

Check warning on line 38 in src/cmd/tools/archiver.go

View check run for this annotation

Codecov / codecov/patch

src/cmd/tools/archiver.go#L38

Added line #L38 was not covered by tests
schristoff-du marked this conversation as resolved.
Show resolved Hide resolved
}
return err

Check warning on line 40 in src/cmd/tools/archiver.go

View check run for this annotation

Codecov / codecov/patch

src/cmd/tools/archiver.go#L40

Added line #L40 was not covered by tests
},
}

Expand All @@ -48,39 +48,40 @@
Aliases: []string{"d"},
Short: lang.CmdToolsArchiverDecompressShort,
Args: cobra.ExactArgs(2),
Run: func(_ *cobra.Command, args []string) {
RunE: func(_ *cobra.Command, args []string) error {

Check warning on line 51 in src/cmd/tools/archiver.go

View check run for this annotation

Codecov / codecov/patch

src/cmd/tools/archiver.go#L51

Added line #L51 was not covered by tests
sourceArchive, destinationPath := args[0], args[1]
err := archiver.Unarchive(sourceArchive, destinationPath)
if err != nil {
message.Fatalf(err, lang.CmdToolsArchiverDecompressErr, err.Error())
return fmt.Errorf("unable to perform decompression: %w", err)

Check warning on line 55 in src/cmd/tools/archiver.go

View check run for this annotation

Codecov / codecov/patch

src/cmd/tools/archiver.go#L55

Added line #L55 was not covered by tests
}

if unarchiveAll {
err := filepath.Walk(destinationPath, func(path string, info os.FileInfo, err error) error {
if !unarchiveAll {
schristoff-du marked this conversation as resolved.
Show resolved Hide resolved
return nil

Check warning on line 58 in src/cmd/tools/archiver.go

View check run for this annotation

Codecov / codecov/patch

src/cmd/tools/archiver.go#L57-L58

Added lines #L57 - L58 were not covered by tests
}
err = filepath.Walk(destinationPath, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err

Check warning on line 62 in src/cmd/tools/archiver.go

View check run for this annotation

Codecov / codecov/patch

src/cmd/tools/archiver.go#L60-L62

Added lines #L60 - L62 were not covered by tests
}
if strings.HasSuffix(path, ".tar") {
dst := filepath.Join(strings.TrimSuffix(path, ".tar"), "..")

Check warning on line 65 in src/cmd/tools/archiver.go

View check run for this annotation

Codecov / codecov/patch

src/cmd/tools/archiver.go#L64-L65

Added lines #L64 - L65 were not covered by tests
// Unpack sboms.tar differently since it has a different folder structure than components
if info.Name() == layout.SBOMTar {
dst = strings.TrimSuffix(path, ".tar")

Check warning on line 68 in src/cmd/tools/archiver.go

View check run for this annotation

Codecov / codecov/patch

src/cmd/tools/archiver.go#L67-L68

Added lines #L67 - L68 were not covered by tests
}
err := archiver.Unarchive(path, dst)

Check warning on line 70 in src/cmd/tools/archiver.go

View check run for this annotation

Codecov / codecov/patch

src/cmd/tools/archiver.go#L70

Added line #L70 was not covered by tests
if err != nil {
return err
return fmt.Errorf(lang.ErrUnarchive, path, err.Error())

Check warning on line 72 in src/cmd/tools/archiver.go

View check run for this annotation

Codecov / codecov/patch

src/cmd/tools/archiver.go#L72

Added line #L72 was not covered by tests
}
if strings.HasSuffix(path, ".tar") {
dst := filepath.Join(strings.TrimSuffix(path, ".tar"), "..")
// Unpack sboms.tar differently since it has a different folder structure than components
if info.Name() == layout.SBOMTar {
dst = strings.TrimSuffix(path, ".tar")
}
err := archiver.Unarchive(path, dst)
if err != nil {
return fmt.Errorf(lang.ErrUnarchive, path, err.Error())
}
err = os.Remove(path)
if err != nil {
return fmt.Errorf(lang.ErrRemoveFile, path, err.Error())
}
err = os.Remove(path)
if err != nil {
return fmt.Errorf(lang.ErrRemoveFile, path, err.Error())

Check warning on line 76 in src/cmd/tools/archiver.go

View check run for this annotation

Codecov / codecov/patch

src/cmd/tools/archiver.go#L74-L76

Added lines #L74 - L76 were not covered by tests
}
return nil
})
if err != nil {
message.Fatalf(err, lang.CmdToolsArchiverUnarchiveAllErr, err.Error())
}
return nil

Check warning on line 79 in src/cmd/tools/archiver.go

View check run for this annotation

Codecov / codecov/patch

src/cmd/tools/archiver.go#L79

Added line #L79 was not covered by tests
})
if err != nil {
return fmt.Errorf("unable to unarchive all nested tarballs: %w", err)

Check warning on line 82 in src/cmd/tools/archiver.go

View check run for this annotation

Codecov / codecov/patch

src/cmd/tools/archiver.go#L81-L82

Added lines #L81 - L82 were not covered by tests
}
return nil

Check warning on line 84 in src/cmd/tools/archiver.go

View check run for this annotation

Codecov / codecov/patch

src/cmd/tools/archiver.go#L84

Added line #L84 was not covered by tests
},
}

Expand All @@ -93,8 +94,5 @@
archiverDecompressCmd.Flags().BoolVar(&unarchiveAll, "decompress-all", false, "Decompress all tarballs in the archive")
archiverDecompressCmd.Flags().BoolVar(&unarchiveAll, "unarchive-all", false, "Unarchive all tarballs in the archive")
archiverDecompressCmd.MarkFlagsMutuallyExclusive("decompress-all", "unarchive-all")
err := archiverDecompressCmd.Flags().MarkHidden("decompress-all")
if err != nil {
message.Fatal(err, err.Error())
}
archiverDecompressCmd.Flags().MarkHidden("decompress-all")

Check warning on line 97 in src/cmd/tools/archiver.go

View check run for this annotation

Codecov / codecov/patch

src/cmd/tools/archiver.go#L97

Added line #L97 was not covered by tests
}
10 changes: 6 additions & 4 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 (
"errors"
"fmt"
"os"
"strings"
Expand Down Expand Up @@ -37,7 +38,7 @@
Use: "registry",
Aliases: []string{"r", "crane"},
Short: lang.CmdToolsRegistryShort,
PersistentPreRun: func(cmd *cobra.Command, _ []string) {
PersistentPreRunE: func(cmd *cobra.Command, _ []string) error {

Check warning on line 41 in src/cmd/tools/crane.go

View check run for this annotation

Codecov / codecov/patch

src/cmd/tools/crane.go#L41

Added line #L41 was not covered by tests
// The crane options loading here comes from the rootCmd of crane
craneOptions = append(craneOptions, crane.WithContext(cmd.Context()))
// TODO(jonjohnsonjr): crane.Verbose option?
Expand All @@ -56,11 +57,12 @@
if platform != "all" {
v1Platform, err = v1.ParsePlatform(platform)
if err != nil {
message.Fatalf(err, lang.CmdToolsRegistryInvalidPlatformErr, platform, err.Error())
return fmt.Errorf("invalid platform %s: %w", platform, err)

Check warning on line 60 in src/cmd/tools/crane.go

View check run for this annotation

Codecov / codecov/patch

src/cmd/tools/crane.go#L60

Added line #L60 was not covered by tests
schristoff-du marked this conversation as resolved.
Show resolved Hide resolved
}
}

craneOptions = append(craneOptions, crane.WithPlatform(v1Platform))
return nil

Check warning on line 65 in src/cmd/tools/crane.go

View check run for this annotation

Codecov / codecov/patch

src/cmd/tools/crane.go#L65

Added line #L65 was not covered by tests
},
}

Expand Down Expand Up @@ -159,7 +161,7 @@

wrappedCommand.RunE = func(cmd *cobra.Command, args []string) error {
if len(args) < imageNameArgumentIndex+1 {
message.Fatal(nil, lang.CmdToolsCraneNotEnoughArgumentsErr)
return errors.New("not have enough arguments specified for this command")

Check warning on line 164 in src/cmd/tools/crane.go

View check run for this annotation

Codecov / codecov/patch

src/cmd/tools/crane.go#L164

Added line #L164 was not covered by tests
}

// Try to connect to a Zarf initialized cluster otherwise then pass it down to crane.
Expand Down Expand Up @@ -333,7 +335,7 @@
Message: lang.CmdConfirmContinue,
}
if err := survey.AskOne(prompt, &confirm); err != nil {
message.Fatalf(nil, lang.ErrConfirmCancel, err)
return fmt.Errorf("confirm selection canceled: %w", err)

Check warning on line 338 in src/cmd/tools/crane.go

View check run for this annotation

Codecov / codecov/patch

src/cmd/tools/crane.go#L338

Added line #L338 was not covered by tests
}
}
if confirm {
Expand Down
11 changes: 2 additions & 9 deletions src/cmd/tools/helm/load_plugins.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@
"strings"
"syscall"

"github.com/defenseunicorns/zarf/src/pkg/message"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"sigs.k8s.io/yaml"
Expand Down Expand Up @@ -217,10 +216,7 @@
if err != nil {
// The file could be missing or invalid. No static completion for this plugin.
if settings.Debug {
err := log.Output(2, fmt.Sprintf("[info] %s\n", err.Error()))
if err != nil {
message.Fatal(err, err.Error())
}
log.Output(2, fmt.Sprintf("[info] %s\n", err.Error()))

Check warning on line 219 in src/cmd/tools/helm/load_plugins.go

View check run for this annotation

Codecov / codecov/patch

src/cmd/tools/helm/load_plugins.go#L219

Added line #L219 was not covered by tests
}
// Continue to setup dynamic completion.
cmds = &pluginCommand{}
Expand All @@ -242,10 +238,7 @@
if len(cmds.Name) == 0 {
// Missing name for a command
if settings.Debug {
err := log.Output(2, fmt.Sprintf("[info] sub-command name field missing for %s", baseCmd.CommandPath()))
if err != nil {
message.Fatal(err, err.Error())
}
log.Output(2, fmt.Sprintf("[info] sub-command name field missing for %s", baseCmd.CommandPath()))

Check warning on line 241 in src/cmd/tools/helm/load_plugins.go

View check run for this annotation

Codecov / codecov/patch

src/cmd/tools/helm/load_plugins.go#L241

Added line #L241 was not covered by tests
}
return
}
Expand Down
7 changes: 1 addition & 6 deletions src/cmd/tools/helm/repo_add.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@

"github.com/defenseunicorns/pkg/helpers/v2"
"github.com/defenseunicorns/zarf/src/pkg/cluster"
"github.com/defenseunicorns/zarf/src/pkg/message"
"github.com/gofrs/flock"
"github.com/pkg/errors"
"github.com/spf13/cobra"
Expand Down Expand Up @@ -134,11 +133,7 @@
defer cancel()
locked, err := fileLock.TryLockContext(lockCtx, time.Second)
if err == nil && locked {
defer func() {
if err := fileLock.Unlock(); err != nil {
message.Fatal(err, err.Error())
}
}()
defer fileLock.Unlock()

Check warning on line 136 in src/cmd/tools/helm/repo_add.go

View check run for this annotation

Codecov / codecov/patch

src/cmd/tools/helm/repo_add.go#L136

Added line #L136 was not covered by tests
}
if err != nil {
return err
Expand Down
3 changes: 1 addition & 2 deletions src/cmd/tools/helm/repo_index.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@
"path/filepath"

"github.com/defenseunicorns/pkg/helpers/v2"
"github.com/defenseunicorns/zarf/src/pkg/message"
"github.com/pkg/errors"
"github.com/spf13/cobra"

Expand Down Expand Up @@ -104,7 +103,7 @@
i2 = repo.NewIndexFile()
err := i2.WriteFile(mergeTo, helpers.ReadAllWriteUser)
if err != nil {
message.Fatal(err, err.Error())
return err

Check warning on line 106 in src/cmd/tools/helm/repo_index.go

View check run for this annotation

Codecov / codecov/patch

src/cmd/tools/helm/repo_index.go#L106

Added line #L106 was not covered by tests
}
} else {
i2, err = repo.LoadIndexFile(mergeTo)
Expand Down
8 changes: 5 additions & 3 deletions src/cmd/tools/wait.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
package tools

import (
"fmt"
"time"

"github.com/defenseunicorns/zarf/src/config/lang"
Expand All @@ -28,11 +29,11 @@
Long: lang.CmdToolsWaitForLong,
Example: lang.CmdToolsWaitForExample,
Args: cobra.MinimumNArgs(1),
Run: func(_ *cobra.Command, args []string) {
RunE: func(_ *cobra.Command, args []string) error {

Check warning on line 32 in src/cmd/tools/wait.go

View check run for this annotation

Codecov / codecov/patch

src/cmd/tools/wait.go#L32

Added line #L32 was not covered by tests
// Parse the timeout string
timeout, err := time.ParseDuration(waitTimeout)
if err != nil {
message.Fatalf(err, lang.CmdToolsWaitForErrTimeoutString, waitTimeout)
return fmt.Errorf("invalid timeout duration %s, use a valid duration string e.g. 1s, 2m, 3h: %w", waitTimeout, err)

Check warning on line 36 in src/cmd/tools/wait.go

View check run for this annotation

Codecov / codecov/patch

src/cmd/tools/wait.go#L36

Added line #L36 was not covered by tests
}

kind := args[0]
Expand All @@ -51,8 +52,9 @@

// Execute the wait command.
if err := utils.ExecuteWait(waitTimeout, waitNamespace, condition, kind, identifier, timeout); err != nil {
message.Fatal(err, err.Error())
return err

Check warning on line 55 in src/cmd/tools/wait.go

View check run for this annotation

Codecov / codecov/patch

src/cmd/tools/wait.go#L55

Added line #L55 was not covered by tests
}
return err

Check warning on line 57 in src/cmd/tools/wait.go

View check run for this annotation

Codecov / codecov/patch

src/cmd/tools/wait.go#L57

Added line #L57 was not covered by tests
},
}

Expand Down
8 changes: 2 additions & 6 deletions src/config/lang/english.go
Original file line number Diff line number Diff line change
Expand Up @@ -573,12 +573,8 @@ $ zarf tools wait-for https 1.1.1.1 200 # wait
$ zarf tools wait-for http google.com # wait for any 2xx response from http://google.com
$ zarf tools wait-for http google.com success # wait for any 2xx response from http://google.com
`
CmdToolsWaitForFlagTimeout = "Specify the timeout duration for the wait command."
CmdToolsWaitForErrTimeoutString = "Invalid timeout duration '%s'. Please use a valid duration string (e.g. 1s, 2m, 3h)."
CmdToolsWaitForErrTimeout = "Wait timed out."
CmdToolsWaitForErrConditionString = "Invalid HTTP status code. Please use a valid HTTP status code (e.g. 200, 404, 500)."
CmdToolsWaitForErrZarfPath = "Could not locate the current Zarf binary path."
CmdToolsWaitForFlagNamespace = "Specify the namespace of the resources to wait for."
CmdToolsWaitForFlagTimeout = "Specify the timeout duration for the wait command."
CmdToolsWaitForFlagNamespace = "Specify the namespace of the resources to wait for."

CmdToolsKubectlDocs = "Kubectl command. See https://kubernetes.io/docs/reference/kubectl/overview/ for more information."

Expand Down
22 changes: 12 additions & 10 deletions src/pkg/utils/wait.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
package utils

import (
"errors"
"fmt"
"net"
"net/http"
Expand All @@ -15,7 +16,6 @@

"github.com/defenseunicorns/zarf/src/pkg/utils/exec"

"github.com/defenseunicorns/zarf/src/config/lang"
"github.com/defenseunicorns/zarf/src/pkg/message"
)

Expand All @@ -33,8 +33,7 @@
// Handle network endpoints.
switch kind {
case "http", "https", "tcp":
waitForNetworkEndpoint(kind, identifier, condition, timeout)
return nil
return waitForNetworkEndpoint(kind, identifier, condition, timeout)

Check warning on line 36 in src/pkg/utils/wait.go

View check run for this annotation

Codecov / codecov/patch

src/pkg/utils/wait.go#L36

Added line #L36 was not covered by tests
}

// Type of wait, condition or JSONPath
Expand All @@ -50,7 +49,7 @@
// Get the Zarf command configuration.
zarfCommand, err := GetFinalExecutableCommand()
if err != nil {
message.Fatal(err, lang.CmdToolsWaitForErrZarfPath)
return fmt.Errorf("could not locate the current Zarf binary path: %w", err)

Check warning on line 52 in src/pkg/utils/wait.go

View check run for this annotation

Codecov / codecov/patch

src/pkg/utils/wait.go#L52

Added line #L52 was not covered by tests
}

identifierMsg := identifier
Expand Down Expand Up @@ -88,7 +87,7 @@

select {
case <-expired:
message.Fatal(nil, lang.CmdToolsWaitForErrTimeout)
return errors.New("wait timed out")

Check warning on line 90 in src/pkg/utils/wait.go

View check run for this annotation

Codecov / codecov/patch

src/pkg/utils/wait.go#L90

Added line #L90 was not covered by tests

default:
spinner.Updatef(existMsg)
Expand Down Expand Up @@ -132,7 +131,7 @@
}

// waitForNetworkEndpoint waits for a network endpoint to respond.
func waitForNetworkEndpoint(resource, name, condition string, timeout time.Duration) {
func waitForNetworkEndpoint(resource, name, condition string, timeout time.Duration) error {

Check warning on line 134 in src/pkg/utils/wait.go

View check run for this annotation

Codecov / codecov/patch

src/pkg/utils/wait.go#L134

Added line #L134 was not covered by tests
// Set the timeout for the wait-for command.
expired := time.After(timeout)

Expand All @@ -153,7 +152,7 @@

select {
case <-expired:
message.Fatal(nil, lang.CmdToolsWaitForErrTimeout)
return errors.New("wait timed out")

Check warning on line 155 in src/pkg/utils/wait.go

View check run for this annotation

Codecov / codecov/patch

src/pkg/utils/wait.go#L155

Added line #L155 was not covered by tests

default:
switch resource {
Expand All @@ -179,8 +178,11 @@

// Convert the condition to an int and check if it's a valid HTTP status code.
code, err := strconv.Atoi(condition)
if err != nil || http.StatusText(code) == "" {
message.Fatal(err, lang.CmdToolsWaitForErrConditionString)
if err != nil {
return fmt.Errorf("http status code %s is not an integer: %w", condition, err)

Check warning on line 182 in src/pkg/utils/wait.go

View check run for this annotation

Codecov / codecov/patch

src/pkg/utils/wait.go#L181-L182

Added lines #L181 - L182 were not covered by tests
}
if http.StatusText(code) == "" {
return errors.New("http status code %s is unknown")

Check warning on line 185 in src/pkg/utils/wait.go

View check run for this annotation

Codecov / codecov/patch

src/pkg/utils/wait.go#L184-L185

Added lines #L184 - L185 were not covered by tests
}

// Try to get the URL and check the status code.
Expand All @@ -202,7 +204,7 @@

// Yay, we made it!
spinner.Success()
return
return nil

Check warning on line 207 in src/pkg/utils/wait.go

View check run for this annotation

Codecov / codecov/patch

src/pkg/utils/wait.go#L207

Added line #L207 was not covered by tests
}
}
}
Loading