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