Last active
May 7, 2019 22:12
-
-
Save ar1a/fae815656344d42ae8a379089f068c9d to your computer and use it in GitHub Desktop.
Lazy load function for zsh
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env zsh | |
# usage: lazyload <name> <path> [source ...] -- callback | |
lazyload() { | |
local name="$1"; shift | |
local spath="$1"; shift | |
local sources=() | |
while [[ $# -gt 0 ]]; do | |
case "$1" in | |
--) shift; break ;; | |
*) sources+=("$1"); shift ;; | |
esac | |
done | |
local globals=() | |
() { | |
local IFS=$'\0' | |
globals=($(find "$spath" -maxdepth 3 \( -type l -o -type f \) -path '*/bin/*' -print0 | xargs -0n1 basename -z | sort -zu )) | |
globals[-1]=() # For some reason theres a blank entry at the end | |
globals+=("$name") | |
} | |
eval "lazy_sources_$name"='(${sources[@]})' | |
eval "lazy_globals_$name"='(${globals[@]})' | |
eval "lazy_callback_$name"='($@)' | |
eval "lazy_load_$name()" '{ | |
for source in "${lazy_sources_'"$name"'[@]}"; do | |
. "$source" | |
done | |
if [[ ${#lazy_callback_'"$name"'} -gt 0 ]]; then | |
"${lazy_callback_'"$name"'[@]}" | |
fi | |
lazy_loaded_'"$name"'=1 | |
}' | |
if [[ -o interactive ]]; then | |
for cmd in "${globals[@]}"; do | |
eval "${cmd}() { unset -f ${cmd} &>/dev/null; [ -z \${lazy_loaded_$name+x} ] && lazy_load_$name; ${cmd} \$@; }" | |
done | |
else | |
"lazy_load_$name" | |
fi | |
} | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
lazy_pyenvcallback() { | |
export PATH="$PYENV_ROOT/bin:$PATH" | |
eval "$(pyenv init -)" | |
} | |
lazy_rbenvcallback() { | |
export PATH="$HOME/.rbenv/bin:$PATH" | |
eval "$(rbenv init -)" | |
} | |
lazyload pyenv ~/.pyenv/versions -- lazy_pyenvcallback | |
lazyload rbenv ~/.rbenv/versions -- lazy_rbenvcallback |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment