我想将当前的 git 修订号添加到构建的二进制文件中,go build
以便我可以做一些事情,例如./mybinary --revision
查看它是从哪个修订版构建的(通常用于稍后部署后的故障排除)。
显然,我不能将修订号放入源代码中,因为这会用新版本更改源代码。
我想知道是否有其他方法可以做到这一点?
或者你认为这只是一个坏主意?如果是这样,在构建的二进制文件与其源版本之间建立关系的推荐方法是什么?
对于分布式版本控制系统,版本号似乎不是一个好主意。
我想将当前的 git 修订号添加到构建的二进制文件中,go build
以便我可以做一些事情,例如./mybinary --revision
查看它是从哪个修订版构建的(通常用于稍后部署后的故障排除)。
显然,我不能将修订号放入源代码中,因为这会用新版本更改源代码。
我想知道是否有其他方法可以做到这一点?
或者你认为这只是一个坏主意?如果是这样,在构建的二进制文件与其源版本之间建立关系的推荐方法是什么?
对于分布式版本控制系统,版本号似乎不是一个好主意。
如果您可以将 git 修订版放入 $VERSION 并version
在您的主包中有一个名为(类型字符串)的变量,您可以在构建期间使用以下命令设置它:
#!/bin/sh
VERSION=`git rev-parse --short HEAD`
go build -ldflags "-X main.version=$VERSION" myfile.go
对于Git 代码中的所有版本和任何版本,获取任何变更集的标识字符串的最明显方法--revision
是(而我留给您在选项上显示此字符串的任务)是
我会version.go
用一个文件创建一个文件,var version string
然后在调用之前处理go build
它并在之后重置它。换句话说,go 不支持任何类型的代码生成,因此您需要依赖外部的东西来执行此操作。
ldflags
从 Go 1.18(2021 年第 4 季度/2022 年第 1 季度)开始,正常流程不应再涉及任何.
该
go
命令现在将版本控制信息嵌入到二进制文件中,包括当前签出的修订版和指示是否存在已编辑或未跟踪文件的标志。Version control information is embedded if the
go
command is invoked in a directory within a Git or Mercurial repository, and themain
package and its containingmain
module are in the same repository.
This information may be omitted using the flag-buildvcs=false
.Additionally, the
go
command embeds information about:
- the build including build and tool tags (set with
-tags
),- compiler,
- assembler, and
- linker flags (like
-gcflags
),- whether
cgo
was enabled, and if it was, the values of thecgo
environment variables (likeCGO_CFLAGS
).This information may be omitted using the flag
-buildinfo=false
.Both VCS and build information may be read together with module information using:
go version -m file
orruntime/debug.ReadBuildInfo
(for the currently running binary) or- the new
debug/buildinfo
package.
CL 373875 adds
- The
BuildInfo
struct has new fields with additional information about how the binary was built.- The new
GoVersion
field holds the version of Go used to build the binary.- The new
Settings
field is a slice ofBuildSettings
structs holding key/value pairs describing the build.
您通常会使用标签(在其他版本控制系统中也称为标签)来记录构成特定构建的文件。 http://git-scm.com/book/en/Git-Basics-Tagging。我通常制作包含版本和构建日期的标签。例如 v1.2_29Mar2013。如果我有几个可以从同一个代码库构建的产品,我将包含一些东西来识别哪个产品。