Skip to content
Myr

[Fix] `nvm_cd`: bypass a user-defined `cd` function

Landed as b1b3a00

`\cd` only bypasses aliases, so a user-defined `cd` function (eg, cdhist's) still ran, and broke `NVM_DIR` auto-detection when it rejected zsh's `-q`. Use `command cd`, which skips functions in POSIX shells. zsh's `command` runs `/usr/bin/cd` instead of the builtin, so use `builtin cd` there, as `nvm_echo` does for `printf`. `nvm_die_on_prefix` also now uses `nvm_cd` instead of a bare `cd`. Fixes #3835. See #3836.

authored by Jordan Harband · committed by the platform · parent 6dc3765 · Browse files · 2 files+31 added−2 removed
This landing

State

Landed as b1b3a00

By oscabriel

Diff stats

2 files+31 added−2 removed

  • tests:+23 added−0 removed
  • other:+8 added−2 removed

2 files+31 added−2 removed

added:test/fast/Unit tests/nvm_cd+23 added
1#!/bin/sh23die () { echo "$@" ; exit 1; }45: nvm.sh6\. ../../../nvm.sh78EXPECTED="$(\cd .. && pwd)"910# a user-defined `cd` function that rejects nvm's arguments, like cdhist's (#3835)11cd() {12 echo 'user-defined cd function was called' >&213 return 114}1516OUTPUT="$(nvm_cd .. 2>&1 && pwd)"17[ "${OUTPUT}" = "${EXPECTED}" ] || die "expected '${EXPECTED}', got '${OUTPUT}'"1819# shellcheck disable=SC208620OUTPUT="$(nvm_cd ${NVM_CD_FLAGS} .. 2>&1 && pwd)"21[ "${OUTPUT}" = "${EXPECTED}" ] || die "with NVM_CD_FLAGS '${NVM_CD_FLAGS}', expected '${EXPECTED}', got '${OUTPUT}'"2223unset -f cd
modified:nvm.sh+8 added-2 removed
39 unmodified lines
40 fi41}4243nvm_cd() {44 \cd "$@"44 # `\cd` still runs a user-defined `cd` function; in zsh, `command cd` runs `/usr/bin/cd` instead of the builtin45 if [ -n "${ZSH_VERSION-}" ]; then46 # shellcheck disable=SC304447 builtin cd "$@"48 else49 command cd "$@"50 fi51}5253# a caller that closed stderr, rather than redirecting it to /dev/null, makes54# the `>&2` fail; zsh cannot report that, so it aborts the script, which only a
3466 unmodified lines
3521 NVM_OS="$(nvm_get_os)"3522 local NVM_CONFIG_VALUE3523 eval "NVM_CONFIG_VALUE=\"\$${NVM_NPM_CONFIG_x_PREFIX_ENV}\""3524 if [ -n "${NVM_CONFIG_VALUE-}" ] && [ "_${NVM_OS}" = "_win" ]; then3519 NVM_CONFIG_VALUE="$(cd "$NVM_CONFIG_VALUE" 2>/dev/null && pwd)"3525 NVM_CONFIG_VALUE="$(nvm_cd "$NVM_CONFIG_VALUE" 2>/dev/null && pwd)"3526 fi3527 if [ -n "${NVM_CONFIG_VALUE-}" ] && ! nvm_tree_contains_path "${NVM_DIR}" "${NVM_CONFIG_VALUE}"; then3528 nvm deactivate >/dev/null 2>&13529 nvm_err "nvm is not compatible with the \"${NVM_NPM_CONFIG_x_PREFIX_ENV}\" environment variable: currently set to \"${NVM_CONFIG_VALUE}\""
2113 unmodified lines