Go 这样设置版本号:我们的项目也可以

人工智能2025-11-05 02:07:06421

 

大家好,样设也我是置版 polarisxu。

项目中,本号特别是项目开源项目,会特别重视项目的样设也版本号。有些项目,置版会把版本号写入源码中,本号每次升级都修改源码号。项目不过这不是样设也特别好的方式。本文通过学习 Go 语言源码的置版处理方式来掌握它,并应用于自己的本号项目中。

本文基于 Go1.17,项目不同版本的样设也实现细节可能有所不同

01 如何获取版本号

在 Go 语言项目中,如果要获取当前 Go 语言版本,置版只需要调用 runtime.Version:

package main import (  "fmt"  "runtime" ) func main() {  fmt.Println("Go Version:",本号 runtime.Version()) } 

02 如何实现的

查看 runtime.Version 的源码:

// buildVersion is the Go trees version string at build time. // // If any GOEXPERIMENTs are set to non-default values, it will include // "X:<GOEXPERIMENT>". // // This is set by the linker. // // This is accessed by "go version <binary>". var buildVersion string // Version returns the Go trees version string. // It is either the commit hash and date at the time of the build or, // when possible, a release tag like "go1.3". func Version() string {  return buildVersion }\ 

根据注释提示,在 Go 仓库源码中,找到 src/cmd/link,这是 Go 链接器的实现。在其中的 internal/ld/main.go 文件找到了如下代码:

buildVersion := buildcfg.Version if goexperiment := buildcfg.GOEXPERIMENT(); goexperiment != "" {   buildVersion += " X:" + goexperiment } addstrdata1(ctxt, "runtime.buildVersion="+buildVersion) 

buildVersion 值从 buildcfg.Version 获取,如果设置了 GOEXPERIMENT(环境变量值),则用该值。服务器租用

着重看 buildcfg.Version 如何得到的:

var (  defaultGOROOT string // set by linker  GOROOT   = envOr("GOROOT", defaultGOROOT)  GOARCH   = envOr("GOARCH", defaultGOARCH)  GOOS     = envOr("GOOS", defaultGOOS)  GO386    = envOr("GO386", defaultGO386)  GOARM    = goarm()  GOMIPS   = gomips()  GOMIPS64 = gomips64()  GOPPC64  = goppc64()  GOWASM   = gowasm()  GO_LDSO  = defaultGO_LDSO  Version  = version ) 

很奇怪,Version 的值,直接用 version 赋值的。但 version 的值是什么?在 src/cmd/dist/buildruntime.go 文件中,有一个函数 mkbuildcfg,用于生成 buildcfg:

// mkbuildcfg writes internal/buildcfg/zbootstrap.go: // // package buildcfg // // const defaultGOROOT = <goroot> // const defaultGO386 = <go386> // ... // const defaultGOOS = runtime.GOOS // const defaultGOARCH = runtime.GOARCH // // The use of runtime.GOOS and runtime.GOARCH makes sure that // a cross-compiled compiler expects to compile for its own target // system. That is, if on a Mac you do: // // GOOS=linux GOARCH=ppc64 go build cmd/compile // // the resulting compiler will default to generating linux/ppc64 object files. // This is more useful than having it default to generating objects for the // original target (in this example, a Mac). func mkbuildcfg(file string) {  var buf bytes.Buffer  fmt.Fprintf(&buf, "// Code generated by go tool dist; DO NOT EDIT.n")  fmt.Fprintln(&buf)  fmt.Fprintf(&buf, "package buildcfgn")  fmt.Fprintln(&buf)  fmt.Fprintf(&buf, "import "runtime"n")  fmt.Fprintln(&buf)  fmt.Fprintf(&buf, "const defaultGO386 = `%s`n", go386)  fmt.Fprintf(&buf, "const defaultGOARM = `%s`n", goarm)  fmt.Fprintf(&buf, "const defaultGOMIPS = `%s`n", gomips)  fmt.Fprintf(&buf, "const defaultGOMIPS64 = `%s`n", gomips64)  fmt.Fprintf(&buf, "const defaultGOPPC64 = `%s`n", goppc64)  fmt.Fprintf(&buf, "const defaultGOEXPERIMENT = `%s`n", goexperiment)  fmt.Fprintf(&buf, "const defaultGO_EXTLINK_ENABLED = `%s`n", goextlinkenabled)  fmt.Fprintf(&buf, "const defaultGO_LDSO = `%s`n", defaultldso)  fmt.Fprintf(&buf, "const version = `%s`n", findgoversion())  fmt.Fprintf(&buf, "const defaultGOOS = runtime.GOOSn")  fmt.Fprintf(&buf, "const defaultGOARCH = runtime.GOARCHn")  writefile(buf.String(), file, writeSkipSame) } 

其中 version 的值是通过 findgoversion() 得到,该函数定义在 src/cmd/dist/build.go 中:(省略了部分细节)

// findgoversion determines the Go version to use in the version string. func findgoversion() string {  // The $GOROOT/VERSION file takes priority, for distributions  // without the source repo.  path := pathf("%s/VERSION", goroot)  if isfile(path) {   ...  }  // The $GOROOT/VERSION.cache file is a cache to avoid invoking  // git every time we run this command. Unlike VERSION, it gets  // deleted by the clean command.  path = pathf("%s/VERSION.cache", goroot)  if isfile(path) {   return chomp(readfile(path))  }  // Show a nicer error message if this isnt a Git repo.  if !isGitRepo() {   fatalf("FAILED: not a Git repo; must put a VERSION file in $GOROOT")  }  // Otherwise, use Git.  // What is the current branch?  branch := chomp(run(goroot, CheckExit, "git", "rev-parse", "--abbrev-ref", "HEAD"))  ...  // Cache version.  writefile(tag, path, 0)  return tag } 

按一下顺序获得 Version(如果前面的获取不到,则依次执行后续获取步骤)

从 $GOROOT/VERSION 获取,在这个文件中放了版本信息,你可以看看你的 Go 安装目录下这个文件的信息 从 $GOROOT/VERSION.cache 获取 根据 Git 仓库生成版本信息,并且生成缓存,这样后续直接读取 $GOROOT/VERSION.cache 获取

03 自己项目

通过前文分析,总结下 Go 版本是如何写入 Go 源码的:

正式版本,通过项目根目录的一个文件得到,比如 $GOROOT/VERSION; 非正式版本,通过 Git 获得版本信息;为了避免编译时重复执行 Git 相关操作,可以生成缓存; 通过环境变量控制版本信息;

最后,可以通过一个 API 把版本信息公开给用户。

对于我们自己的 Go 项目,b2b供应网通过 Git 获得版本信息,可以通过 shell 脚本实现,最后编译 Go 项目时,将版本信息通过 -X 传递进去。

现在我们通过脚本来实现这个功能。

项目代码如下:

// main.go package main import (  "fmt" ) var Version string func main() {  fmt.Println("Version:", Version) } 

现在写一个 shell 脚本,通过该脚本对以上代码进行编译:

#!/bin/sh version="" if [ -f "VERSION" ]; then     version=`cat VERSION` fi if [[ -z $version ]]; then     if [ -d ".git" ]; then         version=`git symbolic-ref HEAD | cut -b 12-`-`git rev-parse HEAD`     else         version="unknown"     fi fi go build -ldflags "-X main.Version=$version" main.go  如果有 VERSION 文件,读取该文件的值作为版本信息; 如果 version 的值是空,判断当前项目是否是 Git 项目。是,则获取版本信息,格式:master-commithash;否则,版本信息设置为 unknown; 通过 go build 的 ldflags 传递版本信息给 main.Version;

这样项目中的 Version 就设置上正确的值了。

04 总结

本文通过对 Go 源码中版本信息的学习研究,掌握了优秀开源项目设置版本信息的做法。最后,演示了如何在自己的项目中用上该技能。

本文没有演示环境变量,一般用的比较少。

云南idc服务商
本文地址:http://www.bzve.cn/news/67d65699276.html
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

全站热门

戴尔电脑开机43错误(探究戴尔电脑开机43错误的根源,提供解决方案)

域名被盗用怎么解决?有什么避免方法?

对二级域名有何看法?有什么二级域名优化技巧?

申请的域名到手后可以退款吗?该怎么做?

探索GalaxyNote3Neo的卓越功能与性能(发现GalaxyNote3Neo的创新之处,了解其先进的技术特性)

域名需要保护吗?投资者所说的域名保护锁是什么?

域名都是怎么买卖的?有什么好的交易方式?

新手对域名有什么疑问吗?有哪些常见问题?

友情链接

滇ICP备2023006006号-39