]> Sergey Matveev's repositories - zsh-autoenv.git/blobdiff - autoenv.zsh
Fixes after using `setopt nounset` during tests
[zsh-autoenv.git] / autoenv.zsh
index f8ca079f6de2aad2ba83a97c5938d0cd44b3832b..db77553cdaaff4ec5593a719906671934a577f35 100644 (file)
@@ -41,9 +41,8 @@ autoenv_source_parent() {
 
 # Internal functions. {{{
 # Internal: stack of entered (and handled) directories. {{{
-_autoenv_stack_entered=()
+typeset -a _autoenv_stack_entered
 typeset -A _autoenv_stack_entered_mtime
-_autoenv_stack_entered_mtime=()
 
 # Add an entry to the stack, and remember its mtime.
 _autoenv_stack_entered_add() {
@@ -122,15 +121,19 @@ _autoenv_debug() {
 zmodload -F zsh/stat b:zstat
 
 
+# Generate hash pair for a given file ($1).
+# A fixed hash value can be given as 2nd arg, but is used with tests only.
 _autoenv_hash_pair() {
   local env_file=${1:A}
-  local env_shasum
-  if [[ -n $2 ]]; then
-    env_shasum=$2
-  else
+  local env_shasum=${2:-}
+  if [[ -z $env_shasum ]]; then
+    if ! [[ -e $env_file ]]; then
+      echo "Missing file argument for _autoenv_hash_pair!" >&2
+      return 1
+    fi
     env_shasum=$(shasum $env_file | cut -d' ' -f1)
   fi
-  echo "$env_file:$env_shasum:1"
+  echo ":${env_file}:${env_shasum}:1"
 }
 
 _autoenv_authorized_env_file() {
@@ -141,15 +144,18 @@ _autoenv_authorized_env_file() {
 }
 
 _autoenv_authorize() {
-  local env_file=$1
+  local env_file=${1:A}
   _autoenv_deauthorize $env_file
   _autoenv_hash_pair $env_file >> $AUTOENV_ENV_FILENAME
 }
 
+# Deauthorize a given filename, by removing it from the auth file.
+# This uses `test -s` to only handle non-empty files, and a subshell to
+# allow for writing to the same file again.
 _autoenv_deauthorize() {
-  local env_file=$1
-  if [[ -f $AUTOENV_ENV_FILENAME ]]; then
-    echo $(\grep -vF $env_file $AUTOENV_ENV_FILENAME) > $AUTOENV_ENV_FILENAME
+  local env_file=${1:A}
+  if [[ -s $AUTOENV_ENV_FILENAME ]]; then
+    echo "$(\grep -vF :${env_file}: $AUTOENV_ENV_FILENAME)" > $AUTOENV_ENV_FILENAME
   fi
 }
 
@@ -211,7 +217,7 @@ _autoenv_source() {
   # Change to directory of env file, source it and cd back.
   local new_dir=$PWD
   builtin cd -q $_autoenv_envfile_dir
-  _autoenv_debug "== SOURCE: ${bold_color}$env_file${reset_color}\n      PWD: $PWD"
+  _autoenv_debug "== SOURCE: ${bold_color:-}$env_file${reset_color:-}\n      PWD: $PWD"
   (( _autoenv_debug_indent++ ))
   source $env_file
   (( _autoenv_debug_indent-- ))
@@ -267,7 +273,7 @@ _autoenv_chpwd_handler() {
           _autoenv_source $env_file_leave leave $prev_dir
         fi
 
-        # Unstash any autostash'd stuff.
+        # Unstash any autostashed stuff.
         varstash_dir=$prev_dir autounstash
 
         _autoenv_stack_entered_remove $prev_file