Commit dd9f5cd8 authored by Dom Sekotill's avatar Dom Sekotill
Browse files

Add a non-broken virtualenv cd-plugin

parent cba5affe
Loading
Loading
Loading
Loading
+48 −0
Original line number Diff line number Diff line
function workon_cwd {
	[[ -n "$DISABLE_WORKON_CWD" ]] && return
	local DISABLE_WORKON_CWD=1  # recursion protection

	local ENV_ROOT PROJECT_ROOT="${PWD:A}"
	until [[ "$PROJECT_ROOT" -ef / ]]; do
		[[ -e "$PROJECT_ROOT/.venv" && -z "$ENV_ROOT" ]] &&
			ENV_ROOT="$PROJECT_ROOT/.venv"
		[[ -d "$PROJECT_ROOT/.git" ]] && break
		PROJECT_ROOT="${PROJECT_ROOT:h}"
	done

	if [[ -z "$ENV_ROOT" ]]; then
		# Try virtualenvwrapper with $(basename $PROJECT_ROOT)
		ENV_NAME=$(basename "$PROJECT_ROOT")
		ENV_ROOT="$WORKON_HOME/$ENV_NAME"
	elif [[ -f "$ENV_ROOT" ]]; then
		# A virtualenvwrapper environment, name is in .venv
		ENV_NAME="$(cat "$ENV_ROOT")"
		ENV_ROOT="$WORKON_HOME/$ENV_NAME"
	elif [[ -f "$ENV_ROOT/bin/activate" ]];then
		# ENV_ROOT is an environment; take the project directory name and
		# relative path to the root (minus '.venv') as ENV_NAME
		ENV_NAME=${ENV_ROOT#$(dirname $PROJECT_ROOT)/}
		ENV_NAME=${ENV_NAME:h}
	fi

	if [[ -n "$ENV_ROOT" && -f "$ENV_ROOT/bin/activate" ]]; then
		# Activate the environment only if it is not already active
		if [[ ! "$VIRTUAL_ENV" -ef "$ENV_ROOT" ]]; then
			source "$ENV_ROOT/bin/activate" && export CD_VIRTUAL_ENV="$ENV_ROOT"
		fi
	else
		if [[ -n "$CD_VIRTUAL_ENV" && -n "$VIRTUAL_ENV" ]]; then
			# We've just left the repo, deactivate the environment
			# Note: this only happens if the virtualenv was activated automatically
			deactivate && unset CD_VIRTUAL_ENV
		fi
		unset ENV_NAME
	fi
}

# Append workon_cwd to the chpwd_functions array, so it will be called on cd
# http://zsh.sourceforge.net/Doc/Release/Functions.html
if ! (( $chpwd_functions[(I)workon_cwd] )); then
	chpwd_functions+=(workon_cwd)
fi
+1 −1
Original line number Diff line number Diff line
@@ -3,7 +3,7 @@ source ~/.shell/funcs
do_update

plugins+=(git django pip python)
plugins+=(virtualenv virtualenvwrapper tmux-virtualenvwrapper)
plugins+=(virtualenv-auto)

ZSH_CUSTOM=~/.shell/zsh_custom
ZSH_THEME="kodo"