Add version command

This commit is contained in:
Max Jonas Werner
2026-04-09 09:25:10 +02:00
parent 7af1dd5db5
commit 7cabca2ade
2 changed files with 91 additions and 0 deletions

View File

@@ -6,6 +6,7 @@ import (
"os"
"time"
"gitea.e13.dev/e13/kubectl-unready/cmd/version"
"github.com/spf13/cobra"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
@@ -35,6 +36,8 @@ func NewUnreadyCmd(ctx context.Context) *cobra.Command {
cmd.Flags().BoolVarP(&allNamespacesFlag, "all-namespaces", "A", false, "If present, list unready pods across all namespaces.")
cmd.AddCommand(version.NewVersionCmd(ctx))
return cmd
}

88
cmd/version/version.go Normal file
View File

@@ -0,0 +1,88 @@
package version
import (
"context"
"encoding/json/v2"
"fmt"
"os"
"runtime"
"runtime/debug"
"strconv"
"github.com/spf13/cobra"
)
func NewVersionCmd(ctx context.Context) *cobra.Command {
return &cobra.Command{
Use: "version",
Short: "print the plugin's version",
RunE: func(cmd *cobra.Command, args []string) error {
if err := json.MarshalWrite(os.Stdout, Get()); err != nil {
return err
}
fmt.Println()
return nil
},
}
}
// GitTreeState represents the state of the Git repository's working tree
// at the time of compilation. It provides a type-safe way to indicate whether
// the source tree was clean, modified, or in an unknown state.
type GitTreeState string
func (g GitTreeState) String() string {
return string(g)
}
// These constants define all possible values for the GitTreeState contained in Info.
const (
GitTreeStateModified GitTreeState = "modified"
GitTreeStateClean GitTreeState = "clean"
GitTreeStateUnknown GitTreeState = "unknown"
)
// Info carries the information gathered and returned by GetVersion().
type Info struct {
Version string
GitCommit string
GitCommitTime string
GitTreeState GitTreeState
GoVersion string
}
// Get returns the version of the application derived directly from the runtime's debug information.
func Get() Info {
var res Info
bi, ok := debug.ReadBuildInfo()
if !ok {
res.Version = "unknown"
}
res.Version = bi.Main.Version
for _, bs := range bi.Settings {
switch bs.Key {
case "vcs.revision":
res.GitCommit = bs.Value
case "vcs.modified":
mod, err := strconv.ParseBool(bs.Value)
if err != nil {
res.GitTreeState = GitTreeStateUnknown
continue
}
if mod {
res.GitTreeState = GitTreeStateModified
continue
}
res.GitTreeState = GitTreeStateClean
case "vcs.time":
res.GitCommitTime = bs.Value
default:
// we don't care about other settings for now
}
}
res.GoVersion = runtime.Version()
return res
}