From c8297534cc0c98307338aa4c00412b7aa550dd90 Mon Sep 17 00:00:00 2001 From: David Allen Date: Wed, 28 Aug 2024 12:34:49 -0600 Subject: [PATCH] Added version command and corresponding implementation --- cmd/version.go | 24 ++++++++++++++++++++++++ internal/version.go | 42 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+) create mode 100644 cmd/version.go create mode 100644 internal/version.go diff --git a/cmd/version.go b/cmd/version.go new file mode 100644 index 0000000..be17843 --- /dev/null +++ b/cmd/version.go @@ -0,0 +1,24 @@ +package cmd + +import ( + "fmt" + + magellan "github.com/OpenCHAMI/magellan/internal" + "github.com/spf13/cobra" +) + +var versionCmd = &cobra.Command{ + Use: "version", + Run: func(cmd *cobra.Command, args []string) { + if cmd.Flag("rev").Value.String() == "true" { + fmt.Println(magellan.VersionCommit()) + } else { + fmt.Println(magellan.VersionTag()) + } + }, +} + +func init() { + versionCmd.Flags().Bool("rev", false, "show the version commit") + rootCmd.AddCommand(versionCmd) +} diff --git a/internal/version.go b/internal/version.go new file mode 100644 index 0000000..f11b47a --- /dev/null +++ b/internal/version.go @@ -0,0 +1,42 @@ +package magellan + +import ( + "fmt" + "os/exec" + "strings" +) + +// VersionCommit() returns a string with 'r{commit_count}.{commit_version}' format. +func VersionCommit() string { + var ( + version string + revlist []byte + revparse []byte + err error + ) + revlist, err = exec.Command("git", "rev-list", "--count", "HEAD").Output() + if err != nil { + return "" + } + + revparse, err = exec.Command("git", "rev-parse", "--short", "HEAD").Output() + if err != nil { + return "" + } + version = fmt.Sprintf("r%s.%s", strings.TrimRight(string(revlist), "\n"), string(revparse)) + return strings.TrimRight(version, "\n") +} + +// VersionTag() returns a string with format '{git_tag}' using the `git describe` command. +func VersionTag() string { + var ( + describe []byte + err error + ) + describe, err = exec.Command("git", "describe", "--long", "HEAD").Output() + if err != nil { + return "" + } + + return strings.TrimRight(string(describe), "\n") +}