Tarrasch/zsh-autoenv

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

AndydeCleyre opened this issue · 2 comments

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

  • I have autoenv files which run functions defined in my ~/.zshrc
  • I am in a folder with such an autoenv configuration
  • I open a new tmux pane in the current path:
    % tmux bind l new-window -c "#{pane_current_path}"
  • Autoenv tries to run those functions, but they are not yet defined

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.

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.

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.