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