#So, how to add a version number to the project? Many people should have used hard coding, that is, writing the version number directly into the source code or configuration file, and modifying the version number every time the function is upgraded. This method is obviously feasible, but it is also error-prone. First, it is easy to forget to update the version number when releasing a version. Second, when multiple branch codes are merged, there may be confusion.
The following will bring you a different management plan.
go linker Linker is a tool for assembling binary files. When we execute the go build command, we can pass <span style="font-size: 15px;">--ldflags</span>
Flags set linker parameters. Use the following statement to view the linker optional parameters.
go build --ldflags="--help"
There are many parameters, but what we are interested in is<span style="font-size: 15px;">-X</span>
$ go build --ldflags="--help" usage: link [options] main.o ... -X definition add string value definition of the form importpath.name=value ...
<span style="font-size: 15px;">-X</span>
parameter, specify importpath.name=value, used to modify the variable value. Among them, importpath represents the package import path, name is the variable name in the program, and value represents the variable value we want to set.
下面,我们通过示例项目来具体感受一下。
$ mkdir versionDemo $ cd versionDemo/ $ go mod init versiondemo go: creating new go.mod: module versiondemo $ touch main.go
在 main 函数中,我们打印 version 值。
package main import ( "fmt" ) var ( version = "0.0.1" ) func main() { fmt.Println("version: ", version) }
如果正常编译执行程序,将得到以下结果
$ go build -o main && ./main version: 0.0.1
此时,我们指定 --ldflags 的 -X 参数重新编译执行
$ go build -o main --ldflags="-X 'main.version=client-0.0.2'" && ./main version: client-0.0.2
可以看到 version 参数值已经被改变。
开发中需要使用 git 工具,本文讨论的版本管理,也经常与 git tag 挂钩。那其实有更酷的操作:我们可以在构建期间,通过 git commit 信息自动填充版本号。
我们基于上文项目目录,添加 git commit 信息。
$ git init $ git add . $ git commit -m "initial commit"
通过以下命令,可拿到 git commit 的 hash 值
$ git rev-parse HEAD 46dab0ddb6ba20445c2c1f047575e25d3aad1a27
该值较长,我们可以添加 --short 选项获取短 hash 值。
$ git rev-parse --short HEAD 46dab0d
此时,通过指定 --ldflags 的 -X 参数,将 version 值替换成 git commit 的哈希值。这样,我们成功地将项目版本与 git 信息绑定在了一起。
$ go build -o main --ldflags="-X 'main.version=$(git rev-parse --short HEAD)'" && ./main version: 46dab0d
本文介绍了一种如何通过 ldflags -X 变量传递的方式。使用这种方式我们可以在构建时轻松设定一些元信息,例如本文示例的程序版本信息。而这种构建的动作不应该手动去执行,而是放入到 CI/CD 流程中,让整个过程变得更加丝滑。
The above is the detailed content of A different Go project version number management solution. For more information, please follow other related articles on the PHP Chinese website!