2 # https://github.com/joshuaclayton/dotfiles/blob/master/zsh_profile.d/autoenv.zsh
4 export AUTOENV_ENV_FILENAME=$HOME/.env_auth
5 [ -e $AUTOENV_ENV_FILENAME ] || touch $AUTOENV_ENV_FILENAME
7 # Name of file to look for when entering directories.
8 : ${AUTOENV_FILE_ENTER:=.env}
10 # Name of file to look for when leaving directories.
11 # Requires AUTOENV_HANDLE_LEAVE=1.
12 : ${AUTOENV_FILE_LEAVE:=.env.leave}
14 # Look for .env in parent dirs?
15 : ${AUTOENV_LOOK_UPWARDS:=1}
17 # Handle leave events when changing away from a subtree, where an "enter"
19 : ${AUTOENV_HANDLE_LEAVE:=1}
21 # Enable debugging. Multiple levels are supported (max 2).
24 # (Temporarily) disable zsh-autoenv. This gets looked at in the chpwd handler.
25 : ${AUTOENV_DISABLED:=0}
27 # Public helper functions, which can be used from your .env files:
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})
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
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=()
49 # Add an entry to the stack, and remember its mtime.
50 _autoenv_stack_entered_add() {
53 # Remove any existing entry.
54 _autoenv_stack_entered_remove $env_file
56 _autoenv_debug "[stack] adding: $env_file" 2
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)
63 _autoenv_get_file_mtime() {
71 # Remove an entry from the stack.
72 _autoenv_stack_entered_remove() {
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]=
79 # Is the given entry already in the stack?
80 _autoenv_stack_entered_contains() {
82 if (( ${+_autoenv_stack_entered[(r)${env_file}]} )); then
84 if [[ $_autoenv_stack_entered_mtime[$env_file] == $(_autoenv_get_file_mtime $env_file) ]]; then
85 # Entry has the expected mtime.
93 # Internal function for debug output. {{{
97 if [[ $AUTOENV_DEBUG -lt $level ]]; then
100 # Load zsh color support.
101 if [[ -z $color ]]; then
105 # Build $indent prefix.
107 if [[ $_autoenv_debug_indent -gt 0 ]]; then
108 for i in {1..${_autoenv_debug_indent}}; do
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
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.
128 stat -t $2 | cut -f13 -d ' '
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
143 env_shasum=$(shasum $env_file | cut -d' ' -f1)
145 echo ":${env_file}:${env_shasum}:1"
148 _autoenv_authorized_env_file() {
150 local pair=$(_autoenv_hash_pair $env_file)
151 test -f $AUTOENV_ENV_FILENAME \
152 && \grep -qF $pair $AUTOENV_ENV_FILENAME
155 _autoenv_authorize() {
156 local env_file=${1:A}
157 _autoenv_deauthorize $env_file
158 _autoenv_hash_pair $env_file >>| $AUTOENV_ENV_FILENAME
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
171 # This function can be mocked in tests
172 _autoenv_ask_for_yes() {
175 if [[ $answer == "yes" ]]; then
182 # Args: 1: absolute path to env file (resolved symlinks).
183 _autoenv_check_authorized_env_file() {
184 if ! [[ -f $1 ]]; then
187 if ! _autoenv_authorized_env_file $1; then
188 echo "Attempting to load unauthorized env file!"
191 echo "**********************************************"
195 echo "**********************************************"
197 echo -n "Would you like to authorize it? (type 'yes') "
199 if ! _autoenv_ask_for_yes; then
203 _autoenv_authorize $1
208 # Get directory of this file (absolute, with resolved symlinks).
209 _autoenv_source_dir=${0:A:h}
214 local _autoenv_envfile_dir=${3:-${1:A:h}}
216 autoenv_from_dir=$_autoenv_chpwd_prev_dir
218 autoenv_env_file=$env_file
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
227 # Change to directory of env file, source it and cd back.
229 _autoenv_debug "== SOURCE: ${bold_color:-}$env_file${reset_color:-}\n PWD: $PWD"
230 (( _autoenv_debug_indent++ ))
232 (( _autoenv_debug_indent-- ))
233 _autoenv_debug "== END SOURCE =="
235 if [[ $autoenv_event == enter ]]; then
236 _autoenv_stack_entered_add $env_file
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
245 _autoenv_get_file_upwards() {
246 local look_from=${1:-$PWD}
247 local look_for=${2:-$AUTOENV_FILE_ENTER}
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.
252 local parent_dir="$look_from/.."
254 parent_dir=${parent_dir:A}
255 if [[ $parent_dir == $last ]]; then
258 parent_file="${parent_dir}/${look_for}"
260 if [[ -f $parent_file ]]; then
266 parent_dir="${parent_dir}/.."
271 _autoenv_chpwd_prev_dir=$PWD
272 _autoenv_chpwd_handler() {
273 _autoenv_debug "Calling chpwd handler: PWD=$PWD"
275 if (( $AUTOENV_DISABLED )); then
276 _autoenv_debug "Disabled (AUTOENV_DISABLED)."
280 local env_file="$PWD/$AUTOENV_FILE_ENTER"
281 _autoenv_debug "env_file: $env_file"
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
294 # Unstash any autostashed stuff.
295 varstash_dir=$prev_dir autounstash
297 _autoenv_stack_entered_remove $prev_file
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
310 # Load the env file only once: check if $env_file is in the stack of entered
312 if _autoenv_stack_entered_contains $env_file; then
313 _autoenv_debug "Already in stack: $env_file"
314 _autoenv_chpwd_prev_dir=$PWD
318 if ! _autoenv_check_authorized_env_file $env_file; then
319 _autoenv_chpwd_prev_dir=$PWD
323 # Source the enter env file.
324 _autoenv_debug "Sourcing from chpwd handler: $env_file"
325 _autoenv_source $env_file enter
327 _autoenv_chpwd_prev_dir=$PWD
329 (( _autoenv_debug_indent++ ))
333 autoload -U add-zsh-hook
334 add-zsh-hook chpwd _autoenv_chpwd_handler
336 # Look in current directory already.
337 _autoenv_chpwd_handler