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