使用”go get”命令获取git标签是否可能?

huangapple go评论85阅读模式
英文:

Is it possible to get the git tag with "go get"?

问题

我想在我的Go二进制文件c2go中添加一个--version选项。

我知道传统上这个版本信息会硬编码到二进制文件中,但由于这是一个质量为alpha的软件,并且经常更新,我希望在go get构建可执行文件时(从git标签中)捕获版本信息。

这个可行吗?

英文:

I would like to add a --version option to my Go binary, c2go.

I know traditionally this would be hardcoded into the binary but since it's alpha quality software and it's being updated very often I'd like to capture the version when the go get builds the executable (from the git tag).

Is this possible?

答案1

得分: 2

这并不完全回答你的问题,但我解决类似需求的方式如下。

在我的main包中,我定义了以下变量:

var (
    buildInfo  string
    buildStamp = "未提供构建时间"
    gitHash    = "未提供Git哈希值"
    version    = "未提供版本号"
)

在我的main函数中,我执行以下代码:

if buildInfo != "" {
    parts := strings.Split(buildInfo, "|")
    if len(parts) >= 3 {
        buildStamp = parts[0]
        gitHash = parts[1]
        version = parts[2]
    }
}

然后,我使用以下bash(Linux)shell脚本构建我的应用程序:

#!/bin/sh

cd "${0%/*}"

buildInfo="`date -u '+%Y-%m-%dT%TZ'`|`git describe --always --long`|`git tag | tail -1`"
go build -ldflags "-X main.buildInfo=${buildInfo} -s -w" ./cmd/...

你需要根据Windows和MacOS调整脚本。

希望对你有所帮助。

英文:

This does not exactly answer your question, but the way I solved a similar need is the following.

In my main package, I define the following variables:

var (
    buildInfo  string
    buildStamp = "No BuildStamp provided"
    gitHash    = "No GitHash provided"
    version    = "No Version provided"
)

and in my main function, I execute the following code:

if buildInfo != "" {
    parts := strings.Split(buildInfo, "|")
    if len(parts) >= 3 {
        buildStamp = parts[0]
        gitHash = parts[1]
        version = parts[2]
    }
}

I then build my application with the following bash (Linux) shell script:

#!/bin/sh

cd "${0%/*}"

buildInfo="`date -u '+%Y-%m-%dT%TZ'`|`git describe --always --long`|`git tag | tail -1`"
go build -ldflags "-X main.buildInfo=${buildInfo} -s -w" ./cmd/...

You will need to adjust the script for Windows and MacOS.

Hope that helps.

答案2

得分: 0

不,这是不可能的。(请注意,go get还支持除git之外的其他源代码管理工具)。

英文:

No this is not possible. (Note that go get supports other SCM than git too).

huangapple
  • 本文由 发表于 2017年4月26日 08:24:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/43623007.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定