Git tag name as version in Go via Travis-CI

789 views Asked by At

Essentially what I want to do is embed the git tag name (from a github release) to a version string within my GO code.

If I use this code;

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
    }
}

what's the best way of setting "VERSION" in -ldflags '-X main.version VERSION' to $TRAVIS_TAG during a build in Travis-CI,

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

My last effort was to use this make file:

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 ./

with this travis config file;

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

However no matter what variation I try, and I have tried many different flavours of essentially this example, it seems that the binary that ends up in my github release does not contain the tag name. What is observed is the branch and date version string that results from when no version string is set in the make file. I have tried this make file on my dev machine and set environment variable to the expected in Travis and it works as expected. I am also clear that I dont expect this to happen on commit builds but only on releases from github ie when a tag is created.

1

There are 1 answers

0
devfubar On BEST ANSWER

So I fixed this my self.

My problem in the above example was in the Travis file. I seems I needed quotes around my "script" parameter. For completeness here is my new Travis file;

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