Commit Hash from debug.ReadBuildInfo()
(Jin Qing's Column, Jan., 2026)
To extract the vcs.revision from debug.ReadBuildInfo() in Go,
you need to iterate through the Settings slice in the BuildInfo struct and check for the key "vcs.revision".
This feature is available for binaries built with Go 1.18 or later, provided Git (or another supported VCS) was present during the build.
Here is a function that retrieves the vcs.revision string:
go
package main
import (
"fmt"
"runtime/debug"
)
// GetVCSRecord retrieves the value for a given VCS key, e.g., "vcs.revision"
func GetVCSRecord(key string) string {
if info, ok := debug.ReadBuildInfo(); ok {
for _, setting := range info.Settings {
if setting.Key == key {
return setting.Value
}
}
}
return "" // Return empty string if not found or build info unavailable
}
func main() {
commitHash := GetVCSRecord("vcs.revision")
if commitHash != "" {
fmt.Printf("VCS Revision: %s\n", commitHash)
} else {
fmt.Println("VCS Revision not available in build info.")
}
}
Output example:
VCS Revision: 70a1e4c86600385257a9c0b4f4c1899fe6edde8b
How to Use
- Ensure Go Version: The code requires Go 1.18 or newer.
- Build within a VCS repository: You must run go build from within a Git (or Mercurial, Fossil, Bazaar) repository for the information to be embedded.
- Ensure VCS tool is present: The go build command needs access to the VCS tool (e.g., git) during the build process to populate the information.
Available VCS Keys
Besides "vcs.revision", other useful keys in info.Settings include:
- "vcs": The version control system used (e.g., "git").
- "vcs.time": The commit timestamp (e.g., "2022-01-15T16:47:19Z").
- "vcs.modified": A boolean indicating if the source was modified since the last commit ("true" or "false").
(AI generated.)