Skip to content

Instantly share code, notes, and snippets.

@Amar1729
Created May 30, 2020 23:40
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Amar1729/294c6e310b191405bf8fceb72e96b399 to your computer and use it in GitHub Desktop.
Save Amar1729/294c6e310b191405bf8fceb72e96b399 to your computer and use it in GitHub Desktop.
# sdkman recommands settings SDKMAN_DIR and sourcing sdkman-init.sh
# this can really slow down shell startup, so here's my attempt to lazy-load sdk()
#
# This snippet lives in my ~/.profile but generally could live in any zsh-related startup file.
#
# the logic of this custom sdk is kind of odd, but it basically checks if the current
# definition of sdk() is too short (less than 10 lines). If so, it tries to source
# the init script and then pass through all the arguments to the real sdk function.
export SDKMAN_DIR="$HOME/.sdkman"
# too slow!
# [[ -s "$SDKMAN_DIR/bin/sdkman-init.sh" ]] && source "$SDKMAN_DIR/bin/sdkman-init.sh"
# do this instead:
sdk () {
# "metaprogramming" lol - source init if sdk currently looks like this sdk function
if [[ "$(which sdk | wc -l)" -le 10 ]]; then
unset -f sdk
source "$SDKMAN_DIR/bin/sdkman-init.sh"
fi
sdk "$@"
}
@sellithy
Copy link

should instead use zsh's autoloading

@Farid-NL
Copy link

should instead use zsh's autoloading

How would you do it?

@Amar1729
Copy link
Author

no u right, this way is really dumb/hacky. I now use this zsh lazyload plugin

I honestly don't know autoload well enough to have written this myself, but i assume you mean something a bit like this: https://stackoverflow.com/questions/30840651/what-does-autoload-do-in-zsh

@Farid-NL
Copy link

Internally (I think) zsh-lazyload works quite similar to this code snippet, creates a function called the same as the command you're lazy loading, unset -f / unfunction the function and source the file the command needs.

The main difference it's the implementation, and that zsh-lazyload can work for any number of commands you like. Quite handy actually.

@Farid-NL
Copy link

Except for nvm, you can't use global installed packages like npm, npx and so on before actually (lazy) load nvm calling it once in the command line.

You can't call npx directly:

npx

You'll need to do something like this instead

nvm --version
npx

For this specific case I recommend zsh-nvm

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment