#!/usr/bin/env bash # Helper script for running commands in a golang build/runtime environment for testing/vendoring/building a go module set -e -o pipefail usage() { cat >&2 < --go-version --go-mod-cache --command "" Runs Required: --module-path The path of the Go module to mount into the container --sdk-image Name of the SDK image to use --go-mod-cache The Go module cache path to mount into the container --command The command to run in the SDK container EOF } required_arg() { local arg="${1:?}" local value="${2}" if [ -z "${value}" ]; then echo "ERROR: ${arg} is required" >&2 exit 2 fi } # shellcheck disable=SC2124 # TODO: improve command interface (#2534) parse_args() { while [ ${#} -gt 0 ] ; do case "${1}" in --help ) usage; exit 0 ;; --module-path ) shift; GO_MODULE_PATH="${1}" ;; --sdk-image ) shift; SDK_IMAGE="${1}" ;; --go-mod-cache ) shift; GO_MOD_CACHE="${1}" ;; --command ) shift; COMMAND="${@:1}" ;; *) ;; esac shift done # Required arguments required_arg "--module-path" "${GO_MODULE_PATH}" required_arg "--sdk-image" "${SDK_IMAGE}" required_arg "--go-mod-cache" "${GO_MOD_CACHE}" required_arg "--command" "${COMMAND}" } # We need to mount the ../.. parent of GO_MOD_CACHE GOPATH=$(cd "${GO_MOD_CACHE}/../.." && pwd) DOCKER_RUN_ARGS="--network=host" parse_args "${@}" # Pass through relevant Go variables, from the config or environment. go_env=( ) for i in GOPROXY GONOPROXY GOPRIVATE GOSUMDB ; do if command -v go >/dev/null 2>&1 ; then govar="$(go env ${i})" if [ -n "${govar}" ] ; then go_env[${#go_env[@]}]="--env=${i}=${govar}" fi elif [ -n "${!i}" ] ; then go_env[${#go_env[@]}]="--env=${i}=${!i}" fi done # Go accepts both lower and uppercase proxy variables, pass both through. proxy_env=( ) for i in http_proxy https_proxy no_proxy HTTP_PROXY HTTPS_PROXY NO_PROXY ; do if [ -n "${!i}" ]; then proxy_env[${#proxy_env[@]}]="--env=$i=${!i}" fi done docker run --rm \ -e GOCACHE='/tmp/.cache' \ -e GOPATH="${GOPATH}" \ "${go_env[@]}" \ "${proxy_env[@]}" \ --user "$(id -u):$(id -g)" \ --security-opt label:disable \ ${DOCKER_RUN_ARGS} \ -v "${GOPATH}":"${GOPATH}" \ -v "${GO_MODULE_PATH}":"${GO_MODULE_PATH}" \ -w "${GO_MODULE_PATH}" \ "${SDK_IMAGE}" \ bash -c "${COMMAND}"