Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save inancgumus/6f3fc940b88036476dd04ab0c184b066 to your computer and use it in GitHub Desktop.
Save inancgumus/6f3fc940b88036476dd04ab0c184b066 to your computer and use it in GitHub Desktop.
Copypasta for easy versioning for your Go binaries

Golang Binary Versioning Trick

To use, place the code in version_trick.go in your project. Don't forget to change the namespace to match yours to the actual name of your package.

In addition to version_trick.go, there's a makefile-snippet, that includes the secret sauce for making this trick work. Be sure to change the package name there as well.

Enjoy!

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

# be sure to change `modcloth-labs/mithril` to your namespace
REV_VAR := github.com/modcloth-labs/mithril.RevString
VERSION_VAR := github.com/modcloth-labs/mithril.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)"
# then, change your `go install` statement from something like this:
go get -x $(TARGETS)
go install -x $(TARGETS)
# to something like this:
go get -x $(GOBUILD_VERSION_ARGS) $(TARGETS)
go install -x $(GOBUILD_VERSION_ARGS) $(TARGETS)
package mithril
import (
"fmt"
"os"
"path"
)
var (
VersionString string
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() //you're probably already doing this somewhere
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)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment