Skip to content

Commit f279837

Browse files
committed
[Refactor] fix some bugs in nvm_is_natural_num, add unit tests.
1 parent 32d1840 commit f279837

File tree

2 files changed

+28
-12
lines changed

2 files changed

+28
-12
lines changed

nvm.sh

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1240,9 +1240,7 @@ nvm_install_node_source() {
12401240
elif [ "_$NVM_OS" = "_sunos" ]; then
12411241
NVM_CPU_THREADS="$(psrinfo | wc -l)"
12421242
fi
1243-
local NVM_CPU_THREAD_VALID
1244-
NVM_CPU_THREAD_VALID=$(nvm_is_natural_num $NVM_CPU_THREADS)
1245-
if [ -z "$NVM_CPU_THREADS" ] || [ "$NVM_CPU_THREAD_VALID" != "true" ] ; then
1243+
if [ ! nvm_is_natural_num "$NVM_CPU_THREADS" ] ; then
12461244
echo "Can not determine how many thread(s) we can use, set to only 1 now." 1>&2
12471245
echo "Please report an issue on GitHub to help us make it better and run it faster on your computer!" 1>&2
12481246
NVM_MAKE_JOBS="1"
@@ -1457,13 +1455,16 @@ nvm_sanitize_path() {
14571455
}
14581456

14591457
nvm_is_natural_num() {
1460-
echo $1 | command egrep -q '^[0-9]{1,}$' &> /dev/null
1461-
local IS_NATURAL_NUM=$?
1462-
if [ "$IS_NATURAL_NUM" = "0" ]; then
1463-
echo true
1464-
else
1465-
echo false
1458+
if [ -z "$1" ]; then
1459+
return 4
14661460
fi
1461+
case "$1" in
1462+
0) return 1 ;;
1463+
-*) return 3 ;; # some BSDs return false positives for double-negated args
1464+
*)
1465+
[ $1 -eq $1 2> /dev/null ] # returns 2 if it doesn't match
1466+
;;
1467+
esac
14671468
}
14681469

14691470
nvm() {
@@ -1586,9 +1587,7 @@ nvm() {
15861587
;;
15871588
-j)
15881589
shift # consume "-j"
1589-
local NVM_CPU_THREAD_VALID
1590-
NVM_CPU_THREAD_VALID=$(nvm_is_natural_num $1)
1591-
if [ "$NVM_CPU_THREAD_VALID" = "true" ]; then
1590+
if [ nvm_is_natural_num "$1" ]; then
15921591
NVM_MAKE_JOBS=$1
15931592
echo "number of \`make\` jobs: $NVM_MAKE_JOBS"
15941593
else
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
#!/bin/sh
2+
3+
die () { echo $@ ; exit 1; }
4+
5+
. ../../../nvm.sh
6+
7+
! nvm_is_natural_num || die 'no args is not false'
8+
! nvm_is_natural_num '' || die 'empty string is not false'
9+
! nvm_is_natural_num a || die 'a is not false'
10+
! nvm_is_natural_num -1 || 'negative number is not false'
11+
! nvm_is_natural_num --1 || 'double negative number is not false'
12+
! nvm_is_natural_num 1.2 || 'decimal number is not false'
13+
! nvm_is_natural_num 0 || die 'zero is not false'
14+
15+
nvm_is_natural_num 1 || die '1 is not true'
16+
nvm_is_natural_num 2 || die '2 is not true'
17+
nvm_is_natural_num 1234 || die '1234 is not true'

0 commit comments

Comments
 (0)