Skip to content

Instantly share code, notes, and snippets.

@andrewn
Created October 9, 2024 09:44
Show Gist options
  • Save andrewn/56e922410433635b8463f8e0194481de to your computer and use it in GitHub Desktop.
Save andrewn/56e922410433635b8463f8e0194481de to your computer and use it in GitHub Desktop.
mise (formally rtx) auto-switch version
function node_prompt_info() {
mise current 2>/dev/null
}
# https://johnlindquist.com/automatically-switch-node-versions-based-on-your-packagejson-and-precmd-in-zsh/
# https://chat.openai.com/share/fbe51310-cde1-47fe-9d6c-f1d1ac017008
# https://chat.openai.com/share/6bfa3691-de5e-44ba-bd18-0274f69a5fdf
precmd(){
if [ -f package.json ]
then
# Return early if .rtx.toml exists, as rtx handles this case
if [ -f .rtx.toml ]; then
return
fi
version_range=$(jq -r '.engines.node | select(.!=null)' package.json)
if [ ! -z $version_range ]
then
node_versions=("${(f)$(mise ls-remote node)}")
wanted_version=$(semver -r $version_range "${node_versions[@]}" | tail -n 1)
current_version=$(mise current node)
if [[ $current_version != $wanted_version ]]
then
echo "Switching to node@$wanted_version as specified in package.json"
mise use node@$wanted_version
fi
fi
fi
}
RPROMPT='$(node_prompt_info)'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment