]> Sergey Matveev's repositories - zsh-autoenv.git/blob - autoenv.zsh
Remove underscore prefix from vars provided for .env files
[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 _autoenv_stack_entered=()
45 typeset -A _autoenv_stack_entered_mtime
46 _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 _autoenv_hash_pair() {
126   local env_file=${1:A}
127   local env_shasum
128   if [[ -n $2 ]]; then
129     env_shasum=$2
130   else
131     env_shasum=$(shasum $env_file | cut -d' ' -f1)
132   fi
133   echo "$env_file:$env_shasum:1"
134 }
135
136 _autoenv_authorized_env_file() {
137   local env_file=$1
138   local pair=$(_autoenv_hash_pair $env_file)
139   test -f $AUTOENV_ENV_FILENAME \
140     && \grep -qF $pair $AUTOENV_ENV_FILENAME
141 }
142
143 _autoenv_authorize() {
144   local env_file=$1
145   _autoenv_deauthorize $env_file
146   _autoenv_hash_pair $env_file >> $AUTOENV_ENV_FILENAME
147 }
148
149 _autoenv_deauthorize() {
150   local env_file=$1
151   if [[ -f $AUTOENV_ENV_FILENAME ]]; then
152     echo $(\grep -vF $env_file $AUTOENV_ENV_FILENAME) > $AUTOENV_ENV_FILENAME
153   fi
154 }
155
156 # This function can be mocked in tests
157 _autoenv_ask_for_yes() {
158   local answer
159   read answer
160   if [[ $answer == "yes" ]]; then
161     return 0
162   else
163     return 1
164   fi
165 }
166
167 # Args: 1: absolute path to env file (resolved symlinks).
168 _autoenv_check_authorized_env_file() {
169   if ! [[ -f $1 ]]; then
170     return 1
171   fi
172   if ! _autoenv_authorized_env_file $1; then
173     echo "Attempting to load unauthorized env file!"
174     command ls -l $1
175     echo ""
176     echo "**********************************************"
177     echo ""
178     cat $1
179     echo ""
180     echo "**********************************************"
181     echo ""
182     echo -n "Would you like to authorize it? (type 'yes') "
183
184     if ! _autoenv_ask_for_yes; then
185       return 1
186     fi
187
188     _autoenv_authorize $1
189   fi
190   return 0
191 }
192
193 # Get directory of this file (absolute, with resolved symlinks).
194 _autoenv_source_dir=${0:A:h}
195
196 _autoenv_source() {
197   local env_file=$1
198   autoenv_event=$2
199   local _autoenv_envfile_dir=${3:-${1:A:h}}
200
201   autoenv_from_dir=$_autoenv_chpwd_prev_dir
202   autoenv_to_dir=$PWD
203
204   # Source varstash library once.
205   if [[ -z "$functions[(I)autostash]" ]]; then
206     source $_autoenv_source_dir/lib/varstash
207     # NOTE: Varstash uses $PWD as default for varstash_dir, we might set it to
208     # ${env_file:h}.
209   fi
210
211   # Change to directory of env file, source it and cd back.
212   local new_dir=$PWD
213   builtin cd -q $_autoenv_envfile_dir
214   _autoenv_debug "== SOURCE: ${bold_color}$env_file${reset_color}\n      PWD: $PWD"
215   (( _autoenv_debug_indent++ ))
216   source $env_file
217   (( _autoenv_debug_indent-- ))
218   _autoenv_debug "== END SOURCE =="
219   builtin cd -q $new_dir
220
221   # Unset vars set for enter/leave scripts.
222   # This should not get done for recursion (via autoenv_source_parent),
223   # and can be useful to have in general after autoenv was used.
224   # unset autoenv_event autoenv_from_dir autoenv_to_dir
225 }
226
227 _autoenv_get_file_upwards() {
228   local look_from=${1:-$PWD}
229   local look_for=${2:-$AUTOENV_FILE_ENTER}
230
231   # Manually look in parent dirs. An extended Zsh glob should use Y1 for
232   # performance reasons, which is only available in zsh-5.0.5-146-g9381bb6.
233   local last
234   local parent_dir="$look_from/.."
235   while true; do
236     parent_dir=${parent_dir:A}
237     if [[ $parent_dir == $last ]]; then
238       break
239     fi
240     parent_file="${parent_dir}/${look_for}"
241
242     if [[ -f $parent_file ]]; then
243       echo $parent_file
244       break
245     fi
246
247     last=$parent_dir
248     parent_dir="${parent_dir}/.."
249   done
250 }
251
252
253 _autoenv_chpwd_prev_dir=$PWD
254 _autoenv_chpwd_handler() {
255   local env_file="$PWD/$AUTOENV_FILE_ENTER"
256
257   _autoenv_debug "Calling chpwd handler: PWD=$PWD"
258
259   # Handle leave event for previously sourced env files.
260   if [[ $AUTOENV_HANDLE_LEAVE == 1 ]] && (( $#_autoenv_stack_entered )); then
261     local prev_file prev_dir
262     for prev_file in ${_autoenv_stack_entered}; do
263       prev_dir=${prev_file:A:h}
264       if ! [[ ${PWD:A}/ == ${prev_dir}/* ]]; then
265         local env_file_leave=$prev_dir/$AUTOENV_FILE_LEAVE
266         if _autoenv_check_authorized_env_file $env_file_leave; then
267           _autoenv_source $env_file_leave leave $prev_dir
268         fi
269         _autoenv_stack_entered_remove $prev_file
270       fi
271     done
272   fi
273
274   if ! [[ -f $env_file ]] && [[ $AUTOENV_LOOK_UPWARDS == 1 ]]; then
275     env_file=$(_autoenv_get_file_upwards $PWD)
276     if [[ -z $env_file ]]; then
277       _autoenv_chpwd_prev_dir=$PWD
278       return
279     fi
280   fi
281
282   # Load the env file only once: check if $env_file is in the stack of entered
283   # directories.
284   if _autoenv_stack_entered_contains $env_file; then
285     _autoenv_debug "Already in stack: $env_file"
286     _autoenv_chpwd_prev_dir=$PWD
287     return
288   fi
289
290   if ! _autoenv_check_authorized_env_file $env_file; then
291     _autoenv_chpwd_prev_dir=$PWD
292     return
293   fi
294
295   _autoenv_stack_entered_add $env_file
296
297   # Source the enter env file.
298   _autoenv_debug "Sourcing from chpwd handler: $env_file"
299   _autoenv_source $env_file enter
300
301   _autoenv_chpwd_prev_dir=$PWD
302
303   (( _autoenv_debug_indent++ ))
304 }
305 # }}}
306
307 autoload -U add-zsh-hook
308 add-zsh-hook chpwd _autoenv_chpwd_handler
309
310 # Look in current directory already.
311 _autoenv_chpwd_handler