Skip to content

Instantly share code, notes, and snippets.

@rsperl
Last active July 25, 2022 12:43
Show Gist options
  • Save rsperl/3e859b585ee50800a8693e5d2e2f9859 to your computer and use it in GitHub Desktop.
Save rsperl/3e859b585ee50800a8693e5d2e2f9859 to your computer and use it in GitHub Desktop.
set variables at build time #go
#!/usr/bin/env bash
BUILD_TIME="$(date --iso-8601=seconds)"
COMMIT_SHA="$(git rev-parse HEAD 2>/dev/null && true)"
# or
# git rev-parse --short=8 HEAD 2>/dev/null && true
COMMIT_SHORT_SHA="${COMMIT_SHA:0:8}"
BRANCH_NAME=$(git rev-parse --abbrev-ref HEAD && true)
COMMIT_TAG="$(git tag --points-at $COMMIT_SHA && true)"
BUILD_HOSTNAME=$(hostname)
BUILD_USERNAME=$USER
# Reference the build-time variables as <package>.<Varname>
go build -o main \
-ldflags="-X main.Version=$COMMIT_TAG \
-X main.BuildCommit=$COMMIT_SHA \
-X main.BuildShortCommit=$COMMIT_SHORT_SHA \
-X main.BranchName=$BRANCH_NAME \
-X main.BuildTime=$BUILD_TIME \
-X main.BuildHostname=$BUILD_HOSTNAME \
-X main.BuildUsername=$BUILD_USERNAME" \
.
package main
import (
"fmt"
"strings"
"log"
)
// Declare public variables to be set at build-time
var (
BuildTime string
BuildCommit string
BuildShortCommit string
BuildBranch string
BuildHostname string
BuildUsername string
Version string
)
// GetBuildInfo returns a list of strings for either printing or logging
func GetBuildInfo() []string {
longLine := strings.Replace(fmt.Sprintf("+%61s+", ""), " ", "-", 61)
return []string{
longLine,
fmt.Sprintf("| Version: %-41s |", Version),
fmt.Sprintf("| BuildTime: %-41s |", BuildTime),
fmt.Sprintf("| BuildCommit: %-41s |", BuildCommit),
fmt.Sprintf("| BuildShortCommit: %-41s |", BuildShortCommit),
fmt.Sprintf("| BuildBranch: %-41s |", BuildBranch),
fmt.Sprintf("| BuildHostname: %-41s |", BuildHostname),
fmt.Sprintf("| BuildUsername: %-41s |", BuildUsername),
fmt.Sprintf(longLine),
}
}
func main() {
for _, line := range GetBuildInfo() {
log.Println(line)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment