penguin/monok8s

k8s image for Mono Gateway Dev Kit

clitools/pkg/cmd/version/version.go

raw ยท 1737 bytes

package version

import (
	"encoding/json"
	"fmt"

	"github.com/spf13/cobra"

	buildinfo "example.com/monok8s/pkg/buildinfo"
)

type versionInfo struct {
	Version     string `json:"version"`
	GitRevision string `json:"gitRevision"`
	Timestamp   string `json:"timestamp"`
	KubeVersion string `json:"kubernetesVersion"`
}

func NewCmdVersion() *cobra.Command {
	var (
		shortOutput      bool
		jsonOutput       bool
		kubernetesOutput bool
	)

	cmd := &cobra.Command{
		Use:   "version",
		Short: "Print version information",
		Args:  cobra.NoArgs,
		RunE: func(cmd *cobra.Command, _ []string) error {
			info := versionInfo{
				Version:     buildinfo.Version,
				GitRevision: buildinfo.GitRevision,
				Timestamp:   buildinfo.Timestamp,
				KubeVersion: buildinfo.KubeVersion,
			}

			out := cmd.OutOrStdout()

			switch {
			case jsonOutput:
				enc := json.NewEncoder(out)
				enc.SetIndent("", "  ")
				return enc.Encode(info)

			case kubernetesOutput:
				_, err := fmt.Fprintln(out, info.KubeVersion)
				return err

			case shortOutput:
				_, err := fmt.Fprintln(out, info.Version)
				return err

			default:
				_, err := fmt.Fprintf(
					out,
					"Version:    %s\nGit commit: %s\nBuilt at:   %s\nKubernetes: %s\n",
					info.Version,
					info.GitRevision,
					info.Timestamp,
					info.KubeVersion,
				)
				return err
			}
		},
	}

	flags := cmd.Flags()
	flags.BoolVar(&shortOutput, "short", false, "Show only the application version")
	flags.BoolVar(&jsonOutput, "json", false, "Show version information as JSON")
	flags.BoolVarP(&kubernetesOutput, "kubernetes", "k", false, "Show only the Kubernetes version this binary was built for")

	cmd.MarkFlagsMutuallyExclusive("short", "json", "kubernetes")

	return cmd
}