Skip to content

Instantly share code, notes, and snippets.

@taikedz
Last active October 17, 2023 10:40
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 taikedz/d158cb8adc6dfe0c434c02eceb0d10ad to your computer and use it in GitHub Desktop.
Save taikedz/d158cb8adc6dfe0c434c02eceb0d10ad to your computer and use it in GitHub Desktop.
GoEnv - python virtualenv-like way to set GOPATH
#!/usr/bin/env bash
# Run `goenv ./env-dir` to create an isolated dependencies dir
# Source the resulting file to activate it in a local shell session
# . env-dir/go-activate
# This sets GOPATH and adds a PATH entry to the environment
# Run `go-deactivate` to deactivate it.
if [[ -z "$1" ]]; then
echo "No name specified"
exit 1
fi
TARGET="$1"; shift
TARGET_F="$(readlink -f "$TARGET")"
TARGET_N="$(basename "$TARGET_F")"
mkdir "$TARGET_F"
cat <<EOF > "$TARGET/go-activate"
if env | grep GOENV_OLD -q ; then
echo "Already activated"
else
GOENV_OLD_PS1="\$PS1"
GOENV_OLD_PATH="\$PATH"
export PS1="(goenv:$TARGET_N) \$PS1"
export GOPATH="$TARGET_F"
export PATH="$TARGET_F/bin:\$PATH"
go-deactivate() {
export PS1="\$OLD_PS1"
unset GOPATH
export PATH="\$GOENV_OLD_PATH"
unset GOENV_OLD_PS1
unset GOENV_OLD_PATH
unset go-deactivate
}
fi
EOF
echo "Created GOPATH directory at $TARGET . Source '$TARGET/go-activate' to load it."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment