Skip to content

Commit f8e7f30

Browse files
home-manager: lazy-initialize pyenv only in Python projects (chpwd hook)
1 parent 9bc7ecb commit f8e7f30

File tree

1 file changed

+33
-4
lines changed

1 file changed

+33
-4
lines changed

home-manager/default.nix

Lines changed: 33 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -117,13 +117,42 @@
117117
eval "$( ${pkgs.direnv}/bin/direnv hook zsh )"
118118
fi
119119
120-
# Initialize pyenv
120+
# Lazy initialize pyenv only when entering Python projects to speed up shell startup.
121121
export PYENV_ROOT="$HOME/.pyenv"
122-
export PATH="$PYENV_ROOT/bin:$PATH"
123-
if command -v pyenv 1>/dev/null 2>&1; then
124-
eval "$(pyenv init -)"
122+
123+
# _pyenv_activate_once: perform one-time initialization of pyenv in this shell
124+
_pyenv_activate_once() {
125+
# avoid reinitializing
126+
[ -n "${PYENV_ACTIVE-}" ] && return
127+
# add pyenv bin to PATH and init
128+
export PATH="$PYENV_ROOT/bin:$PATH"
129+
if command -v pyenv 1>/dev/null 2>&1; then
130+
eval "$(pyenv init -)"
131+
pyenv rehash 2>/dev/null || true
132+
export PYENV_ACTIVE=1
133+
fi
134+
}
135+
136+
# _maybe_init_pyenv: check for Python project files and initialize lazily
137+
_maybe_init_pyenv() {
138+
# If already active, nothing to do
139+
[ -n "${PYENV_ACTIVE-}" ] && return
140+
# Check for common Python project markers in the current directory
141+
if [ -f .python-version ] || [ -f pyproject.toml ] || [ -f Pipfile ] || [ -d .venv ]; then
142+
_pyenv_activate_once
143+
fi
144+
}
145+
146+
# Ensure add-zsh-hook is available and attach _maybe_init_pyenv to chpwd so
147+
# it runs whenever you change directories.
148+
autoload -Uz add-zsh-hook 2>/dev/null || true
149+
if type add-zsh-hook >/dev/null 2>&1; then
150+
add-zsh-hook chpwd _maybe_init_pyenv
125151
fi
126152
153+
# Run once for the current working directory at shell startup (non-blocking)
154+
_maybe_init_pyenv
155+
127156
# --- migrated from /etc/zshrc.local ---
128157
# Enable UTF-8 combining characters support when appropriate
129158
if [[ ! -x /usr/bin/locale ]] || [[ "$(locale LC_CTYPE)" == "UTF-8" ]]; then

0 commit comments

Comments
 (0)