Skip to content

Instantly share code, notes, and snippets.

@tommyip
Last active May 31, 2023 12:56
Embed
What would you like to do?
Automatically activate/deactivate virtualenv in fish shell
# Based on https://gist.github.com/bastibe/c0950e463ffdfdfada7adf149ae77c6f
# Changes:
# * Instead of overriding cd, we detect directory change. This allows the script to work
# for other means of cd, such as z.
# * Update syntax to work with new versions of fish.
# * Handle virtualenvs that are not located in the root of a git directory.
function __auto_source_venv --on-variable PWD --description "Activate/Deactivate virtualenv on directory change"
status --is-command-substitution; and return
# Check if we are inside a git directory
if git rev-parse --show-toplevel &>/dev/null
set gitdir (realpath (git rev-parse --show-toplevel))
set cwd (pwd)
# While we are still inside the git directory, find the closest
# virtualenv starting from the current directory.
while string match "$gitdir*" "$cwd" &>/dev/null
if test -e "$cwd/.venv/bin/activate.fish"
source "$cwd/.venv/bin/activate.fish" &>/dev/null
return
else
set cwd (path dirname "$cwd")
end
end
end
# If virtualenv activated but we are not in a git directory, deactivate.
if test -n "$VIRTUAL_ENV"
deactivate
end
end
@yifeikong
Copy link

This works great, Thanks.

@nilueps
Copy link

nilueps commented Nov 22, 2022

nice!

@Susensio
Copy link

Awesome!

@nakulj
Copy link

nakulj commented Jan 25, 2023

I have packaged this into a fisher plugin: https://github.com/nakulj/auto-venv

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