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