Commit Hash from debug.ReadBuildInfo()

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.)

相关推荐
FfHUCisI9 小时前
Golang Map 哈希表实现
golang·哈希算法·散列表
源代码•宸10 小时前
前置准备:定时微服务背景和现状
开发语言·经验分享·后端·微服务·云原生·架构·golang
李燚12 小时前
把规则搬回家:三个 BC 的贫血→充血重构实录(第103篇)
golang·agent·ddd·领域驱动设计·eino·deepflux·eino adk
astronautyi14 小时前
Go 运行时内存分配与 GC 位图深度剖析
开发语言·后端·golang
techdashen14 小时前
Go 中如何处理错误
开发语言·后端·golang
FfHUCisI15 小时前
Golang 切片扩容策略
开发语言·数据库·golang
名字还没想好☜15 小时前
Go 1.21 context.WithoutCancel 实战:父 context 取消了,收尾任务还要继续跑
开发语言·后端·golang·go
名字还没想好☜19 小时前
Go 用 -race 抓数据竞争:一个偶发崩溃的排查、原理与修复
开发语言·后端·golang·go
专注仿真19 小时前
Go操作Kubernetes API
贪心算法·golang·kubernetes
xcLeigh1 天前
Go入门:整数类型的溢出与安全边界
java·安全·golang