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

相关推荐
geovindu12 小时前
go: Semaphore Pattern
开发语言·后端·设计模式·golang·企业级信号量模式
dusk_star16 小时前
go语言--笔记--封装、组合(继承)
笔记·golang
姚不倒17 小时前
Go 语言基础入门:从零到实战,一篇文章掌握核心语法
云原生·golang
XMYX-020 小时前
33 - Go 文本模板 template:从入门到原理深挖
golang·正则表达式
知彼解己1 天前
从后端角度理解 AI Agent:理论 + Go 实战(附 MCP 服务器实现)
java·golang·ai编程
云川之下1 天前
【go】建工程、初始化、module/package/import语法
golang·初始化
XMYX-01 天前
32 - Go 正则表达式:从匹配字符串到理解 RE2 引擎
golang·正则表达式
存在morning1 天前
【GO语言开发实践】二 GO 并发快速上手
大数据·开发语言·golang
geovindu2 天前
go: Read-Write Lock Pattern
开发语言·后端·设计模式·golang·读写锁模式
知彼解己2 天前
Go 开发环境 安装
后端·golang