Skip to content

Commit

Permalink
add function for JSON outp
Browse files Browse the repository at this point in the history
Signed-off-by: Somtochi Onyekwere <[email protected]>
  • Loading branch information
somtochiama committed Dec 6, 2023
1 parent 33b2fd5 commit b47a545
Showing 1 changed file with 22 additions and 13 deletions.
35 changes: 22 additions & 13 deletions cmd/flux/version.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,15 +78,12 @@ func versionCmdRun(cmd *cobra.Command, args []string) error {
ctx, cancel := context.WithTimeout(context.Background(), rootArgs.timeout)
defer cancel()

// VersionInfo struct is used for yaml because we care about the order.
// Without this `distribution` is printed before `flux`.
// Unfortunately, encoding/json doesn't support the inline tag, so the struct can't be used for json.
yamlInfo := &versionInfo{
// VersionInfo struct and goyaml is used because we care about the order.
// Without this `distribution` is printed before `flux` when the struct is marshalled.
info := &versionInfo{
Controller: map[string]string{},
}
info := map[string]string{}
info["flux"] = rootArgs.defaults.Version
yamlInfo.Flux = rootArgs.defaults.Version
info.Flux = rootArgs.defaults.Version

if !versionArgs.client {
kubeClient, err := utils.KubeClient(kubeconfigArgs, kubeclientOptions)
Expand All @@ -99,8 +96,7 @@ func versionCmdRun(cmd *cobra.Command, args []string) error {
return err
}
if clusterInfo.distribution() != "" {
info["distribution"] = clusterInfo.distribution()
yamlInfo.Distribution = clusterInfo.distribution()
info.Distribution = clusterInfo.distribution()
}

selector := client.MatchingLabels{manifestgen.PartOfLabelKey: manifestgen.PartOfLabelValue}
Expand All @@ -119,8 +115,7 @@ func versionCmdRun(cmd *cobra.Command, args []string) error {
if err != nil {
return err
}
info[name] = tag
yamlInfo.Controller[name] = tag
info.Controller[name] = tag
}
}
}
Expand All @@ -129,10 +124,10 @@ func versionCmdRun(cmd *cobra.Command, args []string) error {
var err error

if versionArgs.output == "json" {
marshalled, err = json.MarshalIndent(&info, "", " ")
marshalled, err = info.toJSON()
marshalled = append(marshalled, "\n"...)
} else {
marshalled, err = yaml.Marshal(&yamlInfo)
marshalled, err = yaml.Marshal(&info)
}

if err != nil {
Expand All @@ -143,6 +138,20 @@ func versionCmdRun(cmd *cobra.Command, args []string) error {
return nil
}

func (info versionInfo) toJSON() ([]byte, error) {
mapInfo := map[string]string{
"flux": info.Flux,
}

if info.Distribution != "" {
mapInfo["distribution"] = info.Distribution
}
for k, v := range info.Controller {
mapInfo[k] = v
}
return json.MarshalIndent(&mapInfo, "", " ")
}

func splitImageStr(image string) (string, string, error) {
ref, err := name.ParseReference(image)
if err != nil {
Expand Down

0 comments on commit b47a545

Please sign in to comment.