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