For some CLI tools I use regularly I noticed that when I run the version flag get some version info that includes a git commit hash or a git tag to the command line:

1
2
3
> kubectl version
Client Version: version.Info{Major:"1", Minor:"16", GitVersion:"v1.16.3", GitCommit:"b3cbbae08ec52a7fc73d334838e18d17e8512749", GitTreeState:"clean", BuildDate:"2019-11-13T11:23:11Z", GoVersion:"go1.12.12", Compiler:"gc", Platform:"linux/amd64"}
Server Version: version.Info{Major:"1", Minor:"16", GitVersion:"v1.16.2", GitCommit:"c97fe5036ef3df2967d086711e6c0c405941e14b", GitTreeState:"clean", BuildDate:"2019-10-15T19:09:08Z", GoVersion:"go1.12.10", Compiler:"gc", Platform:"linux/amd64"}

I discovered a nice way to do this for go programs. You can specify a value for a global variable at build time using the -ldflags "-X" flag.

For this program:

1
2
3
4
5
6
7
8
9
package main

import "fmt"

var Version = "dev"

func main(){
  fmt.Printf("I'm version <%s>", Version)
}

You can use this one liner that builds your go program while setting the Version variable to the sha hash of the latest commit.

1
2
3
> go build -ldflags "-X main.Version=$(git rev-parse HEAD)" -o hello_app main.go
> hello_app
I'm version ba83f7c418c669f705a3cce0c58a1f9129a3de14

Note that you have to specify the full path of the package in your project, for example:

1
2
3
4
5
6
7
# Your project looks like
# - main.go <- module `github.com/myrepo/test`
# - version <- `github.com/myrepo/test/version`
#   - sha.go <- has `var Version = "dev"`
> go build -ldflags "-X github.com/myrepo/test/version.Version=$(git rev-parse HEAD)" -o hello_app main.go
> hello_app
I'm version ba83f7c418c669f705a3cce0c58a1f9129a3de14