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