Skip to content

Commit

Permalink
fix: handle errors in version command
Browse files Browse the repository at this point in the history
  • Loading branch information
phillebaba committed Jun 7, 2024
1 parent c1d1d44 commit 8232f12
Showing 1 changed file with 29 additions and 19 deletions.
48 changes: 29 additions & 19 deletions src/cmd/version.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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 {
Expand All @@ -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
},
}

Expand Down

0 comments on commit 8232f12

Please sign in to comment.