Git 通过 Travis 在 Go 中将名称标记为版本-CI

Git tag name as version in Go via Travis-CI

基本上我想做的是将 git 标签名称(来自 github 版本)嵌入到我的 GO 代码中的版本字符串中。

如果我使用此代码;

package main
    
import (
    "flag"
    "fmt"
)
    
var version string
    
func main() {

    var verFlag bool
    flag.BoolVar(&verFlag, "version", false, "Returns the version number")

    var confPath string
    flag.StringVar(&confPath, "conf", "conf.yml", "Location on config file")

    flag.Parse()
    
    // if the user wants to see the version
    if verFlag {
        fmt.Printf("%s", version)
        return
    }
}

在 Travis-CI、

构建期间将 -ldflags '-X main.version VERSION' 中的“VERSION”设置为 $TRAVIS_TAG 的最佳方法是什么

Additionally, Travis CI sets environment variables you can use in your build, e.g. to tag the build, or to run post-build deployments.

TRAVIS_TAG: If the current build for a tag, this includes the tag’s name

我最后的努力是使用这个 make 文件:

GOFLAGS ?= $(GOFLAGS:)

TAG := $(VERSION)
ifeq ($(TAG),)
  BRANCH := $(shell git rev-parse --abbrev-ref HEAD)
  DT := $(shell date '+%F::%T')
  VSN := $(BRANCH)-$(DT)
else
  VSN := $(TAG)
endif

ENV := $(shell printenv)

GOFLAGS = -ldflags '-X main.version $(VSN)'

default:
    all

all: 
    test
    install

install:
    get-deps
    @go build $(GOFLAGS) *.go

test:
    @go test $(GOFLAGS) ./...

get-deps:
    @go get ./...

clean:
    @go clean $(GOFLAGS) -i ./

使用这个 travis 配置文件;

language: go
script: make VERSION=$TRAVIS_TAG
go:
- 1.4.1
deploy:
  provider: releases
  api_key:
    secure: reallylongsecurestring
  file: releasebin
  skip_cleanup: true
  on:
    tags: true

然而,无论我尝试什么变体,并且我已经尝试了本质上这个示例的许多不同风格,最终出现在我的 github 版本中的二进制文件似乎不包含标签名称。观察到的是在 make 文件中没有设置版本字符串时产生的分支和日期版本字符串。我已经在我的开发机器上尝试了这个 make 文件,并将环境变量设置为 Travis 中的预期值,它按预期工作。我也很清楚,我不希望这种情况发生在提交版本上,而只会发生在 github 的版本上,即创建标签时。

所以我自己解决了这个问题。

我在上面的例子中的问题是在 Travis 文件中。我似乎需要在我的 "script" 参数周围加上引号。为了完整起见,这是我的新 Travis 文件;

language: go
script: 
 - "make VERSION=$TRAVIS_TAG"
go:
 - 1.4.1
deploy:
  provider: releases
  api_key:
    secure: reallylongsecurestring
  file: releasebin
  skip_cleanup: true
  on:
    tags: true