Adding version command to cli tool

main
Drew Bednar 6 days ago
parent 6cfbcfe460
commit e04ef0df1d

@ -6,6 +6,7 @@ VERSION := $(shell git describe --tags --always --dirty 2>/dev/null || echo "dev
BUILD_TIME := $(shell date -u '+%Y-%m-%d_%H:%M:%S') BUILD_TIME := $(shell date -u '+%Y-%m-%d_%H:%M:%S')
GIT_COMMIT := $(shell git rev-parse HEAD 2>/dev/null || echo "unknown") GIT_COMMIT := $(shell git rev-parse HEAD 2>/dev/null || echo "unknown")
DEB_PACKAGE_NAME := $(BINARY_NAME)_$(VERSION)_amd64.deb DEB_PACKAGE_NAME := $(BINARY_NAME)_$(VERSION)_amd64.deb
PKG_PATH=git.runcible.io/${REPO_OWNER}/${REPO_NAME}/cmd
# Default target # Default target
.PHONY: all .PHONY: all
@ -16,7 +17,7 @@ all: build
build: build:
@echo "Building $(BINARY_NAME) version $(VERSION)..." @echo "Building $(BINARY_NAME) version $(VERSION)..."
@mkdir -p $(BUILD_DIR) @mkdir -p $(BUILD_DIR)
@go build -ldflags "-X main.Version=$(VERSION) -X main.BuildTime=$(BUILD_TIME) -X main.GitCommit=$(GIT_COMMIT)" \ @go build -ldflags "-X $(PKG_PATH).Version=$(VERSION) -X $(PKG_PATH).BuildTime=$(BUILD_TIME) -X $(PKG_PATH).GitCommit=$(GIT_COMMIT)" \
-o $(BUILD_DIR)/$(BINARY_NAME) . -o $(BUILD_DIR)/$(BINARY_NAME) .
# Clean build artifacts # Clean build artifacts

@ -13,7 +13,7 @@ var rootCmd = &cobra.Command{
Long: `A longer description that spans multiple lines and likely contains Long: `A longer description that spans multiple lines and likely contains
examples and usage of using your application.`, examples and usage of using your application.`,
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
fmt.Println("Hello from your new Go CLI!") fmt.Println("Hello from your new Go CLI tool ${REPO_NAME}!")
}, },
} }

@ -0,0 +1,38 @@
package cmd
import (
"fmt"
"runtime/debug"
"github.com/spf13/cobra"
)
// These variables are set at build time using ldflags
var (
Version = "dev" // Represents the version of the application
BuildTime = "unknown" // The time the binary was built
GitCommit = "unknown" // The git commit hash
)
// versionCmd represents the version command
var versionCmd = &cobra.Command{
Use: "version",
Short: "Print the version number, build time, and git commit",
Long: `Displays the application's version, the time it was built, the git commit it was built from, and the Go version used.`,
Run: func(cmd *cobra.Command, args []string) {
fmt.Printf("Version: %s\n", Version)
fmt.Printf("Build Time: %s\n", BuildTime)
fmt.Printf("Git Commit: %s\n", GitCommit)
// Print Go version and other build info if available
if info, ok := debug.ReadBuildInfo(); ok {
fmt.Printf("Go Version: %s\n", info.GoVersion)
}
},
}
// init function is called by Go when the package is initialized.
// We use it to add the 'version' command to our root command.
func init() {
rootCmd.AddCommand(versionCmd)
}
Loading…
Cancel
Save