forked from go/pgm
68 lines
1.5 KiB
Go
68 lines
1.5 KiB
Go
|
|
// Patial Tech.
|
||
|
|
// Author, Ankit Patial
|
||
|
|
|
||
|
|
package main
|
||
|
|
|
||
|
|
import (
|
||
|
|
"runtime/debug"
|
||
|
|
"strings"
|
||
|
|
)
|
||
|
|
|
||
|
|
// Version returns the version of the pgm CLI tool.
|
||
|
|
// It tries to detect the version in the following order:
|
||
|
|
// 1. Build-time ldflags (set via: go build -ldflags "-X main.version=v1.2.3")
|
||
|
|
// 2. VCS information from build metadata (git tag/commit)
|
||
|
|
// 3. Falls back to "dev" if no version information is available
|
||
|
|
func Version() string {
|
||
|
|
// If version was set at build time via ldflags
|
||
|
|
if version != "" && version != "dev" {
|
||
|
|
return version
|
||
|
|
}
|
||
|
|
|
||
|
|
// Try to get version from build info (Go 1.18+)
|
||
|
|
if info, ok := debug.ReadBuildInfo(); ok {
|
||
|
|
// Check for version in main module
|
||
|
|
if info.Main.Version != "" && info.Main.Version != "(devel)" {
|
||
|
|
return info.Main.Version
|
||
|
|
}
|
||
|
|
|
||
|
|
// Try to extract from VCS information
|
||
|
|
var revision, modified string
|
||
|
|
for _, setting := range info.Settings {
|
||
|
|
switch setting.Key {
|
||
|
|
case "vcs.revision":
|
||
|
|
revision = setting.Value
|
||
|
|
case "vcs.modified":
|
||
|
|
modified = setting.Value
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
// If we have a git revision
|
||
|
|
if revision != "" {
|
||
|
|
// Shorten commit hash to 7 characters
|
||
|
|
if len(revision) > 7 {
|
||
|
|
revision = revision[:7]
|
||
|
|
}
|
||
|
|
|
||
|
|
// Add -dirty suffix if modified
|
||
|
|
if modified == "true" {
|
||
|
|
return "dev-" + revision + "-dirty"
|
||
|
|
}
|
||
|
|
return "dev-" + revision
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
// Fallback to dev
|
||
|
|
return "dev"
|
||
|
|
}
|
||
|
|
|
||
|
|
// GetVersionString returns a formatted version string for display
|
||
|
|
func GetVersionString() string {
|
||
|
|
v := Version()
|
||
|
|
|
||
|
|
// Clean up version string for display
|
||
|
|
v = strings.TrimPrefix(v, "v")
|
||
|
|
|
||
|
|
return "v" + v
|
||
|
|
}
|