diff --git a/src/cmd/version.go b/src/cmd/version.go index 1daa7af61f..589cab9929 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,18 @@ var versionCmd = &cobra.Command{ }, Short: lang.CmdVersionShort, Long: lang.CmdVersionLong, - Run: func(_ *cobra.Command, _ []string) { + RunE: func(_ *cobra.Command, _ []string) error { + if outputFormat == "" { + fmt.Println(config.CLIVersion) + return nil + } + output := make(map[string]interface{}) + output["version"] = config.CLIVersion buildInfo, ok := debug.ReadBuildInfo() - if !ok && outputFormat != "" { - fmt.Println("Failed to get build info") - return + if !ok { + return errors.New("failed to get build info") } depMap := map[string]string{} for _, dep := range buildInfo.Deps { @@ -50,28 +55,33 @@ 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 && !errors.Is(err, semver.ErrInvalidSemVer) { + 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)) - default: - fmt.Println(config.CLIVersion) + b, err := json.Marshal(output) + if err != nil { + return fmt.Errorf("could not marshal json output: %w", err) + } + fmt.Println(string(b)) } + return nil }, }