1299e2d40ff945091b7bd45b1490bf728def6ea1

Author
Michael Aquilina <michaelaquilina@gmail.com>
Committer
GitHub <noreply@github.com>
Date

Message

Merge pull request #13 from ccheek21/master

Auto switch if .venv is in parent directories

Diff

 1diff --git a/autoswitch_virtualenv.plugin.zsh b/autoswitch_virtualenv.plugin.zsh
 2index 96ede9e9e1425837caa0d6b321a177b8520c20aa..2eeeb9fbbdee77e4a8d954186e4a6bd124e785e8 100644
 3--- a/autoswitch_virtualenv.plugin.zsh
 4+++ b/autoswitch_virtualenv.plugin.zsh
 5@@ -17,6 +17,22 @@ function maybeworkon() {
 6   fi
 7 }
 8 
 9+# Gives the path to the nearest parent .venv file or nothing if it gets to root
10+function check_venv_path()
11+{
12+    local check_dir=$1
13+
14+    if [[ -f "${check_dir}/.venv" ]]; then
15+        echo "${check_dir}/.venv"
16+        return
17+    else
18+        if [ "$check_dir" = "/" ]; then
19+            return
20+        fi
21+        check_venv_path "$(dirname "$check_dir")"
22+    fi
23+}
24+
25 
26 # Automatically switch virtualenv when .venv file detected
27 function check_venv()
28@@ -26,22 +42,23 @@ function check_venv()
29 
30         SWITCH_TO=""
31 
32-        if [[ -f ".venv" ]]; then
33-          file_owner="$(stat -c %u .venv)"
34-          file_permissions="$(stat -c %a .venv)"
35+        venv_path=$(check_venv_path "$PWD")
36+        if [[ -n "$venv_path" ]]; then
37+          file_owner="$(stat -c %u "$venv_path")"
38+          file_permissions="$(stat -c %a "$venv_path")"
39 
40           if [[ "$file_owner" != "$(id -u)" ]]; then
41             echo "AUTOSWITCH WARNING: Virtualenv will not be activated"
42             echo ""
43             echo "Reason: Found a .venv file but it is not owned by the current user"
44-            echo "Change ownership of .venv to '$USER' to fix this"
45+            echo "Change ownership of $venv_path to '$USER' to fix this"
46           elif [[ "$file_permissions" != "600" ]]; then
47             echo "AUTOSWITCH WARNING: Virtualenv will not be activated"
48             echo ""
49             echo "Reason: Found a .venv file with weak permission settings ($file_permissions)."
50             echo "Run the following command to fix this: \"chmod 600 .venv\""
51           else
52-            SWITCH_TO="$(<.venv)"
53+            SWITCH_TO="$(<"$venv_path")"
54             AUTOSWITCH_PROJECT="$PWD"
55           fi
56         fi