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

相关推荐
ttwuai2 小时前
GoFrame + Vue3 后台管理系统实战:CRUD、权限和菜单如何少写重复代码
golang
大P哥阿豪2 小时前
Go panic & recover:深入Go语言的异常拯救之道
开发语言·后端·golang·go
雨师@13 小时前
go语言项目--实例化(图书管理)--004
开发语言·后端·golang
想你依然心痛1 天前
AtomCode在后端开发中的实战体验:Go微服务从零搭建
开发语言·微服务·golang
开发小程序的之朴1 天前
认识安企CMS - 系统概述
nginx·golang·系统架构
雨师@1 天前
go语言项目--实例化(图书管理)--005
开发语言·后端·golang
Vect__1 天前
Go 数据结构 slice 深度剖析
开发语言·数据结构·golang
geovindu1 天前
go: Functional Options Pattern
开发语言·后端·设计模式·golang·函数式选项模式’·惯用法模式
techdashen1 天前
把正确性藏进类型里:从 Go 的 io.Reader 到 Rust 的 API 设计
网络·golang·rust
必胜刻1 天前
从零搭建全栈博客系统:Go + Vue 3 + Docker 全流程实战
vue.js·docker·golang