Skip to content

Instantly share code, notes, and snippets.

@bastibe
Created January 23, 2017 15:08
Show Gist options
  • 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
@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