Skip to content

Commit fcc5935

Browse files
authored
Merge pull request #6 from SangwoonYun/feat/find-venv
feat: Find venv directory generally
2 parents 47e9760 + 86140e7 commit fcc5935

File tree

1 file changed

+19
-8
lines changed

1 file changed

+19
-8
lines changed

zsh-auto-venv.plugin.zsh

+19-8
Original file line numberDiff line numberDiff line change
@@ -58,30 +58,41 @@ auto_venv_update_check() {
5858
# Call the update check function when the plugin loads
5959
auto_venv_update_check
6060

61-
# autoload is used to load the add-zsh-hook function.
62-
autoload -U add-zsh-hook
63-
64-
# Function to search for .venv directories from the current directory upwards.
6561
find_venv() {
6662
local dir=$1
67-
while [[ "$dir" != "" && ! -e "$dir/.venv" ]]; do
68-
dir=${dir%/*}
63+
local found_venvs=() # Array to hold found virtual environments
64+
65+
# Search for 'bin/activate' in current and all parent directories
66+
while [[ "$dir" != "" ]]; do
67+
# Look for 'bin/activate' in all subdirectories of the current directory
68+
found_venvs=($(find "$dir" -maxdepth 3 -type f -name "activate" -path "*/bin/activate"))
69+
echo $found_venvs
70+
if [[ "${#found_venvs[@]}" -gt 0 ]]; then
71+
echo "${found_venvs[0]%/*/*}" # Return the first found virtual environment path
72+
return
73+
fi
74+
dir=${dir%/*} # Move up to the parent directory
6975
done
70-
echo $dir
7176
}
7277

7378
# Function to activate or deactivate virtual environments.
7479
activate_venv() {
7580
local venv_path=$(find_venv $PWD)
7681
if [[ -n "$venv_path" ]]; then
82+
if [[ "$VIRTUAL_ENV" && "$VIRTUAL_ENV" != "$venv_path" ]]; then
83+
deactivate
84+
fi
7785
# Activates the virtual environment if found.
78-
source "$venv_path/.venv/bin/activate"
86+
source "$venv_path"
7987
elif [[ -n "$VIRTUAL_ENV" ]]; then
8088
# Deactivates the virtual environment if exited from project directory.
8189
deactivate
8290
fi
8391
}
8492

93+
# autoload is used to load the add-zsh-hook function.
94+
autoload -U add-zsh-hook
95+
8596
# Sets up the function to be called whenever the current directory changes.
8697
add-zsh-hook chpwd activate_venv
8798

0 commit comments

Comments
 (0)