From b34f8bcd041974b64d53345e06b2d6dc833b35fe Mon Sep 17 00:00:00 2001 From: Loic Nageleisen Date: Mon, 17 Nov 2014 16:09:12 +0100 Subject: [PATCH] proper automatic go workspace path --- shell/go | 50 +++++++++++++++++++++++++++++++++----------------- zsh/rc | 1 + 2 files changed, 34 insertions(+), 17 deletions(-) diff --git a/shell/go b/shell/go index 0b34b7a..2d1d42e 100644 --- a/shell/go +++ b/shell/go @@ -1,5 +1,3 @@ -go_commands=(go vim) - _go-installed() { which go > /dev/null 2>&1 } @@ -7,35 +5,53 @@ _go-installed() { _within-go-project() { local check_dir=$PWD local next_check_dir=${check_dir%/*} + while [ "$next_check_dir" != "" ]; do if [ -f "$check_dir/.gopath" ]; then echo "$check_dir" return fi + check_dir="$next_check_dir" next_check_dir=${check_dir%/*} done + false } -_run-with-gopath() { +_append-go-path() { + local bin_path="$*/bin" + + [[ $PATH == *:"$*"* ]] || export PATH="$PATH:$bin_path" +} + +_strip-go-path() { + local bin_path="$*/bin" + + [[ $PATH == *":$bin_path"* ]] && export PATH=$( + echo -n "$PATH" | + awk -v RS=: -v ORS=: '$0=="'"$bin_path"'" {next} {print}' | + sed 's/:$//' + ) +} + +_set-gopath() { + export GOPATH="$*" +} + +_unset-gopath() { + unset GOPATH +} + +_gopath() { local go_path if _go-installed && go_path=$(_within-go-project); then - env PATH="$PATH:$go_path/bin" GOPATH="$go_path" "$@" - else - "$@" + _set-gopath "$go_path" + _append-go-path "$GOPATH" + elif [[ -n $GOPATH ]]; then + _strip-go-path "$GOPATH" + _unset-gopath fi } -for cmd in "${go_commands[@]}"; do - eval "function gopath_$cmd () { _run-with-gopath $cmd \$@; }" - alias $cmd=gopath_$cmd - - if [[ -n $ZSH_VERSION ]]; then - if which _$cmd > /dev/null 2>&1; then - compdef _$cmd gopath_$cmd=$cmd - fi - fi -done - # vim: ft=sh diff --git a/zsh/rc b/zsh/rc index 0ada628..2b320cf 100644 --- a/zsh/rc +++ b/zsh/rc @@ -32,6 +32,7 @@ preexec() { chpwd() { __git_ps1_gitdir + _gopath } chpwd