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