-
Notifications
You must be signed in to change notification settings - Fork 56
Expand file tree
/
Copy pathinstall.ps1
More file actions
226 lines (205 loc) · 10.4 KB
/
Copy pathinstall.ps1
File metadata and controls
226 lines (205 loc) · 10.4 KB
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
#!/usr/bin/env pwsh
# Nub installer for Windows (PowerShell)
# Usage: irm https://raw.githubusercontent.com/nubjs/nub/main/install.ps1 | iex
#
# Customization (env vars):
# NUB_INSTALL_DIR install location, absolute path (default: %USERPROFILE%\.nub)
# NUB_NO_MODIFY_PATH truthy (1/yes/true/on) to skip editing the User PATH
$ErrorActionPreference = "Stop"
# --- Platform detection ---
$Arch = [System.Runtime.InteropServices.RuntimeInformation]::OSArchitecture
switch ($Arch) {
"X64" { $Target = "win32-x64" }
"Arm64" { $Target = "win32-arm64" }
default { Write-Error "Unsupported architecture: $Arch"; exit 1 }
}
# --- Version ---
$Version = if ($args.Count -gt 0) { $args[0] } else { "latest" }
if ($Version -eq "canary") {
# The rolling canary prerelease — rebuilt from every commit to main and
# published under the un-versioned `canary` tag, so there is no version to
# resolve. May be broken; `nub upgrade --stable` returns to a release.
$ReleaseTag = "canary"
$DisplayVersion = "canary"
} else {
if ($Version -eq "latest") {
# Authenticate the GitHub API call when a token is available: CI runners share
# an IP and hit the 60/hr unauthenticated rate limit (403). Real users without
# GITHUB_TOKEN use the anonymous path unchanged.
$apiHeaders = @{}
if ($env:GITHUB_TOKEN) { $apiHeaders["Authorization"] = "token $env:GITHUB_TOKEN" }
$Release = Invoke-RestMethod "https://api.github.com/repos/nubjs/nub/releases/latest" -Headers $apiHeaders
$Version = $Release.tag_name -replace "^v", ""
}
$ReleaseTag = "v$Version"
$DisplayVersion = "v$Version"
}
Write-Host "Installing nub $DisplayVersion for $Target..." -ForegroundColor Cyan
# --- Install ---
# The install location is overridable via NUB_INSTALL_DIR (default %USERPROFILE%\.nub).
# Both the resolved dir and the default are normalized to full paths so the
# "is this the default location?" test below is an exact comparison.
$DefaultInstallDir = [System.IO.Path]::GetFullPath("$env:USERPROFILE\.nub")
$InstallDir = if ($env:NUB_INSTALL_DIR) { $env:NUB_INSTALL_DIR } else { $DefaultInstallDir }
New-Item -ItemType Directory -Force -Path $InstallDir | Out-Null
$InstallDir = (Resolve-Path -LiteralPath $InstallDir).Path
$BinDir = "$InstallDir\bin"
$Exe = "$BinDir\nub.exe"
# Download the per-platform archive and extract it into the install dir. nub is a
# single self-contained binary that embeds its runtime (preload + vendored
# node_modules + native addon) and JIT-extracts it to the user cache on first run.
# The archive ships bin\ plus a vestigial empty runtime\ (kept only to satisfy the
# sidecar-era `nub upgrade`; the binary ignores it — see release.yml).
$ArchiveName = "nub-$Target.zip"
$Url = "https://github.com/nubjs/nub/releases/download/$ReleaseTag/$ArchiveName"
$ChecksumUrl = "$Url.sha256"
Write-Host "Downloading from $Url..."
$TmpZip = Join-Path $env:TEMP "nub-$Target-$PID.zip"
$TmpChecksum = Join-Path $env:TEMP "nub-$Target-$PID.zip.sha256"
# Suppress the per-chunk progress bar — it re-renders on every received byte
# and dominates the total download time in PowerShell.
$prevProgressPreference = $ProgressPreference
try {
$ProgressPreference = 'SilentlyContinue'
Invoke-WebRequest -Uri $Url -OutFile $TmpZip -UseBasicParsing
Invoke-WebRequest -Uri $ChecksumUrl -OutFile $TmpChecksum -UseBasicParsing
# The sidecar detects corrupt, truncated, stale-cache, or mismatched assets. It
# is not an independent authenticity check because both files share an origin.
$ChecksumBytes = [System.IO.File]::ReadAllBytes($TmpChecksum)
$ChecksumText = [System.Text.Encoding]::ASCII.GetString($ChecksumBytes)
$ChecksumPattern = "\A(?<Digest>[0-9A-Fa-f]{64}) $([regex]::Escape($ArchiveName))`n\z"
if ($ChecksumText -cnotmatch $ChecksumPattern) {
throw "Malformed checksum from: $ChecksumUrl"
}
$ExpectedSha256 = $Matches["Digest"]
$ActualSha256 = (Get-FileHash -LiteralPath $TmpZip -Algorithm SHA256).Hash
if (-not [string]::Equals($ActualSha256, $ExpectedSha256, [System.StringComparison]::OrdinalIgnoreCase)) {
throw "Checksum mismatch for $Url (expected $ExpectedSha256, got $ActualSha256). Refusing to install a corrupt or mismatched archive."
}
# Replace any prior nub artifacts for a clean upgrade. In the default ~\.nub —
# which nub owns outright — drop the whole bin\ and a stale runtime\ from a
# pre-single-binary install. A user-supplied NUB_INSTALL_DIR may hold unrelated
# files, so there remove only the two executables we wrote. Then extract bin\.
if ($InstallDir -ieq $DefaultInstallDir) {
if (Test-Path $BinDir) { Remove-Item -Recurse -Force $BinDir }
if (Test-Path "$InstallDir\runtime") { Remove-Item -Recurse -Force "$InstallDir\runtime" }
} else {
Remove-Item -Force -ErrorAction SilentlyContinue -LiteralPath "$BinDir\nub.exe", "$BinDir\nubx.exe"
}
Expand-Archive -Path $TmpZip -DestinationPath $InstallDir -Force
} catch {
Write-Error "Failed to download/verify/extract nub: $_"
exit 1
} finally {
$ProgressPreference = $prevProgressPreference
if (Test-Path $TmpZip) { Remove-Item -Force $TmpZip }
if (Test-Path $TmpChecksum) { Remove-Item -Force $TmpChecksum }
}
if (-not (Test-Path $Exe)) {
Write-Error "Archive did not contain bin\nub.exe"
exit 1
}
# `nubx` is the same binary as `nub`, dispatched on argv[0] (cli.rs reads
# args_os()[0].file_stem(): "nubx" -> exec). The release archive ships only
# bin\nub.exe, so create the nubx alias. On Windows we COPY rather than symlink:
# symlinks require admin/Developer Mode, and a copy reliably yields argv[0]
# "nubx.exe". Re-extract on upgrade wipes bin\, so this is recreated each run.
$Exex = "$BinDir\nubx.exe"
Copy-Item -Path $Exe -Destination $Exex -Force
# `nub pm shim` HARDLINKS %USERPROFILE%\.nub\shims\{npm,npx,…}.exe at the nub
# binary, so the re-extract above left every one of them pinned to the previous
# version's inode. That fails silently — `npm --version` keeps reporting the old
# nub, with no error and no warning — which is worse than any loud breakage.
# `nub upgrade` re-links after its swap and so does the npm postinstall; this
# installer did not, so the irm channel was the one upgrade path that stranded them.
#
# Mirrors refreshShims in npm/nub/postinstall.js: refresh-only (never CREATE a shim
# the user did not opt into via `nub pm shim`), best-effort, and yields to a live
# `nub pm shim` rather than interleaving with it. The shim dir hangs off the user
# profile regardless of NUB_INSTALL_DIR — see shim_dir() in
# crates/nub-core/src/pm/shim.rs.
function Update-NubPmShims {
param([string] $NubExe)
$shimDir = "$env:USERPROFILE\.nub\shims"
$lock = "$env:USERPROFILE\.nub\shims.lock"
if (-not (Test-Path -LiteralPath $shimDir -PathType Container)) { return }
# shim.rs's lock protocol: create exclusively, steal one whose holder died
# (mtime older than 30s), and skip entirely while a live `nub pm shim` holds it.
$handle = $null
try {
$handle = [System.IO.File]::Open($lock, 'CreateNew', 'Write')
} catch {
$stale = $true # an unreadable mtime counts as stale, as in postinstall.js
try {
$stale = ((Get-Date) - (Get-Item -LiteralPath $lock).LastWriteTime).TotalSeconds -gt 30
} catch {}
if (-not $stale) { return }
try {
Remove-Item -Force -LiteralPath $lock
$handle = [System.IO.File]::Open($lock, 'CreateNew', 'Write')
} catch { return }
}
$refreshed = 0
try {
foreach ($name in @('npm', 'npx', 'pnpm', 'pnpx', 'yarn', 'yarnpkg')) {
$target = "$shimDir\$name.exe"
if (-not (Test-Path -LiteralPath $target)) { continue }
try {
# A hardlink costs no disk; a shim dir on another volume cannot be
# linked, so fall back to a copy. `-Value` rather than `-Target`:
# Windows PowerShell 5.1 has no -Target on New-Item.
Remove-Item -Force -LiteralPath $target
try {
New-Item -ItemType HardLink -Path $target -Value $NubExe -Force | Out-Null
} catch {
Copy-Item -LiteralPath $NubExe -Destination $target -Force
}
$refreshed++
} catch {
# A running shim holds its own file open — degraded, not broken.
}
}
} finally {
if ($handle) { $handle.Close() }
Remove-Item -Force -ErrorAction SilentlyContinue -LiteralPath $lock
}
if ($refreshed -gt 0) {
Write-Host "Refreshed $refreshed nub shim(s) in $shimDir"
}
}
Update-NubPmShims -NubExe $Exe
# Install receipt: marks this dir as a nub self-managed install so `nub upgrade`
# recognizes it as in-place-upgradeable even when NUB_INSTALL_DIR relocated it out
# of the default ~\.nub (cli.rs detect_channel checks for this file).
$Receipt = @'
# This file marks a nub self-managed install so `nub upgrade` can update it in
# place. Created by the nub installer; safe to delete (deleting it disables
# in-place self-update for a non-default install location).
'@
Set-Content -LiteralPath "$InstallDir\.nub-receipt" -Value $Receipt
Write-Host "Installed nub (with nubx) to $Exe" -ForegroundColor Green
# --- PATH setup ---
# Honor NUB_NO_MODIFY_PATH: skip the User PATH edit and just print the dir to add
# (rustup/uv convention).
$NoModifyPath = "$env:NUB_NO_MODIFY_PATH".ToLowerInvariant()
if ($NoModifyPath -in @("1", "yes", "true", "on")) {
Write-Host "Add the nub bin path to your PATH:"
Write-Host " $BinDir" -ForegroundColor White
exit 0
} elseif ($NoModifyPath -notin @("", "0", "no", "false", "off")) {
Write-Error "Invalid NUB_NO_MODIFY_PATH: $env:NUB_NO_MODIFY_PATH (expected 1/yes/true/on or 0/no/false/off)"
exit 1
}
$UserPath = [Environment]::GetEnvironmentVariable("Path", "User")
# Compare against the exact segments rather than a substring match: a custom
# NUB_INSTALL_DIR could be a substring of an unrelated existing entry.
if (($UserPath -split ';') -notcontains $BinDir) {
[Environment]::SetEnvironmentVariable("Path", "$BinDir;$UserPath", "User")
$env:Path = "$BinDir;$env:Path"
Write-Host "Added $BinDir to PATH" -ForegroundColor Green
} else {
Write-Host "Already in PATH" -ForegroundColor Green
}
Write-Host ""
Write-Host "To get started, open a new terminal and run:" -ForegroundColor Cyan
Write-Host " nub --version" -ForegroundColor White