I need to set Os/Arch variable for each build target. My initial thought was to have a script that would calculate these variables and using hooks to run this script every target.
.goreleaser.yaml
:
builds:
hooks:
pre:
- sh variables.sh
ldflags:
- -s -w -X "main.goversion={{.Env.GOVERSION}}"
- -s -w -X "main.commit={{.Env.GITCOMMIT}}"
- -s -w -X "main.os={{.Env.GOOS}}"
- -s -w -X "main.arch={{.Env.GOARCH}}"
- -s -w -X "main.commit={{.Env.GITCOMMIT}}"
- -s -w -X "main.date={{.Env.BUILDTIME}}"
variables.sh
#!/bin/bash
export GITCOMMIT=${GITCOMMIT:-$(git rev-parse --short HEAD 2> /dev/null || true)}
export BUILDTIME=${BUILDTIME:-$(date -u +"%Y-%m-%dT%H:%M:%SZ")}
export GOOS="${GOOS:-$(go env GOHOSTOS)}"
export GOARCH="${GOARCH:-$(go env GOHOSTARCH)}"
export GOVERSION=$(go version | awk '{print $3;}')
But as the variables are not defined anywhere in the config, so it seems it fails to recognize them, throwing:
release failed after 0.45s error=template: tmpl:1:31: executing "tmpl" at <.Env.GOVERSION>: map has no entry for key "GOVERSION"
Which makes sense. But now I am concerned how do I set target specific variables for each target?
Variables exported in those hooks will not leak to the builder itself.
You could, however, do something like:
and the variables should be available in the
.Env
map on templates.PS: you don't need to set
GOOS
andGOARCH
, GoReleaser does that for you.PPS: build time and commit are available as native template variables/functions