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