-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathinstall.ps1
More file actions
416 lines (350 loc) · 13.5 KB
/
Copy pathinstall.ps1
File metadata and controls
416 lines (350 loc) · 13.5 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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
#!/usr/bin/env pwsh
# CAPA Installer Script for Windows
# Licensed under the MIT license
#
# NOTE: This installer is fetched over HTTPS but is not signed. For air-gapped
# or high-security environments, download install.ps1 + SHA256SUMS manually and
# verify before running.
param(
[string]$InstallDir = "",
[switch]$NoModifyPath = $false,
[switch]$Verbose = $false,
[switch]$Quiet = $false,
[switch]$Help = $false
)
$ErrorActionPreference = "Stop"
# Constants
$APP_NAME = "capa"
$GITHUB_REPO = "infragate/capa"
$FALLBACK_VERSION = "1.0.0" # Fallback version if API request fails
# Environment variable overrides
if ($env:CAPA_INSTALL_DIR) {
$InstallDir = $env:CAPA_INSTALL_DIR
}
if ($env:CAPA_NO_MODIFY_PATH -eq "1") {
$NoModifyPath = $true
}
if ($env:CAPA_UNMANAGED_INSTALL) {
$NoModifyPath = $true
}
if ($env:CAPA_PRINT_VERBOSE -eq "1") {
$Verbose = $true
}
if ($env:CAPA_PRINT_QUIET -eq "1") {
$Quiet = $true
}
# Colors
$ColorReset = "`e[0m"
$ColorRed = "`e[31m"
$ColorGreen = "`e[32m"
$ColorYellow = "`e[33m"
$ColorBlue = "`e[34m"
function Show-Usage {
Write-Host @"
capa-installer.ps1
The installer for CAPA (Capabilities Package Manager)
This script installs the CAPA binary to:
`$env:CAPA_INSTALL_DIR (if set)
`$env:LOCALAPPDATA\Programs\capa (default)
It will then add that directory to your PATH environment variable.
USAGE:
.\install.ps1 [OPTIONS]
Or via web:
powershell -ExecutionPolicy ByPass -c "irm https://capa.infragate.ai/install.ps1 | iex"
OPTIONS:
-InstallDir <DIR>
Install to a custom directory
-NoModifyPath
Don't configure the PATH environment variable
-Verbose
Enable verbose output
-Quiet
Disable progress output
-Help
Print help information
ENVIRONMENT VARIABLES:
CAPA_INSTALL_DIR Custom installation directory
CAPA_NO_MODIFY_PATH Set to 1 to skip PATH modification
CAPA_UNMANAGED_INSTALL Set to 1 for CI/unmanaged installs
CAPA_PRINT_VERBOSE Set to 1 for verbose output
CAPA_PRINT_QUIET Set to 1 for quiet output
EXAMPLES:
# Install with defaults
irm https://capa.infragate.ai/install.ps1 | iex
# Install to custom directory
`$env:CAPA_INSTALL_DIR="C:\Tools"; irm https://capa.infragate.ai/install.ps1 | iex
# Install without modifying PATH
powershell -c "irm https://capa.infragate.ai/install.ps1 | iex" -NoModifyPath
"@
}
function Write-Info {
param([string]$Message)
if (-not $Quiet) {
Write-Host "${ColorBlue}INFO${ColorReset}: $Message"
}
}
function Write-Success {
param([string]$Message)
if (-not $Quiet) {
Write-Host "${ColorGreen}✓${ColorReset} $Message"
}
}
function Write-Warning {
param([string]$Message)
if (-not $Quiet) {
Write-Host "${ColorYellow}WARN${ColorReset}: $Message" -ForegroundColor Yellow
}
}
function Write-Error-Custom {
param([string]$Message)
if (-not $Quiet) {
Write-Host "${ColorRed}ERROR${ColorReset}: $Message" -ForegroundColor Red
}
exit 1
}
function Write-Verbose-Custom {
param([string]$Message)
if ($Verbose) {
Write-Host $Message
}
}
function Get-LatestVersion {
try {
if ($Verbose) {
Write-Host "Fetching latest release version from GitHub..."
}
$apiUrl = "https://api.github.com/repos/$GITHUB_REPO/releases/latest"
$response = Invoke-RestMethod -Uri $apiUrl -UseBasicParsing -ErrorAction Stop
$version = $response.tag_name -replace '^v', ''
if ($Verbose) {
Write-Host "Latest version: $version"
}
return $version
}
catch {
if (-not $Quiet) {
Write-Host "${ColorYellow}WARN${ColorReset}: Failed to fetch latest version from GitHub API" -ForegroundColor Yellow
Write-Host "${ColorYellow}WARN${ColorReset}: Falling back to version $FALLBACK_VERSION" -ForegroundColor Yellow
}
return $FALLBACK_VERSION
}
}
function Get-Architecture {
$arch = $env:PROCESSOR_ARCHITECTURE
$arch64 = $env:PROCESSOR_ARCHITEW6432
if ($arch64) {
$arch = $arch64
}
switch ($arch) {
"AMD64" { return "x86_64-pc-windows-msvc" }
# ARM64: no native binary is shipped (bun-windows-arm64 compile target
# is unstable). Fall back to the x64 build, which Windows on ARM runs
# transparently via Prism emulation.
"ARM64" { return "x86_64-pc-windows-msvc" }
"x86" { return "i686-pc-windows-msvc" }
default {
Write-Error-Custom "Unsupported architecture: $arch"
}
}
}
function Get-InstallDirectory {
if ($InstallDir) {
return $InstallDir
}
$localAppData = $env:LOCALAPPDATA
if (-not $localAppData) {
Write-Error-Custom "Could not determine installation directory (LOCALAPPDATA not set)"
}
return Join-Path $localAppData "Programs\capa"
}
function Test-InPath {
param([string]$Directory)
$pathDirs = $env:PATH -split ";"
foreach ($dir in $pathDirs) {
if ($dir -eq $Directory) {
return $true
}
}
return $false
}
function Add-ToPath {
param([string]$Directory)
if ($NoModifyPath) {
return
}
if (Test-InPath $Directory) {
Write-Verbose-Custom "Directory already in PATH"
return
}
try {
Write-Info "Adding $Directory to PATH..."
# Get current user PATH
$userPath = [Environment]::GetEnvironmentVariable("PATH", "User")
# Add directory if not present
if ($userPath -notlike "*$Directory*") {
$newPath = "$Directory;$userPath"
[Environment]::SetEnvironmentVariable("PATH", $newPath, "User")
# Update current session
$env:PATH = "$Directory;$env:PATH"
Write-Success "Added to PATH"
}
}
catch {
Write-Warning "Failed to add to PATH: $_"
Write-Host "You may need to add $Directory to your PATH manually"
}
}
function Install-Capa {
# Fetch the latest version
$APP_VERSION = Get-LatestVersion
$bannerInner = 39
$bannerTitle = " CAPA Installer v$APP_VERSION"
$bannerPad = [Math]::Max(1, $bannerInner - $bannerTitle.Length)
$bannerSpaces = " " * $bannerPad
Write-Host ""
Write-Host "${ColorGreen}╔═══════════════════════════════════════╗${ColorReset}"
Write-Host "${ColorGreen}║${bannerTitle}${bannerSpaces}║${ColorReset}"
Write-Host "${ColorGreen}╚═══════════════════════════════════════╝${ColorReset}"
Write-Host ""
# Detect architecture
Write-Info "Detecting platform..."
$arch = Get-Architecture
Write-Success "Detected: $arch"
# Get installation directory
$installDir = Get-InstallDirectory
Write-Info "Installation directory: $installDir"
# Create installation directory
if (-not (Test-Path $installDir)) {
Write-Info "Creating installation directory..."
New-Item -ItemType Directory -Path $installDir -Force | Out-Null
}
# Determine binary name
$binaryName = "capa-$arch.exe"
$downloadUrl = "https://github.com/$GITHUB_REPO/releases/download/v$APP_VERSION/$binaryName"
$destPath = Join-Path $installDir "capa.exe"
# Download to temp first so we can replace the running exe when upgrading (fixes #19)
$tempPath = Join-Path $env:TEMP "capa-$APP_VERSION-$arch.exe"
Write-Info "Downloading CAPA..."
Write-Verbose-Custom "URL: $downloadUrl"
try {
$ProgressPreference = 'SilentlyContinue'
Invoke-WebRequest -Uri $downloadUrl -OutFile $tempPath -UseBasicParsing
Write-Success "Downloaded CAPA binary"
}
catch {
Write-Error-Custom "Failed to download CAPA from $downloadUrl`n$_"
}
# Verify binary integrity against release checksums
Write-Info "Verifying download integrity..."
$checksumsUrl = "https://github.com/$GITHUB_REPO/releases/download/v$APP_VERSION/SHA256SUMS.txt"
$checksumsPath = Join-Path $env:TEMP "capa-SHA256SUMS.txt"
try {
Invoke-WebRequest -Uri $checksumsUrl -OutFile $checksumsPath -UseBasicParsing
}
catch {
Remove-Item -LiteralPath $tempPath -Force -ErrorAction SilentlyContinue
Write-Error-Custom "Failed to download SHA256SUMS.txt from $checksumsUrl`n$_"
}
$computedHash = (Get-FileHash $tempPath -Algorithm SHA256).Hash.ToLower()
$expectedLine = Get-Content $checksumsPath | Where-Object { $_ -match (' ' + [regex]::Escape($binaryName) + '$') } | Select-Object -First 1
Remove-Item -LiteralPath $checksumsPath -Force -ErrorAction SilentlyContinue
if (-not $expectedLine) {
Remove-Item -LiteralPath $tempPath -Force -ErrorAction SilentlyContinue
Write-Error-Custom "No checksum found for $binaryName in SHA256SUMS.txt"
}
$expectedHash = ($expectedLine -split '\s+')[0].ToLower()
if ($computedHash -ne $expectedHash) {
Remove-Item -LiteralPath $tempPath -Force -ErrorAction SilentlyContinue
Write-Error-Custom "Checksum verification failed for $binaryName (expected $expectedHash, got $computedHash)"
}
Write-Success "Verified binary integrity"
# Replace existing binary (fixes #19). On Windows a running .exe is locked
# and cannot be overwritten, but it *can* be renamed within the same
# directory while it runs (the OS keeps the file handle regardless of name).
# So move the old binary aside first — that frees $destPath — then drop the
# new binary in. This makes the upgrade succeed even if the previous capa
# process hasn't fully exited yet, instead of relying on a timing race.
$backupPath = "$destPath.old"
if (Test-Path $destPath) {
# Remove any leftover backup from a prior upgrade (best-effort; harmless
# if it's still locked — it'll be cleaned on the next run).
if (Test-Path $backupPath) {
Remove-Item -LiteralPath $backupPath -Force -ErrorAction SilentlyContinue
}
try {
Move-Item -Path $destPath -Destination $backupPath -Force
}
catch {
# Rename of a locked exe normally succeeds; if it somehow didn't,
# fall through and let the retry loop attempt a direct replace.
Write-Verbose-Custom "Could not rename existing binary aside: $_"
}
}
# Move the new binary into place. If the rename above succeeded, $destPath is
# free and this lands on the first try. The retry loop is a fallback for the
# rare case the destination is still occupied (e.g. rename failed).
$replaceOk = $false
$maxRetries = 5
$retryDelaySeconds = 2
for ($attempt = 1; $attempt -le $maxRetries; $attempt++) {
try {
Move-Item -Path $tempPath -Destination $destPath -Force
$replaceOk = $true
break
}
catch {
if ($_.Exception.Message -match 'being used by another process' -and $attempt -lt $maxRetries) {
Write-Info "File in use; retrying in ${retryDelaySeconds}s ($attempt/$maxRetries)..."
Start-Sleep -Seconds $retryDelaySeconds
}
else {
Remove-Item -LiteralPath $tempPath -Force -ErrorAction SilentlyContinue
# Restore the original binary if we renamed it aside but couldn't
# install the new one, so the user isn't left without a capa.exe.
if ((-not (Test-Path $destPath)) -and (Test-Path $backupPath)) {
Move-Item -Path $backupPath -Destination $destPath -Force -ErrorAction SilentlyContinue
}
Write-Error-Custom "Could not replace $destPath. Close any process using it and run the installer again, or run: capa upgrade"
}
}
}
if (-not $replaceOk) {
exit 1
}
# New binary is in place; clean up the old one. This will fail silently if
# the previous capa process is still running (the file stays locked) — the
# leftover .old is then removed by the next upgrade.
if (Test-Path $backupPath) {
Remove-Item -LiteralPath $backupPath -Force -ErrorAction SilentlyContinue
}
Write-Success "Installed CAPA to $destPath"
# Add to PATH
Add-ToPath $installDir
# Print success message
Write-Host ""
Write-Host "${ColorGreen}╔═══════════════════════════════════════╗${ColorReset}"
Write-Host "${ColorGreen}║ CAPA installed successfully! 🎉 ║${ColorReset}"
Write-Host "${ColorGreen}╚═══════════════════════════════════════╝${ColorReset}"
Write-Host ""
Write-Host "To get started, run:"
Write-Host " ${ColorBlue}capa init${ColorReset} # Initialize a new project"
Write-Host " ${ColorBlue}capa --help${ColorReset} # Show all commands"
Write-Host ""
if (-not $NoModifyPath) {
Write-Host "${ColorYellow}Note:${ColorReset} You may need to restart your terminal for PATH changes to take effect."
Write-Host ""
}
Write-Host "Documentation: https://github.com/$GITHUB_REPO"
Write-Host ""
}
# Main execution
try {
if ($Help) {
Show-Usage
exit 0
}
Install-Capa
}
catch {
Write-Error-Custom "Installation failed: $_"
}