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 # -g: make it global, this is required when used with antigen.
45 typeset -g -A _autoenv_stack_entered_mtime
47 # Add an entry to the stack, and remember its mtime.
48 _autoenv_stack_entered_add() {
51 # Remove any existing entry.
52 _autoenv_stack_entered_remove $env_file
54 _autoenv_debug "[stack] adding: $env_file" 2
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)
62 # zstat_mime helper, conditionally defined.
63 # Load zstat module, but only its builtin `zstat`.
64 if ! zmodload -F zsh/stat b:zstat 2>/dev/null; then
65 # If the module is not available, define a wrapper around `stat`, and use its
66 # terse output instead of format, which is not supported by busybox.
67 # Assume '+mtime' as $1.
68 _autoenv_get_file_mtime() {
69 setopt localoptions pipefail
70 stat -t $1 2>/dev/null | cut -f13 -d ' ' || echo 0
73 _autoenv_get_file_mtime() {
74 zstat +mtime $1 2>/dev/null || echo 0
79 # Remove an entry from the stack.
80 _autoenv_stack_entered_remove() {
82 _autoenv_debug "[stack] removing: $env_file" 2
83 _autoenv_stack_entered[$_autoenv_stack_entered[(i)$env_file]]=()
84 _autoenv_stack_entered_mtime[$env_file]=
87 # Is the given entry already in the stack?
88 # This checks for the env_file ($1) as-is and with symlinks resolved.
89 _autoenv_stack_entered_contains() {
92 if (( ${+_autoenv_stack_entered[(r)${env_file}]} )); then
96 for i in $_autoenv_stack_entered; do
97 if [[ ${i:A} == ${env_file:A} ]]; then
98 # Entry is in stack (compared with resolved symlinks).
105 if [[ $_autoenv_stack_entered_mtime[$f] == $(_autoenv_get_file_mtime $f) ]]; then
106 # Entry has the expected mtime.
114 # Internal function for debug output. {{{
118 if [[ $AUTOENV_DEBUG -lt $level ]]; then
121 # Load zsh color support.
122 if [[ -z $color ]]; then
126 # Build $indent prefix.
128 if [[ $_autoenv_debug_indent -gt 0 ]]; then
129 for i in {1..${_autoenv_debug_indent}}; do
134 # Split $msg by \n (not newline).
135 lines=(${(ps:\\n:)msg})
136 for line in $lines; do
137 echo -n "${fg_bold[blue]}[autoenv]${fg_no_bold[default]} " >&2
138 echo ${indent}${line} >&2
144 # Generate hash pair for a given file ($1).
145 # A fixed hash value can be given as 2nd arg, but is used with tests only.
146 _autoenv_hash_pair() {
147 local env_file=${1:A}
148 local env_shasum=${2:-}
149 if [[ -z $env_shasum ]]; then
150 if ! [[ -e $env_file ]]; then
151 echo "Missing file argument for _autoenv_hash_pair!" >&2
154 env_shasum=$(shasum $env_file | cut -d' ' -f1)
156 echo ":${env_file}:${env_shasum}:1"
159 _autoenv_authorized_env_file() {
161 local pair=$(_autoenv_hash_pair $env_file)
162 test -f $AUTOENV_ENV_FILENAME \
163 && \grep -qF $pair $AUTOENV_ENV_FILENAME
166 _autoenv_authorize() {
167 local env_file=${1:A}
168 _autoenv_deauthorize $env_file
169 _autoenv_hash_pair $env_file >>| $AUTOENV_ENV_FILENAME
172 # Deauthorize a given filename, by removing it from the auth file.
173 # This uses `test -s` to only handle non-empty files, and a subshell to
174 # allow for writing to the same file again.
175 _autoenv_deauthorize() {
176 local env_file=${1:A}
177 if [[ -s $AUTOENV_ENV_FILENAME ]]; then
178 echo "$(\grep -vF :${env_file}: $AUTOENV_ENV_FILENAME)" >| $AUTOENV_ENV_FILENAME
182 # This function can be mocked in tests
183 _autoenv_ask_for_yes() {
186 if [[ $answer == "yes" ]]; then
193 # Args: 1: absolute path to env file (resolved symlinks).
194 _autoenv_check_authorized_env_file() {
195 if ! [[ -f $1 ]]; then
198 if ! _autoenv_authorized_env_file $1; then
199 echo "Attempting to load unauthorized env file!"
202 echo "**********************************************"
206 echo "**********************************************"
208 echo -n "Would you like to authorize it? (type 'yes') "
210 if ! _autoenv_ask_for_yes; then
214 _autoenv_authorize $1
219 # Get directory of this file (absolute, with resolved symlinks).
220 _autoenv_source_dir=${0:A:h}
225 local _autoenv_envfile_dir=${3:-${1:A:h}}
227 autoenv_from_dir=$_autoenv_chpwd_prev_dir
229 autoenv_env_file=$env_file
231 # Source varstash library once.
232 if [[ -z "$functions[(I)autostash]" ]]; then
233 source $_autoenv_source_dir/lib/varstash
234 # NOTE: Varstash uses $PWD as default for varstash_dir, we might set it to
238 # Change to directory of env file, source it and cd back.
240 _autoenv_debug "== SOURCE: ${bold_color:-}$env_file${reset_color:-}\n PWD: $PWD"
241 (( _autoenv_debug_indent++ ))
243 (( _autoenv_debug_indent-- ))
244 _autoenv_debug "== END SOURCE =="
246 if [[ $autoenv_event == enter ]]; then
247 _autoenv_stack_entered_add $env_file
250 # Unset vars set for enter/leave scripts.
251 # This should not get done for recursion (via autoenv_source_parent),
252 # and can be useful to have in general after autoenv was used.
253 # unset autoenv_event autoenv_from_dir autoenv_to_dir autoenv_env_file
256 _autoenv_get_file_upwards() {
257 local look_from=${1:-$PWD}
258 local look_for=${2:-$AUTOENV_FILE_ENTER}
260 # Manually look in parent dirs. An extended Zsh glob should use Y1 for
261 # performance reasons, which is only available in zsh-5.0.5-146-g9381bb6.
263 local parent_dir="$look_from/.."
265 parent_dir=${parent_dir:A}
266 if [[ $parent_dir == $last ]]; then
269 parent_file="${parent_dir}/${look_for}"
271 if [[ -f $parent_file ]]; then
277 parent_dir="${parent_dir}/.."
282 _autoenv_chpwd_prev_dir=$PWD
283 _autoenv_chpwd_handler() {
284 _autoenv_debug "Calling chpwd handler: PWD=$PWD"
286 if (( $AUTOENV_DISABLED )); then
287 _autoenv_debug "Disabled (AUTOENV_DISABLED)."
291 local env_file="$PWD/$AUTOENV_FILE_ENTER"
292 _autoenv_debug "env_file: $env_file"
294 # Handle leave event for previously sourced env files.
295 if [[ $AUTOENV_HANDLE_LEAVE == 1 ]] && (( $#_autoenv_stack_entered )); then
296 local prev_file prev_dir
297 for prev_file in ${_autoenv_stack_entered}; do
298 prev_dir=${prev_file:h}
299 if ! [[ ${PWD}/ == ${prev_dir}/* ]]; then
300 local env_file_leave=$prev_dir/$AUTOENV_FILE_LEAVE
301 if _autoenv_check_authorized_env_file $env_file_leave; then
302 _autoenv_source $env_file_leave leave $prev_dir
305 # Unstash any autostashed stuff.
306 varstash_dir=$prev_dir autounstash
308 _autoenv_stack_entered_remove $prev_file
313 if ! [[ -f $env_file ]] && [[ $AUTOENV_LOOK_UPWARDS == 1 ]]; then
314 env_file=$(_autoenv_get_file_upwards $PWD)
315 if [[ -z $env_file ]]; then
316 _autoenv_chpwd_prev_dir=$PWD
321 # Load the env file only once: check if $env_file is in the stack of entered
323 if _autoenv_stack_entered_contains $env_file; then
324 _autoenv_debug "Already in stack: $env_file"
325 _autoenv_chpwd_prev_dir=$PWD
329 if ! _autoenv_check_authorized_env_file $env_file; then
330 _autoenv_chpwd_prev_dir=$PWD
334 # Source the enter env file.
335 _autoenv_debug "Sourcing from chpwd handler: $env_file"
336 _autoenv_source $env_file enter
338 _autoenv_chpwd_prev_dir=$PWD
340 (( _autoenv_debug_indent++ ))
344 autoload -U add-zsh-hook
345 add-zsh-hook chpwd _autoenv_chpwd_handler
347 # Look in current directory already.
348 _autoenv_chpwd_handler