Go 這樣設置版本號:我們的項目也可以
大家好,我是 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 tree's 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 tree's 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 buildcfg\n")
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.GOOS\n")
fmt.Fprintf(&buf, "const defaultGOARCH = runtime.GOARCH\n")
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 isn't 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(如果前面的獲取不到,則依次執行後續獲取步驟)
03 自己項目
通過前文分析,總結下 Go 版本是如何寫入 Go 源碼的:
-
正式版本,通過項目根目錄的一個文件得到,比如
$GOROOT/VERSION
; -
非正式版本,通過 Git 獲得版本信息;爲了避免編譯時重複執行 Git 相關操作,可以生成緩存;
-
通過環境變量控制版本信息;
最後,可以通過一個 API 把版本信息公開給用戶。
對於我們自己的 Go 項目,通過 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 源碼中版本信息的學習研究,掌握了優秀開源項目設置版本信息的做法。最後,演示瞭如何在自己的項目中用上該技能。
本文沒有演示環境變量,一般用的比較少。
我是 polarisxu,北大碩士畢業,曾在 360 等知名互聯網公司工作,10 多年技術研發與架構經驗!2012 年接觸 Go 語言並創建了 Go 語言中文網!著有《Go 語言編程之旅》、開源圖書《Go 語言標準庫》等。
堅持輸出技術(包括 Go、Rust 等技術)、職場心得和創業感悟!歡迎關注「polarisxu」一起成長!也歡迎加我微信好友交流:gopherstudio
本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源:https://mp.weixin.qq.com/s/jPbiihVb0b9EMdSMySTkgQ