Skip to content

Instantly share code, notes, and snippets.

@tarcisioe
Last active August 29, 2015 14:06
Show Gist options
  • Save tarcisioe/791fc3320f6ab3c775f7 to your computer and use it in GitHub Desktop.
Save tarcisioe/791fc3320f6ab3c775f7 to your computer and use it in GitHub Desktop.
*sh cd overload for activating a parent virtualenv.
find_file_backwards() {
while [[ "${current_path}" != "/" ]]
do
file="${current_path}/$1"
if [ -f "${file}" ]
then
echo "${file}"
return
fi
current_path="$(dirname "${current_path}")"
done
}
enter_venv() {
current_path="${PWD}"
venvfile="$(find_file_backwards .venv)"
if [[ -z "${venvfile}" ]]
then
[[ -n "${VIRTUAL_ENV}" ]] && deactivate
return
fi
venv="$(dirname "${venvfile}")/$(cat "${venvfile}")"
if [[ -z "${VIRTUAL_ENV}" || "$(readlink -f "${VIRTUAL_ENV}")" != "$(readlink "${venv}")" ]]
then
. "${venv}/Scripts/activate"
return
fi
}
export_pylintrc() {
rc_path="$(find_file_backwards pylintrc)"
if [[ -n ${rc_path} ]]
then
export PYLINTRC="${rc_path}"
else
unset PYLINTRC
fi
}
custom_cd() {
builtin cd $@
enter_venv
export_pylintrc
}
activate_venv_cd() {
alias cd='custom_cd'
}
deactivate_venv_cd() {
unalias cd
}
@tarcisioe
Copy link
Author

Bash cd overload for activating a parent virtualenv. Just create a .venv one-line file with the name of the virtualenv to activate.

It also looks for a pylintrc in a parent directory and exports its path as PYLINTRC. Did this mostly for using Syntastic on vim.

You can cherry-pick features by deleting calls from custom_cd(). Should interoperate with stuff like autoenv without issues.

Works like this:

$ activate_venv_cd # better if called in your .*shrc
$ virtualenv myvenv
(...)
$ echo myvenv > .venv
$ cd .
(myvenv) $ cd src
(myvenv) $ cd ../..
$

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment