1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#!/bin/bash
AL="$HOME/.local/state/cdvenv.allowlist"
BL="$HOME/.local/state/cdvenv.blocklist"
function _cdvenv {
d="$(readlink -f "$1")"
if [[ "$d" =~ "${HOME}".* ]]; then
if [ -d "$d/venv" ]; then
echo "$d/venv"
return
fi
if [ -d "$d/.venv" ]; then
echo "$d/.venv"
return
fi
else
return
fi
_cdvenv "$d/.."
}
function _cdvenvwhitelist {
venv="$1"
[ -f "$BL" ] && grep "$venv" "$BL" >/dev/null && return 1
[ -f "$AL" ] && grep "$venv" "$AL" >/dev/null && return 0
echo "Virtualenv '$venv' is unknown."
while true; do
read -r -p "Do you want to allow auto-activation? [yn] " r
case "$r" in
y | Y)
echo "$venv" >> "$AL"
return 0
;;
n | N)
echo "$venv" >> "$BL"
return 1
;;
esac
done
}
function _cdvenvactivate {
venv="$1"
_cdvenvwhitelist "$venv" || return 1
. "$venv/bin/activate"
}
function cdvenv {
cd "$@" || return $?
venv="$(_cdvenv "$PWD")"
if [ "$venv" != "" ]; then
if [ "$VIRTUAL_ENV" == "" ]; then
_cdvenvactivate "$venv"
fi
if [ "$VIRTUAL_ENV" != "$venv" ]; then
deactivate
_cdvenvactivate "$venv"
fi
else
if [ "$VIRTUAL_ENV" != "" ]; then
deactivate
fi
fi
return 0
}
alias cd=cdvenv