Go 這樣設(shè)置版本號:我們的項(xiàng)目也可以
大家好,我是 polarisxu。
項(xiàng)目中,特別是開源項(xiàng)目,會特別重視項(xiàng)目的版本號。有些項(xiàng)目,會把版本號寫入源碼中,每次升級都修改源碼號。不過這不是特別好的方式。本文通過學(xué)習(xí) Go 語言源碼的處理方式來掌握它,并應(yīng)用于自己的項(xiàng)目中。
本文基于 Go1.17,不同版本的實(shí)現(xiàn)細(xì)節(jié)可能有所不同
01 如何獲取版本號
在 Go 語言項(xiàng)目中,如果要獲取當(dāng)前 Go 語言版本,只需要調(diào)用 runtime.Version:
- package main
- import (
- "fmt"
- "runtime"
- )
- func main() {
- fmt.Println("Go Version:", runtime.Version())
- }
02 如何實(shí)現(xiàn)的
查看 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
- }\
根據(jù)注釋提示,在 Go 倉庫源碼中,找到 src/cmd/link,這是 Go 鏈接器的實(shí)現(xiàn)。在其中的 internal/ld/main.go 文件找到了如下代碼:
- buildVersion := buildcfg.Version
- if goexperiment := buildcfg.GOEXPERIMENT(); goexperiment != "" {
- buildVersion += " X:" + goexperiment
- }
- addstrdata1(ctxt, "runtime.buildVersion="+buildVersion)
buildVersion 值從 buildcfg.Version 獲取,如果設(shè)置了 GOEXPERIMENT(環(huán)境變量值),則用該值。
著重看 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 文件中,有一個(gè)函數(shù) 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() 得到,該函數(shù)定義在 src/cmd/dist/build.go 中:(省略了部分細(xì)節(jié))
- // 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(如果前面的獲取不到,則依次執(zhí)行后續(xù)獲取步驟)
- 從 $GOROOT/VERSION 獲取,在這個(gè)文件中放了版本信息,你可以看看你的 Go 安裝目錄下這個(gè)文件的信息
- 從 $GOROOT/VERSION.cache 獲取
- 根據(jù) Git 倉庫生成版本信息,并且生成緩存,這樣后續(xù)直接讀取 $GOROOT/VERSION.cache 獲取
03 自己項(xiàng)目
通過前文分析,總結(jié)下 Go 版本是如何寫入 Go 源碼的:
- 正式版本,通過項(xiàng)目根目錄的一個(gè)文件得到,比如 $GOROOT/VERSION;
- 非正式版本,通過 Git 獲得版本信息;為了避免編譯時(shí)重復(fù)執(zhí)行 Git 相關(guān)操作,可以生成緩存;
- 通過環(huán)境變量控制版本信息;
最后,可以通過一個(gè) API 把版本信息公開給用戶。
對于我們自己的 Go 項(xiàng)目,通過 Git 獲得版本信息,可以通過 shell 腳本實(shí)現(xiàn),最后編譯 Go 項(xiàng)目時(shí),將版本信息通過 -X 傳遞進(jìn)去。
現(xiàn)在我們通過腳本來實(shí)現(xiàn)這個(gè)功能。
項(xiàng)目代碼如下:
- // main.go
- package main
- import (
- "fmt"
- )
- var Version string
- func main() {
- fmt.Println("Version:", Version)
- }
現(xiàn)在寫一個(gè) shell 腳本,通過該腳本對以上代碼進(jìn)行編譯:
- #!/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 的值是空,判斷當(dāng)前項(xiàng)目是否是 Git 項(xiàng)目。是,則獲取版本信息,格式:master-commithash;否則,版本信息設(shè)置為 unknown;
- 通過 go build 的 ldflags 傳遞版本信息給 main.Version;
這樣項(xiàng)目中的 Version 就設(shè)置上正確的值了。
04 總結(jié)
本文通過對 Go 源碼中版本信息的學(xué)習(xí)研究,掌握了優(yōu)秀開源項(xiàng)目設(shè)置版本信息的做法。最后,演示了如何在自己的項(xiàng)目中用上該技能。
本文沒有演示環(huán)境變量,一般用的比較少。