Tarrasch / zsh-autoenv

Autoenv for zsh
693 stars 30 forks source link

How to ensure .zshrc is already sourced before running autoenv commands? #97

Closed AndydeCleyre closed 10 months ago

AndydeCleyre commented 2 years ago

Related to #2 -- here's some trouble I have with the ordering of events:


It looks like it's the last line of the plugin, calling _autoenv_chpwd_handler at the time the plugin is sourced.

So I guess that means I can work around this by loading this plugin after I define the things it'll need.

I wonder though if it might make sense to temporarily add the function to a different hook, then remove it. Yup, that seems to work. I'll submit a PR.

AndydeCleyre commented 2 years ago

Oh, well my initial attempt breaks something:

tests/varstash_export.t: failed
--- tests/varstash_export.t
+++ tests/varstash_export.t.err
@@ -36,14 +36,11 @@
 Activate autoenv in the subshell.

   $ $TESTSHELL -c "$TEST_SOURCE_AUTOENV; echo \${MYVAR}; echo \$MYEXPORT"
-  ENTER
-  changed
+
   changed_export

 "autounstash" should handle the exported variables.

   $ $TESTSHELL -c "$TEST_SOURCE_AUTOENV; cd ..; echo \${MYVAR:-empty}; echo \$MYEXPORT"
-  ENTER
-  LEAVE
   empty
-  orig_export
+  changed_export

But you can have a look at what I did:

diff --git a/autoenv.zsh b/autoenv.zsh
index fe97d74..0f642d7 100644
--- a/autoenv.zsh
+++ b/autoenv.zsh
@@ -429,6 +429,9 @@ _autoenv_chpwd_handler() {
   emulate -L zsh
   _autoenv_debug "Calling chpwd handler: PWD=$PWD"

+  autoload -U add-zsh-hook
+  add-zsh-hook -d precmd _autoenv_chpwd_handler
+
   if (( $AUTOENV_DISABLED )); then
     _autoenv_debug "Disabled (AUTOENV_DISABLED)."
     return
@@ -490,4 +493,5 @@ autoload -U add-zsh-hook
 add-zsh-hook chpwd _autoenv_chpwd_handler

 # Look in current directory already.
-_autoenv_chpwd_handler
+add-zsh-hook precmd _autoenv_chpwd_handler
+# _autoenv_chpwd_handler immediately removes itself from this array.
AndydeCleyre commented 2 years ago

For now I'm settled on

. . . loading this plugin after I define the things it'll need.

And that may be the last best answer, and that works for me.