Skip to content

Instantly share code, notes, and snippets.

@urbanautomaton
Last active August 29, 2015 14:19
Show Gist options
  • Save urbanautomaton/486c527a46e7eac72fcb to your computer and use it in GitHub Desktop.
Save urbanautomaton/486c527a46e7eac72fcb to your computer and use it in GitHub Desktop.
Set GOPATH and PATH if .goworkspace present
$ echo $GOPATH
$ echo $PATH
/bin:/usr/bin:/usr/local/bin
$ mkdir -p /tmp/some_project
$ touch /tmp/some_project/.goworkspace
$ cd /tmp/some_project
$ echo $GOPATH
/tmp/some_project
$ echo $PATH
/bin:/usr/bin:/usr/local/bin:/tmp/some_project/bin
$ cd ~
$ echo $GOPATH
$ echo $PATH
/bin:/usr/bin:/usr/local/bin
function remove_from_path() {
local readonly remove=$1
local work=:$PATH:
work=${work/:$remove:/:}
work=${work#:}
work=${work%:}
export PATH=$work
}
function go_env_auto() {
local current_dir="$PWD"
until [[ -z "$current_dir" ]]; do
if [[ -f "$current_dir/.goworkspace" ]]; then
[[ "$GOPATH_AUTO" == "$current_dir" ]] && return
GOPATH_AUTO=$current_dir
export GOPATH=$current_dir
export PATH=$PATH:$GOPATH/bin
return
fi
current_dir="${current_dir%/*}"
done
if [[ -n "$GOPATH_AUTO" ]]; then
[[ -n "$GOPATH" ]] && remove_from_path $GOPATH/bin
unset GOPATH_AUTO
unset GOPATH
fi
}
if [[ -n "$ZSH_VERSION" ]]; then
if [[ ! "$preexec_functions" == *go_env_auto* ]]; then
preexec_functions+=("go_env_auto")
fi
elif [[ -n "$BASH_VERSION" ]]; then
trap '[[ "$BASH_COMMAND" != "$PROMPT_COMMAND" ]] && go_env_auto' DEBUG
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment