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