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