Skip to content

Instantly share code, notes, and snippets.

@meatballhat
Forked from rafecolton/Golang-binary-versioning.md
Last active December 20, 2015 04:19
Show Gist options
  • Save meatballhat/6070307 to your computer and use it in GitHub Desktop.
Save meatballhat/6070307 to your computer and use it in GitHub Desktop.

Golang Binary Versioning Trick

To use, adapt the code in main.go for use in your project.

In addition to main.go, there's an example Makefile that includes the secret sauce for making this trick work. If you're already using package main for everything, the code should work as-is, but you'll have to adapt it for more complex (read: sane) code layouts.

Enjoy!

P.S. Special thanks to @meatballhat by way of @syscomet for showing me this trick!

package main
import (
"flag"
"fmt"
"os"
"path"
)
var (
// VersionString is the variable set via -ldflags that contains the
// string produced by `git describe`
VersionString string
// RevString is the variable set via -ldflags that contains the
// current git revision
RevString string
versionFlag = false
revFlag = false
)
func init() {
flag.BoolVar(&versionFlag, "version", false, "Print version and exit")
flag.BoolVar(&revFlag, "rev", false, "Print git revision and exit")
}
func main() {
flag.Parse()
if versionFlag {
progName := path.Base(os.Args[0])
if VersionString == "" {
VersionString = "<unknown>"
}
fmt.Printf("%s %s\n", progName, VersionString)
os.Exit(0)
}
if revFlag {
if RevString == "" {
RevString = "<unknown>"
}
fmt.Println(RevString)
os.Exit(0)
}
}
REV_VAR := main.RevString
VERSION_VAR := main.VersionString
REPO_VERSION := $(shell git describe --always --dirty --tags)
REPO_REV := $(shell git rev-parse --sq HEAD)
GOBUILD_VERSION_ARGS := -ldflags "-X $(REV_VAR) $(REPO_REV) -X $(VERSION_VAR) $(REPO_VERSION)"
build:
go build -x $(GOBUILD_VERSION_ARGS) -o version-trick .
@rafecolton
Copy link

Have you been able to get main.VersionString to work in a namespaced project (i.e. github.com/modcloth-labs/mithril/main.VersionString)? If so, what's the magical incantation?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment