Created
January 23, 2017 15:08
-
-
Save bastibe/c0950e463ffdfdfada7adf149ae77c6f to your computer and use it in GitHub Desktop.
A fish function to automatically activate a venv called ".env" in the current git root
This file contains 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
#!/bin/env fish | |
function cd -d "change directory, and activate virtualenvs, if available" | |
# first and foremost, change directory | |
builtin cd $argv | |
# find a parent git directory | |
if git rev-parse --show-toplevel >/dev/null ^/dev/null | |
set gitdir (realpath (git rev-parse --show-toplevel)) | |
else | |
set gitdir "" | |
end | |
# if that directory contains a virtualenv in a ".env" directory, activate it | |
if test \( -z "$VIRTUAL_ENV" -o "$VIRTUAL_ENV" != "$gitdir/.env" \) -a -f "$gitdir/.env/bin/activate.fish" | |
source $gitdir/.env/bin/activate.fish | |
end | |
# deactivate an active virtualenv if not int a git directory with an ".env" | |
if test -n "$VIRTUAL_ENV" -a "$VIRTUAL_ENV" != "$gitdir/.env" | |
deactivate | |
end | |
end |
For bash users:
has_cmd() {
case "$(type -t $1)" in
"alias"|\
"keyword"|\
"function"|\
"builtin"|\
"file") return 0 ;;
*) return 1 ;;
esac
}
if ! has_cmd auto_source_venv; then
export AUTO_SOURCE_VENV_DEACTIVATE=true
auto_source_venv() {
if [[ "$PS1" =~ ^\(venv_.* ]]; then
if $AUTO_SOURCE_VENV_DEACTIVATE; then
if has_cmd deactivate; then
deactivate
fi
else
return
fi
fi
venvs=$(find . -maxdepth 1 -type d -iname "venv_*" | head -n 1)
if [ -z "$venvs" ]; then
return
fi
. "$venvs/bin/activate"
}
fi
if has_cmd auto_source_venv; then
cd() {
builtin cd "$@" && auto_source_venv
}
fi
More robust version that work with current fish syntax: https://gist.github.com/tommyip/cf9099fa6053e30247e5d0318de2fb9e
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
note that the
test
function in fish combines different tests with-a
forand
and-o
foror
. This should make thetest
parts readable. See here for the full documentation.