[Refactor] create `nvm_normalize_lts` helper

Jordan Harband 2021-12-16 22:55:02 -08:00
parent 430860a8be
commit 0b4cd8df6c
No known key found for this signature in database
GPG Key ID: 9F6A681E35EF8B56
2 changed files with 65 additions and 17 deletions

42
nvm.sh
View File

@ -687,6 +687,29 @@ nvm_normalize_version() {
}' "${1#v}" }' "${1#v}"
} }
nvm_normalize_lts() {
local LTS
LTS="${1-}"
if [ "$(expr "${LTS}" : '^lts/-[1-9][0-9]*$')" -gt 0 ]; then
local N
N="$(echo "${LTS}" | cut -d '-' -f 2)"
N=$((N+1))
local NVM_ALIAS_DIR
NVM_ALIAS_DIR="$(nvm_alias_path)"
local RESULT
RESULT="$(command ls "${NVM_ALIAS_DIR}/lts" | command tail -n "${N}" | command head -n 1)"
if [ "${RESULT}" != '*' ]; then
nvm_echo "lts/${RESULT}"
else
nvm_err 'That many LTS releases do not exist yet.'
return 2
fi
else
nvm_echo "${LTS}"
fi
}
nvm_ensure_version_prefix() { nvm_ensure_version_prefix() {
local NVM_VERSION local NVM_VERSION
NVM_VERSION="$(nvm_strip_iojs_prefix "${1-}" | command sed -e 's/^\([0-9]\)/v\1/g')" NVM_VERSION="$(nvm_strip_iojs_prefix "${1-}" | command sed -e 's/^\([0-9]\)/v\1/g')"
@ -1043,27 +1066,14 @@ nvm_alias() {
nvm_err 'An alias is required.' nvm_err 'An alias is required.'
return 1 return 1
fi fi
ALIAS="$(nvm_normalize_lts "${ALIAS}")"
local NVM_ALIAS_DIR if [ -z "${ALIAS}" ]; then
NVM_ALIAS_DIR="$(nvm_alias_path)"
if [ "$(expr "${ALIAS}" : '^lts/-[1-9][0-9]*$')" -gt 0 ]; then
local N
N="$(echo "${ALIAS}" | cut -d '-' -f 2)"
N=$((N+1))
local RESULT
RESULT="$(command ls "${NVM_ALIAS_DIR}/lts" | command tail -n "${N}" | command head -n 1)"
if [ "${RESULT}" != '*' ]; then
nvm_alias "lts/${RESULT}"
return $?
else
nvm_err 'That many LTS releases do not exist yet.'
return 2 return 2
fi fi
fi
local NVM_ALIAS_PATH local NVM_ALIAS_PATH
NVM_ALIAS_PATH="${NVM_ALIAS_DIR}/${ALIAS}" NVM_ALIAS_PATH="$(nvm_alias_path)/${ALIAS}"
if [ ! -f "${NVM_ALIAS_PATH}" ]; then if [ ! -f "${NVM_ALIAS_PATH}" ]; then
nvm_err 'Alias does not exist.' nvm_err 'Alias does not exist.'
return 2 return 2

View File

@ -0,0 +1,38 @@
#!/bin/sh
cleanup() {
unset nvm_get_os
}
die () { cleanup; echo "$@" ; exit 1; }
\. ../../../nvm.sh
ACTUAL="$(nvm_normalize_lts "foo")"
EXPECTED='foo'
[ "${ACTUAL}" = "${EXPECTED}" ] || die "expected >${EXPECTED}<, got >${ACTUAL}<"
ACTUAL="$(nvm_normalize_lts "lts/*")"
EXPECTED='lts/*'
[ "${ACTUAL}" = "${EXPECTED}" ] || die "expected >${EXPECTED}<, got >${ACTUAL}<"
MOCKS_DIR="../Unit tests/mocks"
STAR="$(cat "$MOCKS_DIR/lts-star.txt")"
ACTUAL="$(nvm_normalize_lts "${STAR}")"
EXPECTED="${STAR}"
[ "${ACTUAL}" = "${EXPECTED}" ] || die "expected >${EXPECTED}<, got >${ACTUAL}<"
LTS_NAMES_PATH="${MOCKS_DIR}/LTS_names.txt"
LTS_LIST="$(cat "${LTS_NAMES_PATH}" | tail -n +2)"
INDEX=1
for LTS in $LTS_LIST; do
ACTUAL="$(nvm_normalize_lts "lts/-${INDEX}")"
MESSAGE="for lts/-${INDEX}"
EXPECTED="lts/$(echo "${LTS_LIST}" | tail -n +${INDEX} | head -n1)"
[ "${ACTUAL}" = "${EXPECTED}" ] || die "${MESSAGE}: expected >${EXPECTED}<, got >${ACTUAL}<"
INDEX=$(($INDEX + 1))
done