-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathinstall.ps1
More file actions
291 lines (247 loc) · 12.5 KB
/
Copy pathinstall.ps1
File metadata and controls
291 lines (247 loc) · 12.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
# Installer for Dispatch — a Go TUI launcher for GitHub Copilot CLI extensions.
#
# Usage:
# irm https://raw.githubusercontent.com/jongio/dispatch/main/install.ps1 | iex
# $v="v0.1.0"; irm https://raw.githubusercontent.com/jongio/dispatch/main/install.ps1 | iex
# $env:VERSION = "v0.1.0"; irm https://raw.githubusercontent.com/jongio/dispatch/main/install.ps1 | iex
# .\install.ps1 -Version v0.1.0
#
# Parameters:
# -Version Version to install (e.g. v0.1.0, 0.1.0). Defaults to latest.
#
# Environment variables:
# VERSION Override the version to install (e.g. v0.1.0). Defaults to latest.
# The -Version parameter and $v variable take precedence.
$ErrorActionPreference = 'Stop'
# ---------------------------------------------------------------------------
# Configuration
# ---------------------------------------------------------------------------
$Script:Repo = 'jongio/dispatch'
$Script:BinaryName = 'dispatch.exe'
$Script:ChecksumsFile = 'dispatch_checksums.txt'
$Script:GitHubDownload = "https://github.com/$Script:Repo/releases/download"
# ---------------------------------------------------------------------------
# Output helpers
# ---------------------------------------------------------------------------
function Write-Status { param([string]$Message) Write-Host " -> $Message" -ForegroundColor Cyan }
function Write-Success { param([string]$Message) Write-Host " OK $Message" -ForegroundColor Green }
function Write-Warn { param([string]$Message) Write-Host " !! $Message" -ForegroundColor Yellow }
function Write-Fail { param([string]$Message) throw $Message }
# ---------------------------------------------------------------------------
# Architecture detection
# ---------------------------------------------------------------------------
function Get-DispatchArch {
# Prefer .NET RuntimeInformation (PS 6+, or PS 5.1 on .NET 4.7.1+).
try {
$procArch = [System.Runtime.InteropServices.RuntimeInformation]::ProcessArchitecture
switch ($procArch.ToString()) {
'X64' { return 'amd64' }
'Arm64' { return 'arm64' }
default { Write-Fail "Unsupported process architecture: $procArch" }
}
}
catch {
# Fallback for older .NET Framework — use environment variable.
switch ($env:PROCESSOR_ARCHITECTURE) {
'AMD64' { return 'amd64' }
'ARM64' { return 'arm64' }
'x86' { Write-Fail '32-bit Windows is not supported. Please use 64-bit PowerShell.' }
default { Write-Fail "Unsupported processor architecture: $env:PROCESSOR_ARCHITECTURE" }
}
}
}
# ---------------------------------------------------------------------------
# Version resolution
# ---------------------------------------------------------------------------
function Get-DispatchVersion {
# Priority: $v variable (one-liner friendly) > $env:VERSION > latest from GitHub.
# $v is set by: $v="v0.1.0"; irm ... | iex
$requestedVersion = if ($v) { $v } elseif ($env:VERSION) { $env:VERSION } else { $null }
if ($requestedVersion) {
$ver = $requestedVersion.ToString().Trim()
# Normalise: ensure the tag starts with "v".
if (-not $ver.StartsWith('v')) { $ver = "v$ver" }
return $ver
}
Write-Status 'Querying GitHub for latest release...'
# Use the releases/latest redirect - no auth required, no API rate limit.
$redirectUrl = "https://github.com/$Script:Repo/releases/latest"
try {
$response = Invoke-WebRequest -Uri $redirectUrl -UseBasicParsing -MaximumRedirection 5
$finalUrl = $response.BaseResponse.RequestMessage.RequestUri.ToString()
if (-not $finalUrl) {
# PS 5.1: ResponseUri is on BaseResponse directly.
$finalUrl = $response.BaseResponse.ResponseUri.ToString()
}
if ($finalUrl -match '/tag/([^/]+)$') {
return $Matches[1]
}
}
catch {}
Write-Fail 'Could not determine the latest version. Set $env:VERSION and retry.'
}
# ---------------------------------------------------------------------------
# PATH management
# ---------------------------------------------------------------------------
function Add-ToUserPath {
param([string]$Directory)
$normalised = $Directory.TrimEnd('\')
# --- Persistent user PATH (registry) ---
$userPath = [System.Environment]::GetEnvironmentVariable('PATH', [System.EnvironmentVariableTarget]::User)
if (-not $userPath) { $userPath = '' }
$entries = $userPath -split ';' |
ForEach-Object { $_.Trim().TrimEnd('\') } |
Where-Object { $_ -ne '' }
if ($entries -and ($entries | Where-Object { $_ -ieq $normalised })) {
Write-Status 'Install directory already in user PATH'
}
else {
$newPath = if ($userPath.TrimEnd(';')) { "$($userPath.TrimEnd(';'));$Directory" } else { $Directory }
[System.Environment]::SetEnvironmentVariable('PATH', $newPath, [System.EnvironmentVariableTarget]::User)
Write-Success 'Added to user PATH'
}
# --- Current-session PATH ---
$sessionEntries = $env:PATH -split ';' |
ForEach-Object { $_.Trim().TrimEnd('\') } |
Where-Object { $_ -ne '' }
if (-not ($sessionEntries | Where-Object { $_ -ieq $normalised })) {
$env:PATH = "$env:PATH;$Directory"
}
}
# ---------------------------------------------------------------------------
# Main installer
# ---------------------------------------------------------------------------
function Install-Dispatch {
# Ensure TLS 1.2 — PowerShell 5.1 defaults to TLS 1.0 which GitHub rejects.
[Net.ServicePointManager]::SecurityProtocol =
[Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12
# Suppress the progress bar so Invoke-WebRequest doesn't crawl in PS 5.1.
$prevProgressPref = $ProgressPreference
$ProgressPreference = 'SilentlyContinue'
$installDir = Join-Path $env:LOCALAPPDATA 'Programs\dispatch'
$tempDir = Join-Path ([System.IO.Path]::GetTempPath()) "dispatch-install-$([guid]::NewGuid().ToString('N').Substring(0, 8))"
try {
Write-Host ''
Write-Host ' Dispatch Installer' -ForegroundColor White
Write-Host ''
# ---- Platform --------------------------------------------------------
$arch = Get-DispatchArch
Write-Status "Detected platform: windows/$arch"
# ---- Version ---------------------------------------------------------
$tag = Get-DispatchVersion
$version = $tag.TrimStart('v') # strip leading "v" for filename
Write-Success "Version: $tag"
# ---- Build URLs ------------------------------------------------------
$archiveName = "dispatch_${version}_windows_${arch}.zip"
$archiveUrl = "$Script:GitHubDownload/$tag/$archiveName"
$checksumsUrl = "$Script:GitHubDownload/$tag/$Script:ChecksumsFile"
# ---- Temp directory --------------------------------------------------
New-Item -ItemType Directory -Path $tempDir -Force | Out-Null
$archivePath = Join-Path $tempDir $archiveName
$checksumsPath = Join-Path $tempDir $Script:ChecksumsFile
# ---- Download --------------------------------------------------------
Write-Status "Downloading $archiveName..."
Invoke-WebRequest -Uri $archiveUrl -OutFile $archivePath -UseBasicParsing
Write-Status "Downloading checksums..."
Invoke-WebRequest -Uri $checksumsUrl -OutFile $checksumsPath -UseBasicParsing
Write-Success 'Downloaded archive'
# ---- Verify cosign signature on checksums file -----------------------
$cosignCmd = Get-Command cosign -ErrorAction SilentlyContinue
if ($cosignCmd) {
Write-Status 'Verifying cosign signature on checksums file...'
$sigUrl = "$Script:GitHubDownload/$tag/$($Script:ChecksumsFile).sig"
$pemUrl = "$Script:GitHubDownload/$tag/$($Script:ChecksumsFile).pem"
$sigPath = Join-Path $tempDir "$($Script:ChecksumsFile).sig"
$pemPath = Join-Path $tempDir "$($Script:ChecksumsFile).pem"
Invoke-WebRequest -Uri $sigUrl -OutFile $sigPath -UseBasicParsing
Invoke-WebRequest -Uri $pemUrl -OutFile $pemPath -UseBasicParsing
$cosignArgs = @(
'verify-blob'
'--signature', $sigPath
'--certificate', $pemPath
'--certificate-identity-regexp', "^https://github\.com/$Script:Repo/"
'--certificate-oidc-issuer', 'https://token.actions.githubusercontent.com'
$checksumsPath
)
$cosignResult = & cosign @cosignArgs 2>&1
if ($LASTEXITCODE -ne 0) {
Write-Fail "Cosign signature verification failed. The checksums file may have been tampered with.`n$cosignResult"
}
Write-Success 'Cosign signature verified'
}
else {
Write-Warn 'cosign not found - skipping signature verification. Install cosign for supply-chain security.'
}
# ---- Verify checksum -------------------------------------------------
Write-Status 'Verifying SHA-256 checksum...'
# Parse the checksums file for the matching archive entry.
$checksumLine = Get-Content $checksumsPath |
Where-Object {
$fields = $_.Trim() -split '\s+'
$fields.Count -ge 2 -and $fields[-1] -eq $archiveName
} |
Select-Object -First 1
if (-not $checksumLine) {
Write-Fail "Archive '$archiveName' not found in $($Script:ChecksumsFile)."
}
$expectedHash = ($checksumLine.Trim() -split '\s+')[0]
$actualHash = (Get-FileHash -Path $archivePath -Algorithm SHA256).Hash
if ($actualHash -ine $expectedHash) {
Write-Fail "Checksum mismatch!`n Expected: $expectedHash`n Got: $actualHash"
}
Write-Success 'Checksum verified'
# ---- Extract ---------------------------------------------------------
Write-Status 'Extracting...'
$extractDir = Join-Path $tempDir 'extract'
Expand-Archive -Path $archivePath -DestinationPath $extractDir -Force
# Find the binary (handles both flat and nested archive layouts).
$binary = Get-ChildItem -Path $extractDir -Filter $Script:BinaryName -Recurse |
Select-Object -First 1
if (-not $binary) {
Write-Fail "$($Script:BinaryName) not found in the downloaded archive."
}
Write-Success "Extracted $($Script:BinaryName)"
# ---- Install ---------------------------------------------------------
if (-not (Test-Path $installDir)) {
New-Item -ItemType Directory -Path $installDir -Force | Out-Null
}
Copy-Item -Path $binary.FullName -Destination (Join-Path $installDir $Script:BinaryName) -Force
Copy-Item -Path $binary.FullName -Destination (Join-Path $installDir 'disp.exe') -Force
Write-Success "Installed to $installDir (dispatch.exe + disp.exe alias)"
# ---- PATH ------------------------------------------------------------
Add-ToUserPath -Directory $installDir
# ---- Verify installation ---------------------------------------------
$dispatchCmd = Get-Command dispatch -ErrorAction SilentlyContinue
if ($dispatchCmd) {
$installedVersion = & dispatch --version 2>$null
if ($installedVersion) {
Write-Success "Verified: $installedVersion"
}
}
# ---- Done ------------------------------------------------------------
Write-Host ''
Write-Host " Dispatch $tag installed successfully!" -ForegroundColor Green
Write-Host ' Run ''dispatch'' to get started.' -ForegroundColor Cyan
Write-Host ''
Write-Warn 'Restart your terminal if ''dispatch'' is not recognized.'
Write-Host ''
}
catch {
Write-Host ''
Write-Host " Error: $($_.Exception.Message)" -ForegroundColor Red
Write-Host ''
# Re-throw so the caller sees a non-zero exit / terminating error.
# Without this, 'irm | iex' silently succeeds even on failure.
throw
}
finally {
# Clean up temp files.
if (Test-Path $tempDir) {
Remove-Item -Path $tempDir -Recurse -Force -ErrorAction SilentlyContinue
}
# Restore progress preference.
$ProgressPreference = $prevProgressPref
}
}
# Entry point — supports both direct execution and piped (irm | iex) usage.
Install-Dispatch