rossmacarthur / sheldon

:bowtie: Fast, configurable, shell plugin manager
https://sheldon.cli.rs
Apache License 2.0
958 stars 21 forks source link

Example with zsh-defer and nvm auto-load functionality #131

Closed jvzaniolo closed 2 years ago

jvzaniolo commented 2 years ago

Hi there!

I'm setting up a sheldon configuration with zsh-defer and nvm with auto load functionality but I'm seeing some errors.

CleanShot 2022-01-24 at 1 48 11

I believe it's because zsh is running the load-nvmrc() function before nvm is loaded (because I'm applying zsh-defer to nvm)

How should I make this work?

Here's my .zshrc file:

eval "$(sheldon source)"

# place this after nvm initialization!
autoload -U add-zsh-hook
load-nvmrc() {
  local node_version="$(nvm version)"
  local nvmrc_path="$(nvm_find_nvmrc)"

  if [ -n "$nvmrc_path" ]; then
    local nvmrc_node_version=$(nvm version "$(cat "${nvmrc_path}")")

    if [ "$nvmrc_node_version" = "N/A" ]; then
      nvm install
    elif [ "$nvmrc_node_version" != "$node_version" ]; then
      nvm use
    fi
  elif [ "$node_version" != "$(nvm version default)" ]; then
    echo "Reverting to nvm default version"
    nvm use default
  fi
}
add-zsh-hook chpwd load-nvmrc
load-nvmrc
rossmacarthur commented 2 years ago

If nvm loading is deferred then you could try defer the loading of this function as well. zsh-defer will load things in the order you call zsh-defer on them. So since these are after sheldon they will only be loaded after the deferred sheldon plugins are loaded.

zsh-defer add-zsh-hook chpwd load-nvmrc
zsh-defer load-nvmrc

How would handle this is to make this code a local plugin

# path/to/nvmrc/nvmrc.plugin.zsh

#!/usr/bin/env zsh
autoload -U add-zsh-hook
load-nvmrc() {
  local node_version="$(nvm version)"
  local nvmrc_path="$(nvm_find_nvmrc)"

  if [ -n "$nvmrc_path" ]; then
    local nvmrc_node_version=$(nvm version "$(cat "${nvmrc_path}")")

    if [ "$nvmrc_node_version" = "N/A" ]; then
      nvm install
    elif [ "$nvmrc_node_version" != "$node_version" ]; then
      nvm use
    fi
  elif [ "$node_version" != "$(nvm version default)" ]; then
    echo "Reverting to nvm default version"
    nvm use default
  fi
}
add-zsh-hook chpwd load-nvmrc
load-nvmrc

And then load this using sheldon

[plugins.nvmrc]
local = "path/to/nvmrc"
apply = ["defer"]
jvzaniolo commented 2 years ago

Thanks @rossmacarthur. It worked!!