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

相关推荐
会编程的土豆5 小时前
洛谷题单入门1 顺序结构
数据结构·算法·golang
亿牛云爬虫专家13 小时前
Go爬虫进阶:如何优雅地在Colly框架中实现无缝代理切换?
爬虫·中间件·golang·爬虫代理·colly框架·代理切换·api提取
会编程的土豆15 小时前
洛谷题单 入门1 顺序结构(go语言)
开发语言·后端·golang·洛谷
jieyucx15 小时前
Go 语言 switch 条件语句详解
开发语言·c++·golang
初心未改HD15 小时前
Go语言defer机制深度解析
开发语言·golang
不甘先生18 小时前
Go 包引用架构指南:从 internal 隔离到破解循环依赖的实战手册
架构·golang
初心未改HD19 小时前
Go语言接口与nil深度解析
开发语言·golang
Achou.Wang19 小时前
go语言并发编程
java·开发语言·golang
jieyucx19 小时前
Go 语言函数入门:定义、参数、返回值
c++·算法·golang·入门·函数
XMYX-019 小时前
20 - Go 互斥锁:Mutex 与并发安全
开发语言·golang