From 4a895cd44c0b475d6758b628e9180998e0d7a643 Mon Sep 17 00:00:00 2001 From: Philip Laine Date: Thu, 6 Jun 2024 10:40:34 +0200 Subject: [PATCH] fix: handle errors in version command --- src/cmd/version.go | 39 +++++++++++++++++++++++---------------- 1 file changed, 23 insertions(+), 16 deletions(-) diff --git a/src/cmd/version.go b/src/cmd/version.go index 1daa7af61f..f5e1b7390c 100644 --- a/src/cmd/version.go +++ b/src/cmd/version.go @@ -6,17 +6,17 @@ package cmd import ( "encoding/json" + "errors" "fmt" "runtime" + "runtime/debug" "github.com/Masterminds/semver/v3" - "github.com/defenseunicorns/zarf/src/config" - "github.com/defenseunicorns/zarf/src/config/lang" + goyaml "github.com/goccy/go-yaml" "github.com/spf13/cobra" - "runtime/debug" - - goyaml "github.com/goccy/go-yaml" + "github.com/defenseunicorns/zarf/src/config" + "github.com/defenseunicorns/zarf/src/config/lang" ) var outputFormat string @@ -29,13 +29,13 @@ var versionCmd = &cobra.Command{ }, Short: lang.CmdVersionShort, Long: lang.CmdVersionLong, - Run: func(_ *cobra.Command, _ []string) { + RunE: func(_ *cobra.Command, _ []string) error { output := make(map[string]interface{}) + output["version"] = config.CLIVersion buildInfo, ok := debug.ReadBuildInfo() if !ok && outputFormat != "" { - fmt.Println("Failed to get build info") - return + return errors.New("failed to get build info") } depMap := map[string]string{} for _, dep := range buildInfo.Deps { @@ -50,28 +50,35 @@ var versionCmd = &cobra.Command{ buildMap := make(map[string]interface{}) buildMap["platform"] = runtime.GOOS + "/" + runtime.GOARCH buildMap["goVersion"] = runtime.Version() - ver, _ := semver.NewVersion(config.CLIVersion) + ver, err := semver.NewVersion(config.CLIVersion) + if err != nil { + return fmt.Errorf("Could not parse CLI version %s: %w", config.CLIVersion, err) + } if ver != nil { buildMap["major"] = ver.Major() buildMap["minor"] = ver.Minor() buildMap["patch"] = ver.Patch() buildMap["prerelease"] = ver.Prerelease() } - - output["version"] = config.CLIVersion - output["build"] = buildMap switch outputFormat { case "yaml": - text, _ := goyaml.Marshal(output) - fmt.Println(string(text)) + b, err := goyaml.Marshal(output) + if err != nil { + return fmt.Errorf("could not marshal yaml output: %w", err) + } + fmt.Println(string(b)) case "json": - text, _ := json.Marshal(output) - fmt.Println(string(text)) + b, err := json.Marshal(output) + if err != nil { + return fmt.Errorf("could not marshal json output: %w", err) + } + fmt.Println(string(b)) default: fmt.Println(config.CLIVersion) } + return nil }, }