From d6bfdff968cd7749d0c34416b9059afe0a3d150e Mon Sep 17 00:00:00 2001
From: Daniel Hahler <github@thequod.de>
Date: Thu, 14 Dec 2017 00:53:25 +0100
Subject: [PATCH] Fix (auto)unstashing when being sourced from a subdir (#79)

Fixes https://github.com/Tarrasch/zsh-autoenv/issues/77.
---
 autoenv.zsh                       | 5 ++---
 tests/varstash-unstash-on-leave.t | 6 +++---
 2 files changed, 5 insertions(+), 6 deletions(-)

diff --git a/autoenv.zsh b/autoenv.zsh
index 2deac54..5395e1f 100644
--- a/autoenv.zsh
+++ b/autoenv.zsh
@@ -293,8 +293,6 @@ _autoenv_source() {
     if \grep -qE '\b(autostash|autounstash|stash|unstash)\b' $autoenv_env_file; then
       source ${${funcsourcetrace[1]%:*}:h}/lib/varstash
     fi
-    # NOTE: Varstash uses $PWD as default for varstash_dir, we might set it to
-    # ${autoenv_env_file:h}.
   fi
 
   # Source the env file.
@@ -306,7 +304,8 @@ _autoenv_source() {
     restore_xtrace=1
     setopt localoptions xtrace
   fi
-  source $autoenv_env_file
+
+  varstash_dir=${autoenv_env_file:h} source $autoenv_env_file
   if (( restore_xtrace )); then
     setopt noxtrace
   fi
diff --git a/tests/varstash-unstash-on-leave.t b/tests/varstash-unstash-on-leave.t
index bfea2bf..c5cc125 100644
--- a/tests/varstash-unstash-on-leave.t
+++ b/tests/varstash-unstash-on-leave.t
@@ -4,7 +4,7 @@ Test unstash behavior on leaving.
 
 Setup test environment.
 
-  $ mkdir sub
+  $ mkdir -p sub/sub2
   $ echo 'echo ENTER; stash FOO=changed' >| sub/$AUTOENV_FILE_ENTER
   $ echo 'echo LEAVE; unstash FOO' >| sub/$AUTOENV_FILE_LEAVE
   $ test_autoenv_auth_env_files sub
@@ -12,14 +12,14 @@ Setup test environment.
 
 Activating the env stashes it and applies a new value.
 
-  $ cd sub
+  $ cd sub/sub2
   ENTER
   $ echo $FOO
   changed
 
 Leaving the directory unstashes it (varstash_dir is set to prev dir).
 
-  $ cd ..
+  $ cd -
   LEAVE
   $ echo $FOO
   orig
-- 
2.51.0