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