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 小时前
Golang面试题库(sync.Map)
开发语言·后端·面试·golang·map·sync.map·expunged
终生成长者6 小时前
Golang cursorrule
开发语言·后端·golang
席万里6 小时前
基于Go和Vue快速开发的博客系统-快速上手Gin框架
vue.js·golang·gin
源代码•宸7 小时前
Golang面试题库(Map)
后端·面试·golang·map·bmap·hmap·nevacuate
只是懒得想了7 小时前
用Go通道实现并发安全队列:从基础到最佳实践
开发语言·数据库·golang·go·并发安全
Fgaoxing18 小时前
Go反射:性能瓶颈与零拷贝优化
性能优化·golang·反射
源代码•宸1 天前
Leetcode—94. 二叉树的中序遍历【简单】
经验分享·后端·算法·leetcode·职场和发展·golang·dfs
想摆烂的不会研究的研究生1 天前
Go后端场景——接口响应慢排查与优化
开发语言·经验分享·后端·golang
梦想画家1 天前
Go并发实战|管道模式(Pipeline)入门到精通:用Goroutine+Channel打造高效数据流
开发语言·golang