Skip to content

Instantly share code, notes, and snippets.

@jtagcat
Last active April 26, 2022 09:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jtagcat/189b2fd239687ab700f54faa46907df4 to your computer and use it in GitHub Desktop.
Save jtagcat/189b2fd239687ab700f54faa46907df4 to your computer and use it in GitHub Desktop.
[NON-FUNCTIONAL] Get golang version from go module
# see https://github.com/jtagcat/dotfiles/blob/main/scripts/template/gobuild.Dockerfile
# stuck on https://github.com/moby/moby/issues/29110
FROM alpine
COPY getGoModVersion.sh .
COPY go.mod .
ENVCMD gover ./dockerGoMod.sh | sed -n '1 p'
FROM golang:$ver AS builder
# ...
ENVCMD basename dockerGoMod.sh | sed -n '3 p'
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o $basename
ENVCMD module dockerGoMod.sh | sed -n '2 p'
LABEL org.opencontainers.image.source="https://$module"
# ...
COPY --from=builder /wd/$basename ./
CMD ["./$basename"]
#!/usr/bin/env bash
set -eo pipefail
file="go.mod"
if [[ -n "$1" ]]; then
file="$1"
fi
if [[ ! -r "$file" ]]; then
echo "error: file '${file}' not readable"
exit 1
fi
matches=0
while read -r line; do
if [[ "$line" =~ ^go[[:space:]].* ]]; then
# begins with "go "
v="$(xargs <<< "${line:3}")"
if [[ "$matches" != 0 ]]; then
>&2 echo "error: multiple versions found, 2nd is '${v}'"
exit 1
fi
echo "${v}"
((matches++))
fi
done <go.mod
if [[ "$matches" == 0 ]]; then
>&2 echo "error: no version found"
exit 1
fi
matches=0
while read -r line; do
if [[ "$line" =~ ^module[[:space:]].* ]]; then
# begins with "module "
v="$(xargs <<< "${line:7}")"
if [[ "$matches" != 0 ]]; then
>&2 echo "error: multiple module names found, 2nd is '${v}'"
exit 1
fi
echo "${v}"
basename "${v}"
((matches++))
fi
done <go.mod
if [[ "$matches" == 0 ]]; then
>&2 echo "error: no module name found"
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment