2 # https://github.com/joshuaclayton/dotfiles/blob/master/zsh_profile.d/autoenv.zsh
4 # File to store confirmed authentication into.
5 # This handles the deprecated, old location(s).
6 if [[ -z $AUTOENV_AUTH_FILE ]]; then
7 if [[ -n $AUTOENV_ENV_FILENAME ]]; then
8 echo "zsh-autoenv: using deprecated setting for AUTOENV_AUTH_FILE from AUTOENV_ENV_FILENAME." >&2
9 echo "Please set AUTOENV_AUTH_FILE instead." >&2
10 AUTOENV_AUTH_FILE=$AUTOENV_ENV_FILENAME
12 if [[ -n $XDG_DATA_HOME ]]; then
13 AUTOENV_AUTH_FILE=$XDG_DATA_HOME/autoenv_auth
15 AUTOENV_AUTH_FILE=~/.local/share/autoenv_auth
17 if [[ -f ~/.env_auth ]]; then
18 echo "zsh-autoenv: using deprecated location for AUTOENV_AUTH_FILE." >&2
19 echo "Please move it: mv ~/.env_auth ${(D)AUTOENV_AUTH_FILE}" >&2
20 AUTOENV_AUTH_FILE=~/.env_auth
25 # Name of the file to look for when entering directories.
26 : ${AUTOENV_FILE_ENTER:=.autoenv.zsh}
28 # Name of the file to look for when leaving directories.
29 # Requires AUTOENV_HANDLE_LEAVE=1.
30 : ${AUTOENV_FILE_LEAVE:=.autoenv_leave.zsh}
32 # Look for zsh-autoenv "enter" files in parent dirs?
33 : ${AUTOENV_LOOK_UPWARDS:=1}
35 # Handle leave events when changing away from a subtree, where an "enter"
37 : ${AUTOENV_HANDLE_LEAVE:=1}
39 # Enable debugging. Multiple levels are supported (max 2).
42 # (Temporarily) disable zsh-autoenv. This gets looked at in the chpwd handler.
43 : ${AUTOENV_DISABLED:=0}
45 # Public helper functions, which can be used from your .autoenv.zsh files:
47 # Source the next .autoenv.zsh file from parent directories.
48 # This is useful if you want to use a base .autoenv.zsh file for a directory
50 autoenv_source_parent() {
51 local look_until=${1:-/}
52 local parent_env_file=$(_autoenv_get_file_upwards \
53 ${autoenv_env_file:h} ${AUTOENV_FILE_ENTER} $look_until)
55 if [[ -n $parent_env_file ]] \
56 && _autoenv_check_authorized_env_file $parent_env_file; then
57 _autoenv_debug "Calling autoenv_source_parent: parent_env_file:$parent_env_file"
58 _autoenv_source $parent_env_file enter
62 # Internal functions. {{{
63 # Internal: stack of loaded env files (i.e. entered directories). {{{
64 typeset -g -a _autoenv_stack_entered
65 # -g: make it global, this is required when used with antigen.
66 typeset -g -A _autoenv_stack_entered_mtime
68 # Add an entry to the stack, and remember its mtime.
69 _autoenv_stack_entered_add() {
72 # Remove any existing entry.
73 _autoenv_stack_entered_remove $env_file
75 # Append it to the stack, and remember its mtime.
76 _autoenv_debug "[stack] adding: $env_file" 2
77 _autoenv_stack_entered+=($env_file)
78 _autoenv_stack_entered_mtime[$env_file]=$(_autoenv_get_file_mtime $env_file)
81 # zstat_mime helper, conditionally defined.
82 # Load zstat module, but only its builtin `zstat`.
83 if ! zmodload -F zsh/stat b:zstat 2>/dev/null; then
84 # If the module is not available, define a wrapper around `stat`, and use its
85 # terse output instead of format, which is not supported by busybox.
86 # Assume '+mtime' as $1.
87 _autoenv_get_file_mtime() {
88 # setopt localoptions pipefail
90 stat=$(stat -t $1 2>/dev/null)
91 if [[ -n $stat ]]; then
92 echo ${${(s: :)stat}[13]}
98 _autoenv_get_file_mtime() {
99 zstat +mtime $1 2>/dev/null || echo 0
103 # Remove an entry from the stack.
104 _autoenv_stack_entered_remove() {
106 _autoenv_debug "[stack] removing: $env_file" 2
107 _autoenv_stack_entered[$_autoenv_stack_entered[(i)$env_file]]=()
108 _autoenv_stack_entered_mtime[$env_file]=
111 # Is the given entry already in the stack?
112 # This checks for the env_file ($1) as-is and with symlinks resolved.
113 _autoenv_stack_entered_contains() {
116 if (( ${+_autoenv_stack_entered[(r)${env_file}]} )); then
120 for i in $_autoenv_stack_entered; do
121 if [[ ${i:A} == ${env_file:A} ]]; then
122 # Entry is in stack (compared with resolved symlinks).
129 if [[ $_autoenv_stack_entered_mtime[$f] == $(_autoenv_get_file_mtime $f) ]]; then
130 # Entry has the expected mtime.
138 # Internal function for debug output. {{{
141 if (( AUTOENV_DEBUG < level )); then
144 local msg="$1" # Might trigger a bug in Zsh 5.0.5 with shwordsplit.
145 # Load zsh color support.
146 if [[ -z $color ]]; then
150 # Build $indent prefix.
152 if [[ $_autoenv_debug_indent -gt 0 ]]; then
153 for i in {1..${_autoenv_debug_indent}}; do
158 # Split $msg by \n (not newline).
159 lines=(${(ps:\\n:)msg})
160 for line in $lines; do
161 echo -n "${fg_bold[blue]}[autoenv]${fg_no_bold[default]} " >&2
162 echo ${indent}${line} >&2
168 # Generate hash pair for a given file ($1) and version ($2).
169 # A fixed hash value can be given as 3rd arg, but is used with tests only.
170 # The format is ":$file:$hash:$version".
171 _autoenv_hash_pair() {
172 local env_file=${1:A}
173 local cksum_version=${2:-2}
174 local env_cksum=${3:-}
176 if [[ -z $env_cksum ]]; then
177 if ! [[ -e $env_file ]]; then
178 echo "Missing file argument for _autoenv_hash_pair!" >&2
181 if [[ $cksum_version = 2 ]]; then
182 # Get the output from `cksum` and join the first two words with a dot.
183 env_cksum=${(j:.:)${:-$(cksum "$env_file")}[1,2]}
184 elif [[ $cksum_version = 1 ]]; then
185 env_cksum=$(sha1sum $env_file | cut -d' ' -f1)
187 echo "Invalid version argument (${cksum_version}) for _autoenv_hash_pair!" >&2
191 ret_pair=":${env_file}:${env_cksum}:${cksum_version}"
195 # Check if a given env_file is authorized.
196 _autoenv_authorized_env_file() {
198 local env_file_abs=${env_file:A}
202 if [[ -f $AUTOENV_AUTH_FILE ]]; then
203 lines=( ${(M)"${(f@)"$(< $AUTOENV_AUTH_FILE)"}":#:$env_file_abs:*} )
205 if [[ -z $lines ]]; then
209 if (( $#lines != 1 )); then
210 echo "zsh-autoenv: found unexpected number ($#lines) of auth entries for $env_file in $AUTOENV_AUTH_FILE." >&2
215 if [[ $line == *:2 ]]; then
216 _autoenv_hash_pair $env_file
217 _autoenv_debug "Checking v2 pair: ${ret_pair}"
218 if [[ $line == $ret_pair ]]; then
221 elif [[ $line == *:1 ]]; then
222 # Fallback for v1 (SHA-1) pairs
223 _autoenv_debug "Checking v1 pair: ${ret_pair}"
224 _autoenv_hash_pair $env_file 1
225 if [[ $line == $ret_pair ]]; then
226 # Upgrade v1 entries to v2
227 _autoenv_authorize $env_file
234 _autoenv_authorize() {
235 local env_file=${1:A}
236 _autoenv_deauthorize $env_file
237 [[ -d ${AUTOENV_AUTH_FILE:h} ]] || mkdir -p ${AUTOENV_AUTH_FILE:h}
240 _autoenv_hash_pair $env_file && echo "$ret_pair"
241 } >>| $AUTOENV_AUTH_FILE
244 # Deauthorize a given filename, by removing it from the auth file.
245 # This uses `test -s` to only handle non-empty files.
246 _autoenv_deauthorize() {
247 local env_file=${1:A}
248 if [[ -s $AUTOENV_AUTH_FILE ]]; then
249 \grep -vF :${env_file}: $AUTOENV_AUTH_FILE >| $AUTOENV_AUTH_FILE.tmp
250 \mv $AUTOENV_AUTH_FILE.tmp $AUTOENV_AUTH_FILE
254 # This function can be mocked in tests
255 _autoenv_ask_for_yes() {
258 # Handle/catch Ctrl-C and return, instead of letting it potentially abort the
259 # shell setup process.
264 if [[ $answer == "yes" ]]; then
271 # Args: 1: absolute path to env file (resolved symlinks).
272 _autoenv_check_authorized_env_file() {
273 if ! [[ -f $1 ]]; then
276 if ! _autoenv_authorized_env_file $1; then
277 echo "Attempting to load unauthorized env file!" >&2
280 echo "**********************************************" >&2
284 echo "**********************************************" >&2
286 echo -n "Would you like to authorize it? (type 'yes') " >&2
287 # echo "Would you like to authorize it?"
288 # echo "('yes' to allow, 'no' to not being asked again; otherwise ignore it for the shell) "
290 if ! _autoenv_ask_for_yes; then
294 _autoenv_authorize $1
300 # Public API for the .autoenv.zsh script.
301 local autoenv_env_file=$1
302 local autoenv_event=$2
303 local autoenv_from_dir=$OLDPWD
304 local autoenv_to_dir=$PWD
306 # Source varstash library once.
307 # XXX: pollutes environment with e.g. `stash`, and `autostash` will cause
308 # an overwritten `stash` function to be called!
309 if ! (( $+functions[autostash] )); then
310 if \grep -qE '\b(autostash|autounstash|stash|unstash)\b' $autoenv_env_file; then
311 source ${${funcsourcetrace[1]%:*}:h}/lib/varstash
315 # Source the env file.
316 _autoenv_debug "== SOURCE: $autoenv_event: ${bold_color:-}$autoenv_env_file${reset_color:-} (in $PWD)"
317 (( ++_autoenv_debug_indent ))
320 if [[ $AUTOENV_DEBUG -gt 2 && ! -o xtrace ]]; then
322 setopt localoptions xtrace
325 varstash_dir=${autoenv_env_file:h} source $autoenv_env_file
326 if (( restore_xtrace )); then
329 (( --_autoenv_debug_indent ))
330 _autoenv_debug "== END SOURCE =="
332 if [[ $autoenv_event == enter ]]; then
333 _autoenv_stack_entered_add $autoenv_env_file
337 _autoenv_get_file_upwards() {
338 local look_from=${1:-$PWD}
339 local look_for=${2:-$AUTOENV_FILE_ENTER}
340 local look_until=${${3:-/}:A}
342 # Manually look in parent dirs. An extended Zsh glob should use Y1 for
343 # performance reasons, which is only available in zsh-5.0.5-146-g9381bb6.
345 local parent_dir="$look_from/.."
348 abs_parent_dir=${parent_dir:A}
349 if [[ $abs_parent_dir == $last ]]; then
352 local parent_file="${parent_dir}/${look_for}"
354 if [[ -f $parent_file ]]; then
355 if [[ ${parent_file[1,2]} == './' ]]; then
356 echo ${parent_file#./}
358 echo ${parent_file:a}
363 if [[ $abs_parent_dir == $look_until ]]; then
367 parent_dir="${parent_dir}/.."
375 check[enter]=$AUTOENV_FILE_ENTER
376 if [[ "$AUTOENV_FILE_ENTER" != "$AUTOENV_FILE_LEAVE" ]]; then
377 check[leave]=$AUTOENV_FILE_LEAVE
380 for t f in ${(kv)check}; do
382 if ! [[ -f $env_file ]]; then
383 env_file=$(_autoenv_get_file_upwards . $f)
384 if [[ -z $env_file ]]; then
385 echo "No $f file found ($t)." >&2
388 if ! [[ $AUTOENV_LOOK_UPWARDS == 1 ]]; then
389 echo "Note: found $env_file, but AUTOENV_LOOK_UPWARDS is disabled."
394 if [[ -z "$files" ]]; then
397 echo "Editing $files.."
399 editor="${${AUTOENV_EDITOR:-$EDITOR}:-vim}"
400 eval $editor "$files"
403 _autoenv_chpwd_handler() {
404 _autoenv_debug "Calling chpwd handler: PWD=$PWD"
406 if (( $AUTOENV_DISABLED )); then
407 _autoenv_debug "Disabled (AUTOENV_DISABLED)."
411 local env_file="$PWD/$AUTOENV_FILE_ENTER"
412 _autoenv_debug "Looking for env_file: $env_file"
414 # Handle leave event for previously sourced env files.
415 if [[ $AUTOENV_HANDLE_LEAVE == 1 ]] && (( $#_autoenv_stack_entered )); then
416 local prev_file prev_dir
417 for prev_file in ${_autoenv_stack_entered}; do
418 prev_dir=${prev_file:h}
419 if ! [[ ${PWD}/ == ${prev_dir}/* ]]; then
420 local env_file_leave=$prev_dir/$AUTOENV_FILE_LEAVE
421 _autoenv_debug "Handling leave event: $env_file_leave"
422 if _autoenv_check_authorized_env_file $env_file_leave; then
423 varstash_dir=$prev_dir _autoenv_source $env_file_leave leave $prev_dir
426 # Unstash any autostashed stuff.
427 if (( $+functions[autostash] )); then
428 varstash_dir=$prev_dir autounstash
431 _autoenv_stack_entered_remove $prev_file
436 if ! [[ -f $env_file ]] && [[ $AUTOENV_LOOK_UPWARDS == 1 ]]; then
437 env_file=$(_autoenv_get_file_upwards $PWD)
438 if [[ -z $env_file ]]; then
439 _autoenv_debug "No env_file found when looking upwards"
442 _autoenv_debug "Found env_file: $env_file"
445 # Load the env file only once: check if $env_file is in the stack of entered
447 if _autoenv_stack_entered_contains $env_file; then
448 _autoenv_debug "Already in stack: $env_file"
452 if ! _autoenv_check_authorized_env_file $env_file; then
456 # Source the enter env file.
457 _autoenv_debug "Sourcing from chpwd handler: $env_file"
458 _autoenv_source $env_file enter
462 autoload -U add-zsh-hook
463 add-zsh-hook chpwd _autoenv_chpwd_handler
465 # Look in current directory already.
466 _autoenv_chpwd_handler