Improves the `version` command to automatically extract build details (version, commit, date) from Go's `debug.ReadBuildInfo` when `ldflags` are not provided. This allows users installing via `go install` to receive accurate version information without requiring a Makefile or explicit build flags. Updates the README to reflect this new capability.
59 lines
1.3 KiB
Go
59 lines
1.3 KiB
Go
package cmd
|
|
|
|
import (
|
|
"fmt"
|
|
"runtime/debug"
|
|
|
|
"github.com/spf13/cobra"
|
|
)
|
|
|
|
var (
|
|
// Version is set via -ldflags during build (for make install)
|
|
// Falls back to module version from go install
|
|
Version = "dev"
|
|
// Commit is set via -ldflags during build
|
|
Commit = "unknown"
|
|
// Date is set via -ldflags during build
|
|
Date = "unknown"
|
|
)
|
|
|
|
var versionCmd = &cobra.Command{
|
|
Use: "version",
|
|
Short: "Print version information",
|
|
Long: `Display the version, commit hash, and build date of gitlocal.`,
|
|
Run: func(cmd *cobra.Command, args []string) {
|
|
version := Version
|
|
commit := Commit
|
|
date := Date
|
|
|
|
// If installed via 'go install', read version from build info
|
|
if version == "dev" {
|
|
if info, ok := debug.ReadBuildInfo(); ok {
|
|
version = info.Main.Version
|
|
|
|
// Extract commit and date from build settings
|
|
for _, setting := range info.Settings {
|
|
switch setting.Key {
|
|
case "vcs.revision":
|
|
if len(setting.Value) > 7 {
|
|
commit = setting.Value[:7]
|
|
} else {
|
|
commit = setting.Value
|
|
}
|
|
case "vcs.time":
|
|
date = setting.Value
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
fmt.Printf("gitlocal version %s\n", version)
|
|
fmt.Printf(" Commit: %s\n", commit)
|
|
fmt.Printf(" Built: %s\n", date)
|
|
},
|
|
}
|
|
|
|
func init() {
|
|
rootCmd.AddCommand(versionCmd)
|
|
}
|