-
Notifications
You must be signed in to change notification settings - Fork 0
/
upgradenode
executable file
·100 lines (86 loc) · 2.07 KB
/
upgradenode
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#!/usr/bin/env bash
declare -r esc=$'\033'
declare -r c_reset="${esc}[0m"
declare -r c_red="${esc}[31m"
ask() {
read -r -p "$1 " -n1 ans
echo
[[ "${ans^}" == Y ]]
}
err() {
printf "${c_red}%s${c_reset}\n" "$*" >&2
}
die() {
[[ -n "$1" ]] && err "$1"
exit 1
}
has() {
local verbose=false
if [[ $1 == '-v' ]]; then
verbose=true
shift
fi
for c in "$@"; do c="${c%% *}"
if ! command -v "$c" &> /dev/null; then
[[ "$verbose" == true ]] && err "$c not found"
return 1
fi
done
}
confirm_cmd() {
if ask "$*?"; then
"$@"
fi
}
check_hash() {
file="$1"
latest="$2"
remotehash=$(grep "${file##*/}" <<< "$latest")
remotehash=${remotehash%% *}
localhash=$(sha256sum "$file")
localhash=${localhash%% *}
if [[ "$remotehash" != "$localhash" ]]; then
err 'hash mismatch!';
die 1
fi
}
has -v curl || die
declare path="$HOME"
if [[ -d $1 ]]; then
path=$1
fi
cputype=$(uname --machine)
echo 'checking latest node version...'
latest=$(curl -sL 'https://nodejs.org/dist/latest/SHASUMS256.txt')
name=$(grep -m1 -o -P 'node-v[^-]+-linux-x'"${cputype:(-2)}" <<< "$latest")
if has node; then
current=$(node --version)
newver=$(grep -oP 'v[0-9]+\.[0-9]+\.[0-9]+' <<< "$name")
if [[ "${current}" == "${newver}" ]]; then
echo 'up-to-date'
exit 0
else
echo "${current} reported, ${newver} available"
fi
fi
declare file="${path}/${name}.tar.xz"
if [[ ! -e "${file}" ]]; then
confirm_cmd curl -LO "https://nodejs.org/dist/latest/${name}.tar.xz" -o "$file"
[[ -e "$file" ]] && check_hash "$file" "$latest"
fi
if [[ ! -e "${file}" ]]; then
echo "$path"
if [[ -e "${path}/node*.tar.xz" ]]; then
file=$(realpath "${path}node*.tar.xz" | sort -h | head -n1)
fi
echo "$file"
fi
if [[ -e "$file" ]]; then
echo "installing $file"
mkdir -p "${HOME}/build"
tar -x -f "$file" -C "${HOME}/build/" || die
mv "${HOME}/build"/node*/bin/* "${HOME}/.local/bin/"
rm -fr "${HOME}/.local"/{lib/node_modules,include/node}
cp -R "${HOME}/build/node"*/{lib,share,include} "${HOME}/.local/"
rm -fr "${HOME}/build/$name"
fi