]> Sergey Matveev's repositories - zsh-autoenv.git/blob - autoenv.zsh
Do not `cd` in the `chpwd` hook
[zsh-autoenv.git] / autoenv.zsh
1 # Initially based on
2 # https://github.com/joshuaclayton/dotfiles/blob/master/zsh_profile.d/autoenv.zsh
3
4 export AUTOENV_ENV_FILENAME=$HOME/.env_auth
5 [ -e $AUTOENV_ENV_FILENAME ] || touch $AUTOENV_ENV_FILENAME
6
7 # Name of file to look for when entering directories.
8 : ${AUTOENV_FILE_ENTER:=.env}
9
10 # Name of file to look for when leaving directories.
11 # Requires AUTOENV_HANDLE_LEAVE=1.
12 : ${AUTOENV_FILE_LEAVE:=.env.leave}
13
14 # Look for .env in parent dirs?
15 : ${AUTOENV_LOOK_UPWARDS:=1}
16
17 # Handle leave events when changing away from a subtree, where an "enter"
18 # event was handled?
19 : ${AUTOENV_HANDLE_LEAVE:=1}
20
21 # Enable debugging. Multiple levels are supported (max 2).
22 : ${AUTOENV_DEBUG:=0}
23
24 # Public helper functions, which can be used from your .env files:
25 #
26 # Source the next .env file from parent directories.
27 # This is useful if you want to use a base .env file for a directory subtree.
28 autoenv_source_parent() {
29   local parent_env_file=$(_autoenv_get_file_upwards ${autoenv_env_file:h})
30
31   if [[ -n $parent_env_file ]] \
32     && _autoenv_check_authorized_env_file $parent_env_file; then
33     _autoenv_debug "Calling autoenv_source_parent: parent_env_file:$parent_env_file"
34     _autoenv_source $parent_env_file enter
35   fi
36 }
37
38 # Internal functions. {{{
39 # Internal: stack of entered (and handled) directories. {{{
40 typeset -g -a _autoenv_stack_entered
41 _autoenv_stack_entered=()
42 # -g: make it global, this is required when used with antigen.
43 typeset -g -A _autoenv_stack_entered_mtime
44 _autoenv_stack_entered_mtime=()
45
46 # Add an entry to the stack, and remember its mtime.
47 _autoenv_stack_entered_add() {
48   local env_file=$1
49
50   # Remove any existing entry.
51   _autoenv_stack_entered_remove $env_file
52
53   _autoenv_debug "[stack] adding: $env_file" 2
54
55   # Append it to the stack, and remember its mtime.
56   _autoenv_stack_entered+=($env_file)
57   _autoenv_stack_entered_mtime[$env_file]=$(_autoenv_get_file_mtime $env_file)
58 }
59
60 _autoenv_get_file_mtime() {
61   if [[ -f $1 ]]; then
62     zstat +mtime $1
63   else
64     echo 0
65   fi
66 }
67
68 # Remove an entry from the stack.
69 _autoenv_stack_entered_remove() {
70   local env_file=$1
71   _autoenv_debug "[stack] removing: $env_file" 2
72   _autoenv_stack_entered[$_autoenv_stack_entered[(i)$env_file]]=()
73   _autoenv_stack_entered_mtime[$env_file]=
74 }
75
76 # Is the given entry already in the stack?
77 _autoenv_stack_entered_contains() {
78   local env_file=$1
79   if (( ${+_autoenv_stack_entered[(r)${env_file}]} )); then
80     # Entry is in stack.
81     if [[ $_autoenv_stack_entered_mtime[$env_file] == $(_autoenv_get_file_mtime $env_file) ]]; then
82       # Entry has the expected mtime.
83       return
84     fi
85   fi
86   return 1
87 }
88 # }}}
89
90 # Internal function for debug output. {{{
91 _autoenv_debug() {
92   local msg=$1
93   local level=${2:-1}
94   if [[ $AUTOENV_DEBUG -lt $level ]]; then
95     return
96   fi
97   # Load zsh color support.
98   if [[ -z $color ]]; then
99     autoload colors
100     colors
101   fi
102   # Build $indent prefix.
103   local indent=
104   if [[ $_autoenv_debug_indent -gt 0 ]]; then
105     for i in {1..${_autoenv_debug_indent}}; do
106       indent="  $indent"
107     done
108   fi
109
110   # Split $msg by \n (not newline).
111   lines=(${(ps:\\n:)msg})
112   for line in $lines; do
113     echo -n "${fg_bold[blue]}[autoenv]${fg_no_bold[default]} " >&2
114     echo ${indent}${line} >&2
115   done
116 }
117 # }}}
118
119 # Load zstat module, but only its builtin `zstat`.
120 if ! zmodload -F zsh/stat b:zstat 2>/dev/null; then
121   # If the module is not available, define a wrapper around `stat`, and use its
122   # terse output instead of format, which is not supported by busybox.
123   # Assume '+mtime' as $1.
124   zstat() {
125     stat -t $2 | cut -f13 -d ' '
126   }
127 fi
128
129
130 # Generate hash pair for a given file ($1).
131 # A fixed hash value can be given as 2nd arg, but is used with tests only.
132 _autoenv_hash_pair() {
133   local env_file=${1:A}
134   local env_shasum=${2:-}
135   if [[ -z $env_shasum ]]; then
136     if ! [[ -e $env_file ]]; then
137       echo "Missing file argument for _autoenv_hash_pair!" >&2
138       return 1
139     fi
140     env_shasum=$(shasum $env_file | cut -d' ' -f1)
141   fi
142   echo ":${env_file}:${env_shasum}:1"
143 }
144
145 _autoenv_authorized_env_file() {
146   local env_file=$1
147   local pair=$(_autoenv_hash_pair $env_file)
148   test -f $AUTOENV_ENV_FILENAME \
149     && \grep -qF $pair $AUTOENV_ENV_FILENAME
150 }
151
152 _autoenv_authorize() {
153   local env_file=${1:A}
154   _autoenv_deauthorize $env_file
155   _autoenv_hash_pair $env_file >>| $AUTOENV_ENV_FILENAME
156 }
157
158 # Deauthorize a given filename, by removing it from the auth file.
159 # This uses `test -s` to only handle non-empty files, and a subshell to
160 # allow for writing to the same file again.
161 _autoenv_deauthorize() {
162   local env_file=${1:A}
163   if [[ -s $AUTOENV_ENV_FILENAME ]]; then
164     echo "$(\grep -vF :${env_file}: $AUTOENV_ENV_FILENAME)" >| $AUTOENV_ENV_FILENAME
165   fi
166 }
167
168 # This function can be mocked in tests
169 _autoenv_ask_for_yes() {
170   local answer
171   read answer
172   if [[ $answer == "yes" ]]; then
173     return 0
174   else
175     return 1
176   fi
177 }
178
179 # Args: 1: absolute path to env file (resolved symlinks).
180 _autoenv_check_authorized_env_file() {
181   if ! [[ -f $1 ]]; then
182     return 1
183   fi
184   if ! _autoenv_authorized_env_file $1; then
185     echo "Attempting to load unauthorized env file!"
186     command ls -l $1
187     echo ""
188     echo "**********************************************"
189     echo ""
190     cat $1
191     echo ""
192     echo "**********************************************"
193     echo ""
194     echo -n "Would you like to authorize it? (type 'yes') "
195
196     if ! _autoenv_ask_for_yes; then
197       return 1
198     fi
199
200     _autoenv_authorize $1
201   fi
202   return 0
203 }
204
205 # Get directory of this file (absolute, with resolved symlinks).
206 _autoenv_source_dir=${0:A:h}
207
208 _autoenv_source() {
209   local env_file=$1
210   autoenv_event=$2
211   local _autoenv_envfile_dir=${3:-${1:A:h}}
212
213   autoenv_from_dir=$_autoenv_chpwd_prev_dir
214   autoenv_to_dir=$PWD
215   autoenv_env_file=$env_file
216
217   # Source varstash library once.
218   if [[ -z "$functions[(I)autostash]" ]]; then
219     source $_autoenv_source_dir/lib/varstash
220     # NOTE: Varstash uses $PWD as default for varstash_dir, we might set it to
221     # ${env_file:h}.
222   fi
223
224   # Change to directory of env file, source it and cd back.
225   local new_dir=$PWD
226   _autoenv_debug "== SOURCE: ${bold_color:-}$env_file${reset_color:-}\n      PWD: $PWD"
227   (( _autoenv_debug_indent++ ))
228   source $env_file
229   (( _autoenv_debug_indent-- ))
230   _autoenv_debug "== END SOURCE =="
231
232   if [[ $autoenv_event == enter ]]; then
233     _autoenv_stack_entered_add $env_file
234   fi
235
236   # Unset vars set for enter/leave scripts.
237   # This should not get done for recursion (via autoenv_source_parent),
238   # and can be useful to have in general after autoenv was used.
239   # unset autoenv_event autoenv_from_dir autoenv_to_dir autoenv_env_file
240 }
241
242 _autoenv_get_file_upwards() {
243   local look_from=${1:-$PWD}
244   local look_for=${2:-$AUTOENV_FILE_ENTER}
245
246   # Manually look in parent dirs. An extended Zsh glob should use Y1 for
247   # performance reasons, which is only available in zsh-5.0.5-146-g9381bb6.
248   local last
249   local parent_dir="$look_from/.."
250   while true; do
251     parent_dir=${parent_dir:A}
252     if [[ $parent_dir == $last ]]; then
253       break
254     fi
255     parent_file="${parent_dir}/${look_for}"
256
257     if [[ -f $parent_file ]]; then
258       echo $parent_file
259       break
260     fi
261
262     last=$parent_dir
263     parent_dir="${parent_dir}/.."
264   done
265 }
266
267
268 _autoenv_chpwd_prev_dir=$PWD
269 _autoenv_chpwd_handler() {
270   local env_file="$PWD/$AUTOENV_FILE_ENTER"
271
272   _autoenv_debug "Calling chpwd handler: PWD=$PWD"
273
274   # Handle leave event for previously sourced env files.
275   if [[ $AUTOENV_HANDLE_LEAVE == 1 ]] && (( $#_autoenv_stack_entered )); then
276     local prev_file prev_dir
277     for prev_file in ${_autoenv_stack_entered}; do
278       prev_dir=${prev_file:A:h}
279       if ! [[ ${PWD:A}/ == ${prev_dir}/* ]]; then
280         local env_file_leave=$prev_dir/$AUTOENV_FILE_LEAVE
281         if _autoenv_check_authorized_env_file $env_file_leave; then
282           _autoenv_source $env_file_leave leave $prev_dir
283         fi
284
285         # Unstash any autostashed stuff.
286         varstash_dir=$prev_dir autounstash
287
288         _autoenv_stack_entered_remove $prev_file
289       fi
290     done
291   fi
292
293   if ! [[ -f $env_file ]] && [[ $AUTOENV_LOOK_UPWARDS == 1 ]]; then
294     env_file=$(_autoenv_get_file_upwards $PWD)
295     if [[ -z $env_file ]]; then
296       _autoenv_chpwd_prev_dir=$PWD
297       return
298     fi
299   fi
300
301   # Load the env file only once: check if $env_file is in the stack of entered
302   # directories.
303   if _autoenv_stack_entered_contains $env_file; then
304     _autoenv_debug "Already in stack: $env_file"
305     _autoenv_chpwd_prev_dir=$PWD
306     return
307   fi
308
309   if ! _autoenv_check_authorized_env_file $env_file; then
310     _autoenv_chpwd_prev_dir=$PWD
311     return
312   fi
313
314   # Source the enter env file.
315   _autoenv_debug "Sourcing from chpwd handler: $env_file"
316   _autoenv_source $env_file enter
317
318   _autoenv_chpwd_prev_dir=$PWD
319
320   (( _autoenv_debug_indent++ ))
321 }
322 # }}}
323
324 autoload -U add-zsh-hook
325 add-zsh-hook chpwd _autoenv_chpwd_handler
326
327 # Look in current directory already.
328 _autoenv_chpwd_handler