Golang-如何从代码内部显示模块版本 [英] Golang - How to display modules version from inside of code
问题描述
我正在编写两个二进制文件,并且它们两个都使用两个库(我们可以将它们称为libA和libB).
I'm writing two binaries, and both of them use two libraries (we can call them libA and libB).
每个库都位于专用的git repo中,带有git-tags来声明版本.例如,libA的版本为v1.0.9,而libB的版本为v0.0.12.
Each lib is in a dedicated git repo, with git-tags to declare versions. For example, libA is at v1.0.9 and libB is v0.0.12.
两个二进制文件都具有CLI标志,我想添加一个调试标志来显示类似的lib版本:
Both binaries have CLI flags, and I would like to add a debug flag to display lib versions like that:
> ./prog -d
Used libraries:
- libA, v1.0.9
- libB, v0.0.12
我不知道该怎么做.
我看到的从外部"设置变量的唯一方法是使用ldflags(例如, go build -ldflags =-X'main.Version = v1.0.0'"
).但是这种方式似乎不具有可扩展性,如何添加libC?这也意味着管理标签两次,一次用于git,一次在goreleaser.yml或makefile中.
The only way I see to set variable from "outside" is to use ldflags (go build -ldflags="-X 'main.Version=v1.0.0'"
for example). But this way don't seems scalable, how to add a libC? It also imply to manage tags two times, one time for git, and one time in goreleaser.yml or makefile.
您能帮我找到解决方法吗?
Can you help me to find a solution?
推荐答案
Go工具在可执行二进制文件中包含模块和依赖项信息.您可以使用 runtime/debug.ReadBuildInfo()
获得它.它为您返回依赖项列表,包括模块路径和版本.每个模块/依赖项均由类型为 debug.Module
的值描述.包含以下信息:
The Go tool includes module and dependency information in the executable binary. You may use runtime/debug.ReadBuildInfo()
to acquire it. It returns you a list of dependencies, including module path and version. Each module / dependency is described by a value of type debug.Module
which contains these info:
type Module struct {
Path string // module path
Version string // module version
Sum string // checksum
Replace *Module // replaced by this module
}
例如:
package main
import (
"fmt"
"log"
"runtime/debug"
"github.com/icza/bitio"
)
func main() {
_ = bitio.NewReader
bi, ok := debug.ReadBuildInfo()
if !ok {
log.Printf("Failed to read build info")
return
}
for _, dep := range bi.Deps {
fmt.Printf("Dep: %+v\n", dep)
}
}
此输出(在游乐场上尝试):
Dep: &{Path:github.com/icza/bitio Version:v1.0.0 Sum:h1:squ/m1SHyFeCA6+6Gyol1AxV9nmPPlJFT8c2vKdj3U8= Replace:<nil>}
这篇关于Golang-如何从代码内部显示模块版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!