Last active
November 27, 2017 19:02
-
-
Save sczizzo/a4d880d9965ac16813aa4e936baa7d8f to your computer and use it in GitHub Desktop.
Automagically create a go env for each git project
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
unset OLD_GOPATH | |
# Try to find the nearest GOPATH under the given dir | |
func goproj_home() { | |
local dir="${1:-"$PWD"}/" | |
until [[ -z "$dir" ]]; do | |
dir="${dir%/*}" | |
if [[ -d "$dir/src" ]] && [[ -d "$dir/bin" ]] && [[ -d "$dir/pkg" ]]; then | |
echo "$dir" | |
break | |
fi | |
done | |
} | |
# Find the nearest git repo under the given dir | |
func goproj_repo() { | |
local dir="${1:-"$PWD"}/" | |
until [[ -z "$dir" ]]; do | |
dir="${dir%/*}" | |
if [[ -d "$dir/.git" ]]; then | |
echo "$dir" | |
break | |
fi | |
done | |
} | |
# Automagically create a go env for each git repo | |
function goproj_auto() { | |
local gohome="$(goproj_home)" | |
local gorepo="$(goproj_repo)" | |
local goproj="${gorepo#"$gohome/src/"}" | |
local gopath="$HOME/.goproj/$goproj" | |
# Exited repo, restore original go env values | |
if [[ -z "$gohome" ]] || [[ -z "$gorepo" ]]; then | |
[[ -z "$OLD_GOPATH" ]] && return | |
export GOPATH="$OLD_GOPATH" | |
export GOBIN="$GOPATH/bin" | |
export PATH="$OLD_PATH" | |
unset OLD_GOPATH | |
unset OLD_PATH | |
return | |
fi | |
# Same repo, no need to modify go env | |
[[ "$gopath:$gohome" == "$GOPATH" ]] && return | |
# Entering repo, save go env and set new values | |
mkdir -p "$gopath"/{bin,pkg,src} | |
export OLD_PATH="$PATH" | |
export OLD_GOPATH="$GOPATH" | |
export GOPATH="$gopath:$gohome" | |
export GOBIN="$gopath/bin:$gohome/bin" | |
export PATH="$GOBIN:$PATH" | |
} | |
# Execute before each ZSH command | |
if [[ -n "$ZSH_VERSION" ]]; then | |
if [[ ! "$preexec_functions" == *goproj_auto* ]]; then | |
preexec_functions+=("goproj_auto") | |
fi | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment