Embedding unique version information in each built artifact
Programming Estimated reading time: ~2 minutes
For troubleshooting purposes it’s useful to embed a unique version info into each artifact you build. The following approach has proven to be very robust when developing e.g. Go programs.
The following build command instructs the Go linker
to embed the version info into the resulting executable
(file make-build.sh
):
#!/bin/bash
set -e
source ./make-common.sh
LDFLAGS="-w -s -X main.VersionInfo=$(get_version_info)"
go build -ldflags "$LDFLAGS" -o $BINARY
The get_version_info
function is implemented
in the make-common.sh
file:
#!/bin/bash
BINARY=fancy-executable
function get_version_info {
local COMMIT_COUNT_TOWARDS_HEAD=$(git rev-list --count HEAD)
local BRANCH_NAME=$(git rev-parse --abbrev-ref HEAD)
local SHORT_COMMIT_HASH=$(git rev-parse --short HEAD)
local DIRTY_LABEL=""
if [ $(git status --porcelain | wc -l) -ne 0 ]; then
DIRTY_LABEL="-dirty"
fi
echo $COMMIT_COUNT_TOWARDS_HEAD-$BRANCH_NAME-$SHORT_COMMIT_HASH$DIRTY_LABEL
}
The version info consists of the following parts
COMMIT_COUNT_TOWARDS_HEAD
: The number of commits leading from the initial commit to the current HEAD. This enables a developer to estimate the age of a version. A high number indicates a young version, whereas a lower number indicates an old version.BRANCH_NAME
: The name of the current branch ;-)SHORT_COMMIT_HASH
: The abbreviated version of the Git commit hash.DIRTY_LABEL
: A label / flag which indicates if the current working copy was dirty during the build.
Examples:
10-master-a22f7da-dirty
10-master-a22f7da
1113-fix-caching-issue-3feab24
You can then access the version info string using the
VersionInfo
variable in e.g. main.go
:
package main
<...>
var VersionInfo string
func main() {
<...>
}
A note about Netcup (advertisement)
Netcup is a German hosting company. Netcup offers inexpensive, yet powerfull web hosting packages, KVM-based root servers or dedicated servers for example. Using a coupon code from my Netcup coupon code web app you can even save more money (6$ on your first purchase, 30% off any KVM-based root server, ...).