]> Sergey Matveev's repositories - zsh-autoenv.git/blob - autoenv.zsh
Handle `setopt shwordsplit` (#89)
[zsh-autoenv.git] / autoenv.zsh
1 # Initially based on
2 # https://github.com/joshuaclayton/dotfiles/blob/master/zsh_profile.d/autoenv.zsh
3
4 # File to store confirmed authentication into.
5 # This handles the deprecated, old location(s).
6 if [[ -z $AUTOENV_AUTH_FILE ]]; then
7   if [[ -n $AUTOENV_ENV_FILENAME ]]; then
8     echo "zsh-autoenv: using deprecated setting for AUTOENV_AUTH_FILE from AUTOENV_ENV_FILENAME." >&2
9     echo "Please set AUTOENV_AUTH_FILE instead." >&2
10     AUTOENV_AUTH_FILE=$AUTOENV_ENV_FILENAME
11   else
12     if [[ -n $XDG_DATA_HOME ]]; then
13       AUTOENV_AUTH_FILE=$XDG_DATA_HOME/autoenv_auth
14     else
15       AUTOENV_AUTH_FILE=~/.local/share/autoenv_auth
16     fi
17     if [[ -f ~/.env_auth ]]; then
18       echo "zsh-autoenv: using deprecated location for AUTOENV_AUTH_FILE." >&2
19       echo "Please move it: mv ~/.env_auth ${(D)AUTOENV_AUTH_FILE}" >&2
20       AUTOENV_AUTH_FILE=~/.env_auth
21     fi
22   fi
23 fi
24
25 # Name of the file to look for when entering directories.
26 : ${AUTOENV_FILE_ENTER:=.autoenv.zsh}
27
28 # Name of the file to look for when leaving directories.
29 # Requires AUTOENV_HANDLE_LEAVE=1.
30 : ${AUTOENV_FILE_LEAVE:=.autoenv_leave.zsh}
31
32 # Look for zsh-autoenv "enter" files in parent dirs?
33 : ${AUTOENV_LOOK_UPWARDS:=1}
34
35 # Handle leave events when changing away from a subtree, where an "enter"
36 # event was handled?
37 : ${AUTOENV_HANDLE_LEAVE:=1}
38
39 # Enable debugging. Multiple levels are supported (max 2).
40 : ${AUTOENV_DEBUG:=0}
41
42 # (Temporarily) disable zsh-autoenv. This gets looked at in the chpwd handler.
43 : ${AUTOENV_DISABLED:=0}
44
45 # Public helper functions, which can be used from your .autoenv.zsh files:
46
47 # Source the next .autoenv.zsh file from parent directories.
48 # This is useful if you want to use a base .autoenv.zsh file for a directory
49 # subtree.
50 autoenv_source_parent() {
51   local look_until=${1:-/}
52   local parent_env_file=$(_autoenv_get_file_upwards \
53     ${autoenv_env_file:h} ${AUTOENV_FILE_ENTER} $look_until)
54
55   if [[ -n $parent_env_file ]] \
56     && _autoenv_check_authorized_env_file $parent_env_file; then
57     _autoenv_debug "Calling autoenv_source_parent: parent_env_file:$parent_env_file"
58     _autoenv_source $parent_env_file enter
59   fi
60 }
61
62 # Internal functions. {{{
63 # Internal: stack of loaded env files (i.e. entered directories). {{{
64 typeset -g -a _autoenv_stack_entered
65 # -g: make it global, this is required when used with antigen.
66 typeset -g -A _autoenv_stack_entered_mtime
67
68 # Add an entry to the stack, and remember its mtime.
69 _autoenv_stack_entered_add() {
70   local env_file=$1
71
72   # Remove any existing entry.
73   _autoenv_stack_entered_remove $env_file
74
75   # Append it to the stack, and remember its mtime.
76   _autoenv_debug "[stack] adding: $env_file" 2
77   _autoenv_stack_entered+=($env_file)
78   _autoenv_stack_entered_mtime[$env_file]=$(_autoenv_get_file_mtime $env_file)
79 }
80
81 # zstat_mime helper, conditionally defined.
82 # Load zstat module, but only its builtin `zstat`.
83 if ! zmodload -F zsh/stat b:zstat 2>/dev/null; then
84   # If the module is not available, define a wrapper around `stat`, and use its
85   # terse output instead of format, which is not supported by busybox.
86   # Assume '+mtime' as $1.
87   _autoenv_get_file_mtime() {
88     # setopt localoptions pipefail
89     local stat
90     stat=$(stat -t $1 2>/dev/null)
91     if [[ -n $stat ]]; then
92       echo ${${(s: :)stat}[13]}
93     else
94       echo 0
95     fi
96   }
97 else
98   _autoenv_get_file_mtime() {
99     zstat +mtime $1 2>/dev/null || echo 0
100   }
101 fi
102
103 # Remove an entry from the stack.
104 _autoenv_stack_entered_remove() {
105   local env_file=$1
106   _autoenv_debug "[stack] removing: $env_file" 2
107   _autoenv_stack_entered[$_autoenv_stack_entered[(i)$env_file]]=()
108   _autoenv_stack_entered_mtime[$env_file]=
109 }
110
111 # Is the given entry already in the stack?
112 # This checks for the env_file ($1) as-is and with symlinks resolved.
113 _autoenv_stack_entered_contains() {
114   local env_file=$1
115   local f i
116   if (( ${+_autoenv_stack_entered[(r)${env_file}]} )); then
117     # Entry is in stack.
118     f=$env_file
119   else
120     local env_file_abs=${env_file:A}
121     for i in $_autoenv_stack_entered; do
122       if [[ ${i:A} == ${env_file_abs} ]]; then
123         # Entry is in stack (compared with resolved symlinks).
124         f=$i
125         break
126       fi
127     done
128   fi
129   if [[ -n $f ]]; then
130     if [[ $_autoenv_stack_entered_mtime[$f] == $(_autoenv_get_file_mtime $f) ]]; then
131       # Entry has the expected mtime.
132       return
133     fi
134   fi
135   return 1
136 }
137 # }}}
138
139 # Internal function for debug output. {{{
140 _autoenv_debug() {
141   local level=${2:-1}
142   if (( AUTOENV_DEBUG < level )); then
143     return
144   fi
145   local msg="$1"  # Might trigger a bug in Zsh 5.0.5 with shwordsplit.
146   # Load zsh color support.
147   if [[ -z $color ]]; then
148     autoload colors
149     colors
150   fi
151   # Build $indent prefix.
152   local indent=
153   if [[ $_autoenv_debug_indent -gt 0 ]]; then
154     for i in {1..${_autoenv_debug_indent}}; do
155       indent="  $indent"
156     done
157   fi
158
159   # Split $msg by \n (not newline).
160   lines=(${(ps:\\n:)msg})
161   for line in $lines; do
162     echo -n "${fg_bold[blue]}[autoenv]${fg_no_bold[default]} " >&2
163     echo ${indent}${line} >&2
164   done
165 }
166 # }}}
167
168
169 # Generate hash pair for a given file ($1) and version ($2).
170 # A fixed hash value can be given as 3rd arg, but is used with tests only.
171 # The format is ":$file:$hash:$version".
172 _autoenv_hash_pair() {
173   local env_file=${1:A}
174   local cksum_version=${2:-2}
175   local env_cksum=${3:-}
176   ret_pair=
177   if [[ -z $env_cksum ]]; then
178     if ! [[ -e $env_file ]]; then
179       echo "Missing file argument for _autoenv_hash_pair!" >&2
180       return 1
181     fi
182     if [[ $cksum_version = 2 ]]; then
183       # Get the output from `cksum` and join the first two words with a dot.
184       env_cksum=${(j:.:)${:-$(cksum "$env_file")}[1,2]}
185     elif [[ $cksum_version = 1 ]]; then
186       env_cksum=$(sha1sum $env_file | cut -d' ' -f1)
187     else
188       echo "Invalid version argument (${cksum_version}) for _autoenv_hash_pair!" >&2
189       return 1
190     fi
191   fi
192   ret_pair=":${env_file}:${env_cksum}:${cksum_version}"
193 }
194
195
196 # Check if a given env_file is authorized.
197 _autoenv_authorized_env_file() {
198   local env_file=$1
199   local env_file_abs=${env_file:A}
200   local ret_pair
201
202   local -a lines
203   if [[ -f $AUTOENV_AUTH_FILE ]]; then
204     lines=( ${(M)"${(f@)"$(< $AUTOENV_AUTH_FILE)"}":#:$env_file_abs:*} )
205   fi
206   if [[ -z $lines ]]; then
207     return 1
208   fi
209
210   if (( $#lines != 1 )); then
211     echo "zsh-autoenv: found unexpected number ($#lines) of auth entries for $env_file in $AUTOENV_AUTH_FILE." >&2
212     echo $lines
213   fi
214   line=${lines[-1]}
215
216   if [[ $line == *:2 ]]; then
217     _autoenv_hash_pair $env_file
218     _autoenv_debug "Checking v2 pair: ${ret_pair}"
219     if [[ $line == $ret_pair ]]; then
220       return
221     fi
222   elif [[ $line == *:1 ]]; then
223     # Fallback for v1 (SHA-1) pairs
224     _autoenv_debug "Checking v1 pair: ${ret_pair}"
225     _autoenv_hash_pair $env_file 1
226     if [[ $line == $ret_pair ]]; then
227       # Upgrade v1 entries to v2
228       _autoenv_authorize $env_file
229       return
230     fi
231   fi
232   return 1
233 }
234
235 _autoenv_authorize() {
236   local env_file=${1:A}
237   _autoenv_deauthorize $env_file
238   [[ -d ${AUTOENV_AUTH_FILE:h} ]] || mkdir -p ${AUTOENV_AUTH_FILE:h}
239   {
240     local ret_pair
241     _autoenv_hash_pair $env_file && echo "$ret_pair"
242   } >>| $AUTOENV_AUTH_FILE
243 }
244
245 # Deauthorize a given filename, by removing it from the auth file.
246 # This uses `test -s` to only handle non-empty files.
247 _autoenv_deauthorize() {
248   local env_file=${1:A}
249   if [[ -s $AUTOENV_AUTH_FILE ]]; then
250     \grep -vF :${env_file}: $AUTOENV_AUTH_FILE >| $AUTOENV_AUTH_FILE.tmp
251     \mv $AUTOENV_AUTH_FILE.tmp $AUTOENV_AUTH_FILE
252   fi
253 }
254
255 # This function can be mocked in tests
256 _autoenv_ask_for_yes() {
257   local answer
258
259   # Handle/catch Ctrl-C and return, instead of letting it potentially abort the
260   # shell setup process.
261   setopt localtraps
262   trap 'return 1' INT
263
264   read answer
265   if [[ $answer == "yes" ]]; then
266     return 0
267   else
268     return 1
269   fi
270 }
271
272 # Args: 1: absolute path to env file (resolved symlinks).
273 _autoenv_check_authorized_env_file() {
274   if ! [[ -f $1 ]]; then
275     return 1
276   fi
277   if ! _autoenv_authorized_env_file $1; then
278     echo "Attempting to load unauthorized env file!" >&2
279     command ls -l $1 >&2
280     echo >&2
281     echo "**********************************************" >&2
282     echo >&2
283     command cat $1 >&2
284     echo >&2
285     echo "**********************************************" >&2
286     echo >&2
287     echo -n "Would you like to authorize it? (type 'yes') " >&2
288     # echo "Would you like to authorize it?"
289     # echo "('yes' to allow, 'no' to not being asked again; otherwise ignore it for the shell) "
290
291     if ! _autoenv_ask_for_yes; then
292       return 1
293     fi
294
295     _autoenv_authorize $1
296   fi
297   return 0
298 }
299
300 _autoenv_source() {
301   # Public API for the .autoenv.zsh script.
302   local autoenv_env_file=$1
303   local autoenv_event=$2
304   local autoenv_from_dir=$OLDPWD
305   local autoenv_to_dir=$PWD
306
307   # Source varstash library once.
308   # XXX: pollutes environment with e.g. `stash`, and `autostash` will cause
309   # an overwritten `stash` function to be called!
310   if ! (( $+functions[autostash] )); then
311     if \grep -qE '\b(autostash|autounstash|stash|unstash)\b' $autoenv_env_file; then
312       source ${${funcsourcetrace[1]%:*}:h}/lib/varstash
313     fi
314   fi
315
316   # Source the env file.
317   _autoenv_debug "== SOURCE: $autoenv_event: ${bold_color:-}$autoenv_env_file${reset_color:-} (in $PWD)"
318   (( ++_autoenv_debug_indent ))
319
320   local restore_xtrace
321   if [[ $AUTOENV_DEBUG -gt 2 && ! -o xtrace ]]; then
322     restore_xtrace=1
323     setopt localoptions xtrace
324   fi
325
326   varstash_dir=${autoenv_env_file:h} source $autoenv_env_file
327   if (( restore_xtrace )); then
328     setopt noxtrace
329   fi
330   (( --_autoenv_debug_indent ))
331   _autoenv_debug "== END SOURCE =="
332
333   if [[ $autoenv_event == enter ]]; then
334     _autoenv_stack_entered_add $autoenv_env_file
335   fi
336 }
337
338 _autoenv_get_file_upwards() {
339   local look_from=${1:-$PWD}
340   local look_for=${2:-$AUTOENV_FILE_ENTER}
341   local look_until=${${3:-/}:A}
342
343   # Manually look in parent dirs. An extended Zsh glob should use Y1 for
344   # performance reasons, which is only available in zsh-5.0.5-146-g9381bb6.
345   local last
346   local parent_dir="$look_from/.."
347   local abs_parent_dir
348   while true; do
349     abs_parent_dir=${parent_dir:A}
350     if [[ $abs_parent_dir == $last ]]; then
351       break
352     fi
353     local parent_file="${parent_dir}/${look_for}"
354
355     if [[ -f $parent_file ]]; then
356       if [[ ${parent_file[1,2]} == './' ]]; then
357         echo ${parent_file#./}
358       else
359         echo ${parent_file:a}
360       fi
361       break
362     fi
363
364     if [[ $abs_parent_dir == $look_until ]]; then
365       break
366     fi
367     last=$abs_parent_dir
368     parent_dir="${parent_dir}/.."
369   done
370 }
371
372 autoenv-edit() {
373   emulate -L zsh
374   local env_file
375   local -a files
376   local -A check
377   check[enter]=$AUTOENV_FILE_ENTER
378   if [[ "$AUTOENV_FILE_ENTER" != "$AUTOENV_FILE_LEAVE" ]]; then
379     check[leave]=$AUTOENV_FILE_LEAVE
380   fi
381   local f t
382   for t f in ${(kv)check}; do
383     env_file="$f"
384     if ! [[ -f $env_file ]]; then
385       env_file=$(_autoenv_get_file_upwards . $f)
386       if [[ -z $env_file ]]; then
387         echo "No $f file found ($t)." >&2
388         continue
389       fi
390       if ! [[ $AUTOENV_LOOK_UPWARDS == 1 ]]; then
391         echo "Note: found $env_file, but AUTOENV_LOOK_UPWARDS is disabled."
392       fi
393     fi
394     files+=($env_file)
395   done
396   if [[ -z "$files" ]]; then
397     return 1
398   fi
399   echo "Editing $files.."
400   local editor
401   editor="${${AUTOENV_EDITOR:-$EDITOR}:-vim}"
402   eval $editor "$files"
403 }
404
405 _autoenv_chpwd_handler() {
406   emulate -L zsh
407   _autoenv_debug "Calling chpwd handler: PWD=$PWD"
408
409   if (( $AUTOENV_DISABLED )); then
410     _autoenv_debug "Disabled (AUTOENV_DISABLED)."
411     return
412   fi
413
414   local env_file="$PWD/$AUTOENV_FILE_ENTER"
415   _autoenv_debug "Looking for env_file: $env_file"
416
417   # Handle leave event for previously sourced env files.
418   if [[ $AUTOENV_HANDLE_LEAVE == 1 ]] && (( $#_autoenv_stack_entered )); then
419     local prev_file prev_dir
420     for prev_file in ${_autoenv_stack_entered}; do
421       prev_dir=${prev_file:h}
422       if ! [[ ${PWD}/ == ${prev_dir}/* ]]; then
423         local env_file_leave=$prev_dir/$AUTOENV_FILE_LEAVE
424         _autoenv_debug "Handling leave event: $env_file_leave"
425         if _autoenv_check_authorized_env_file $env_file_leave; then
426           varstash_dir=$prev_dir _autoenv_source $env_file_leave leave $prev_dir
427         fi
428
429         # Unstash any autostashed stuff.
430         if (( $+functions[autostash] )); then
431           varstash_dir=$prev_dir autounstash
432         fi
433
434         _autoenv_stack_entered_remove $prev_file
435       fi
436     done
437   fi
438
439   if ! [[ -f $env_file ]] && [[ $AUTOENV_LOOK_UPWARDS == 1 ]]; then
440     env_file=$(_autoenv_get_file_upwards $PWD)
441     if [[ -z $env_file ]]; then
442       _autoenv_debug "No env_file found when looking upwards"
443       return
444     fi
445     _autoenv_debug "Found env_file: $env_file"
446   fi
447
448   # Load the env file only once: check if $env_file is in the stack of entered
449   # directories.
450   if _autoenv_stack_entered_contains $env_file; then
451     _autoenv_debug "Already in stack: $env_file"
452     return
453   fi
454
455   if ! _autoenv_check_authorized_env_file $env_file; then
456     return
457   fi
458
459   # Source the enter env file.
460   _autoenv_debug "Sourcing from chpwd handler: $env_file"
461   _autoenv_source $env_file enter
462 }
463 # }}}
464
465 autoload -U add-zsh-hook
466 add-zsh-hook chpwd _autoenv_chpwd_handler
467
468 # Look in current directory already.
469 _autoenv_chpwd_handler