Skip to content

Commit

Permalink
[Fix] nvm_get_default_packages: use awk for more reliable file pr…
Browse files Browse the repository at this point in the history
…ocessing
  • Loading branch information
ljharb committed Jul 28, 2024
1 parent f439acd commit 458da17
Showing 1 changed file with 14 additions and 29 deletions.
43 changes: 14 additions & 29 deletions nvm.sh
Original file line number Diff line number Diff line change
Expand Up @@ -4436,37 +4436,22 @@ nvm() {
}

nvm_get_default_packages() {
local NVM_DEFAULT_PACKAGE_FILE="${NVM_DIR}/default-packages"
local NVM_DEFAULT_PACKAGE_FILE
NVM_DEFAULT_PACKAGE_FILE="${NVM_DIR}/default-packages"
if [ -f "${NVM_DEFAULT_PACKAGE_FILE}" ]; then
local DEFAULT_PACKAGES
DEFAULT_PACKAGES=''

# Read lines from $NVM_DIR/default-packages
local line
# ensure a trailing newline
WORK=$(mktemp -d) || exit $?
# shellcheck disable=SC2064
trap "command rm -rf '$WORK'" EXIT
# shellcheck disable=SC1003
sed -e '$a\' "${NVM_DEFAULT_PACKAGE_FILE}" > "${WORK}/default-packages"
while IFS=' ' read -r line; do
# Skip empty lines.
[ -n "${line-}" ] || continue

# Skip comment lines that begin with `#`.
[ "$(nvm_echo "${line}" | command cut -c1)" != "#" ] || continue

# Fail on lines that have multiple space-separated words
case $line in
*\ *)
nvm_err "Only one package per line is allowed in the ${NVM_DIR}/default-packages file. Please remove any lines with multiple space-separated values."
return 1
;;
esac
command awk '
/^[[:space:]]*#/ { next } # Skip lines that begin with #
/^[[:space:]]*$/ { next } # Skip empty lines
/[[:space:]]/ && !/^[[:space:]]*#/ {
print "Only one package per line is allowed in the ${NVM_DIR}/default-packages file. Please remove any lines with multiple space-separated values."
err = 1
next
}
{ print } # Print remaining lines
END { if (err) exit 1 }
' "$NVM_DEFAULT_PACKAGE_FILE"

DEFAULT_PACKAGES="${DEFAULT_PACKAGES}${line} "
done < "${WORK}/default-packages"
echo "${DEFAULT_PACKAGES}" | command xargs
return $?
fi
}

Expand Down

0 comments on commit 458da17

Please sign in to comment.