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

相关推荐
ithadoop21 分钟前
go面试知识点分类整理
golang·go
@PHARAOH29 分钟前
HOW - Go 开发入门(二)
开发语言·后端·golang
@PHARAOH1 小时前
HOW - Go 开发入门(四)- ORM 对象关系映射
开发语言·后端·golang
白毛大侠2 小时前
理解 _ “github.com/go-sql-driver/mysql“:Go语言接口编程与init结合的经典案例
golang
keep intensify3 小时前
深度解析TCP三次握手四次挥手
网络·c++·后端·网络协议·tcp/ip·golang
xUxIAOrUIII3 小时前
【Go每日面试题】内存管理
java·开发语言·golang
呆萌很14 小时前
【GO】切片练习题
golang
呆萌很19 小时前
【GO】数组练习题
golang
呆萌很21 小时前
【GO】Map练习题
golang
Geoking.1 天前
【新手向】go语言最新下载及安装配置教程
开发语言·后端·golang