Skip to content

Instantly share code, notes, and snippets.

@bastibe
Created January 23, 2017 15:08
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bastibe/c0950e463ffdfdfada7adf149ae77c6f to your computer and use it in GitHub Desktop.
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
#!/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
@bastibe
Copy link
Author

bastibe commented Jan 23, 2017

note that the test function in fish combines different tests with -a for and and -o for or. This should make the test parts readable. See here for the full documentation.

@phrohdoh
Copy link

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

@tommyip
Copy link

tommyip commented Dec 2, 2021

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