Simplifies the version command and Makefile by removing manual ldflags injection. The application now relies entirely on Go's built-in VCS metadata embedding to extract version, commit, and date information, ensuring accurate reporting across all build methods.
47 lines
1004 B
Go
47 lines
1004 B
Go
package cmd
|
|
|
|
import (
|
|
"fmt"
|
|
"runtime/debug"
|
|
|
|
"github.com/spf13/cobra"
|
|
)
|
|
|
|
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 := "dev"
|
|
commit := "unknown"
|
|
date := "unknown"
|
|
|
|
// Read version from build info (works for both 'go install' and 'go build')
|
|
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)
|
|
}
|