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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
|
[CmdletBinding()]
param(
[string]$Channel = $env:HERDR_CHANNEL,
[string]$ManifestUrl = $env:HERDR_MANIFEST_URL,
[string]$InstallDir = $env:HERDR_INSTALL_DIR,
[string]$ExpectedBuildId = $env:HERDR_EXPECTED_BUILD_ID,
[int]$Retain = 3
)
Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
$ProgressPreference = "SilentlyContinue"
if ([string]::IsNullOrWhiteSpace($Channel)) {
$Channel = "preview"
}
if ($Channel -notin @("stable", "preview")) {
Write-Error "Invalid Herdr channel '$Channel'. Use 'preview'."
exit 1
}
function Write-Step {
param([string]$Message)
Write-Host "==> $Message"
}
function Write-WarningStep {
param([string]$Message)
Write-Warning $Message
}
function Get-HerdrCommandSource {
$existing = Get-Command herdr -ErrorAction SilentlyContinue
if ($null -eq $existing) {
return $null
}
return $existing.Source
}
function Test-PathStartsWith {
param(
[string]$Path,
[string]$Prefix
)
if ([string]::IsNullOrWhiteSpace($Path) -or [string]::IsNullOrWhiteSpace($Prefix)) {
return $false
}
try {
$normalizedPath = [System.IO.Path]::GetFullPath($Path)
$normalizedPrefix = [System.IO.Path]::GetFullPath($Prefix).TrimEnd("\") + "\"
return $normalizedPath.StartsWith($normalizedPrefix, [System.StringComparison]::OrdinalIgnoreCase)
} catch {
return $false
}
}
function Path-Contains {
param(
[string]$PathValue,
[string]$Entry
)
if ([string]::IsNullOrWhiteSpace($PathValue)) {
return $false
}
$needle = $Entry.TrimEnd("\")
foreach ($segment in $PathValue.Split(";", [System.StringSplitOptions]::RemoveEmptyEntries)) {
if ($segment.TrimEnd("\") -ieq $needle) {
return $true
}
}
return $false
}
function Prepend-PathEntry {
param(
[string]$PathValue,
[string]$Entry
)
$needle = $Entry.TrimEnd("\")
$segments = @($Entry)
if (-not [string]::IsNullOrWhiteSpace($PathValue)) {
$segments += $PathValue.Split(";", [System.StringSplitOptions]::RemoveEmptyEntries) |
Where-Object { $_.TrimEnd("\") -ine $needle }
}
return ($segments -join ";")
}
function Update-PathRegistryEntry {
param(
[Microsoft.Win32.RegistryKey]$EnvironmentKey,
[string]$Entry
)
$options = [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames
$value = $EnvironmentKey.GetValue("Path", $null, $options)
$kind = if ($null -eq $value) {
[Microsoft.Win32.RegistryValueKind]::String
} else {
$EnvironmentKey.GetValueKind("Path")
}
$newValue = Prepend-PathEntry -PathValue $value -Entry $Entry
if ($newValue -ceq $value) {
return $false
}
$EnvironmentKey.SetValue("Path", $newValue, $kind)
return $true
}
function Publish-EnvironmentChange {
if (-not ("HerdrInstaller.EnvironmentNativeMethods" -as [type])) {
Add-Type -Namespace HerdrInstaller -Name EnvironmentNativeMethods -MemberDefinition @'
[System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
public static extern System.IntPtr SendMessageTimeout(
System.IntPtr hWnd,
uint message,
System.UIntPtr wParam,
string lParam,
uint flags,
uint timeout,
out System.UIntPtr result);
'@
}
$result = [UIntPtr]::Zero
[HerdrInstaller.EnvironmentNativeMethods]::SendMessageTimeout(
[IntPtr]0xffff,
0x1a,
[UIntPtr]::Zero,
"Environment",
0x0002,
1000,
[ref]$result
) | Out-Null
}
function Get-ManifestAsset {
param(
[object]$Manifest,
[string]$Target
)
$property = $Manifest.assets.PSObject.Properties[$Target]
if ($null -eq $property) {
throw "Release manifest does not include a binary for $Target."
}
$sha256 = $null
$shaMapProperty = $Manifest.PSObject.Properties["sha256"]
if ($null -ne $shaMapProperty -and $null -ne $shaMapProperty.Value) {
$targetShaProperty = $shaMapProperty.Value.PSObject.Properties[$Target]
if ($null -ne $targetShaProperty -and -not [string]::IsNullOrWhiteSpace([string]$targetShaProperty.Value)) {
$sha256 = [string]$targetShaProperty.Value
}
}
$asset = $property.Value
if ($asset -is [string]) {
$url = [string]$asset
return [PSCustomObject]@{
Url = $url
Sha256 = $sha256
Format = if ($url.EndsWith(".zip", [System.StringComparison]::OrdinalIgnoreCase)) { "zip" } else { "exe" }
}
}
$urlProperty = $asset.PSObject.Properties["url"]
if ($null -eq $urlProperty -or [string]::IsNullOrWhiteSpace([string]$urlProperty.Value)) {
throw "Release manifest asset $Target is missing a URL."
}
$url = [string]$urlProperty.Value
$formatProperty = $asset.PSObject.Properties["format"]
$format = if ($null -eq $formatProperty -or [string]::IsNullOrWhiteSpace([string]$formatProperty.Value)) {
if ($url.EndsWith(".zip", [System.StringComparison]::OrdinalIgnoreCase)) { "zip" } else { "exe" }
} else {
[string]$formatProperty.Value
}
if ($format -notin @("zip", "exe")) {
throw "Release manifest asset $Target has unsupported format '$format'."
}
$shaProperty = $asset.PSObject.Properties["sha256"]
if ($null -ne $shaProperty -and -not [string]::IsNullOrWhiteSpace([string]$shaProperty.Value)) {
$sha256 = [string]$shaProperty.Value
}
return [PSCustomObject]@{
Url = $url
Sha256 = $sha256
Format = $format
}
}
function ConvertTo-ManifestObject {
param([object]$Manifest)
if ($Manifest -isnot [string]) {
return $Manifest
}
$json = $Manifest.TrimStart([char]0xFEFF)
$utf8BomDecodedAsLatin1 = [string]::Concat([char]0x00EF, [char]0x00BB, [char]0x00BF)
if ($json.StartsWith($utf8BomDecodedAsLatin1)) {
$json = $json.Substring(3)
}
return $json | ConvertFrom-Json
}
function Test-FileDigest {
param(
[string]$Path,
[string]$ExpectedDigest
)
if ([string]::IsNullOrWhiteSpace($ExpectedDigest)) {
throw "A SHA-256 checksum is required for $Path."
}
if ($ExpectedDigest -notmatch '^[0-9a-fA-F]{64}$') {
throw "Invalid SHA-256 checksum for $Path."
}
$sha256 = [System.Security.Cryptography.SHA256]::Create()
try {
$bytes = [System.IO.File]::ReadAllBytes($Path)
$actual = [System.BitConverter]::ToString($sha256.ComputeHash($bytes)).Replace("-", "").ToLowerInvariant()
} finally {
$sha256.Dispose()
}
if ($actual -ne $ExpectedDigest.ToLowerInvariant()) {
throw "Downloaded Herdr checksum did not match. Expected $ExpectedDigest but got $actual."
}
}
function Test-RegularFile {
param([string]$Path)
if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) {
return $false
}
$item = Get-Item -LiteralPath $Path -Force
return -not ($item.Attributes -band [IO.FileAttributes]::ReparsePoint)
}
function Test-RegularDirectory {
param([string]$Path)
if (-not (Test-Path -LiteralPath $Path -PathType Container)) {
return $false
}
$item = Get-Item -LiteralPath $Path -Force
return -not ($item.Attributes -band [IO.FileAttributes]::ReparsePoint)
}
function Test-HerdrReleaseComplete {
param(
[string]$ReleaseDir,
[string]$Format
)
if (-not (Test-RegularDirectory -Path $ReleaseDir)) {
return $false
}
$herdrExe = Join-Path $ReleaseDir "herdr.exe"
if (-not (Test-RegularFile -Path $herdrExe)) {
return $false
}
if ($Format -eq "exe") {
return $true
}
$conptyRoot = Join-Path $ReleaseDir "conpty"
if (-not (Test-RegularDirectory -Path $conptyRoot) -or
-not (Test-RegularDirectory -Path (Join-Path $conptyRoot "x64")) -or
-not (Test-RegularDirectory -Path (Join-Path $conptyRoot "arm64"))) {
return $false
}
$markerPath = Join-Path $conptyRoot "herdr-conpty.json"
$required = @(
"conpty/conpty.dll",
"conpty/x64/OpenConsole.exe",
"conpty/arm64/OpenConsole.exe",
"THIRD-PARTY-NOTICES/Microsoft.Windows.Console.ConPTY-LICENSE.txt",
"THIRD-PARTY-NOTICES/Microsoft.Windows.Console.ConPTY-NOTICE.md"
)
foreach ($relative in $required) {
if (-not (Test-RegularFile -Path (Join-Path $ReleaseDir ($relative -replace '/', '\')))) {
return $false
}
}
if (-not (Test-RegularFile -Path $markerPath)) {
return $false
}
try {
$marker = ConvertTo-ManifestObject -Manifest (Get-Content -LiteralPath $markerPath -Raw)
$schemaProperty = $marker.PSObject.Properties["schema_version"]
$packageProperty = $marker.PSObject.Properties["package"]
$versionProperty = $marker.PSObject.Properties["version"]
$architectureProperty = $marker.PSObject.Properties["architecture"]
$filesProperty = $marker.PSObject.Properties["files"]
if ($null -eq $schemaProperty -or [int]$schemaProperty.Value -ne 1 -or
$null -eq $packageProperty -or [string]$packageProperty.Value -ne "Microsoft.Windows.Console.ConPTY" -or
$null -eq $versionProperty -or [string]::IsNullOrWhiteSpace([string]$versionProperty.Value) -or
$null -eq $architectureProperty -or [string]$architectureProperty.Value -ne "x86_64" -or
$null -eq $filesProperty) {
return $false
}
$expectedConptyFiles = @(
"conpty/conpty.dll",
"conpty/x64/OpenConsole.exe",
"conpty/arm64/OpenConsole.exe"
)
$markerFileNames = @($filesProperty.Value.PSObject.Properties | ForEach-Object { $_.Name })
if (@(Compare-Object $expectedConptyFiles $markerFileNames).Count -ne 0) {
return $false
}
$bundleEntries = @(Get-ChildItem -LiteralPath $conptyRoot -Force -Recurse)
if (@($bundleEntries | Where-Object {
$_.Attributes -band [IO.FileAttributes]::ReparsePoint
}).Count -ne 0) {
return $false
}
$releaseRoot = [System.IO.Path]::GetFullPath($ReleaseDir).TrimEnd('\')
$actualBundleFiles = @($bundleEntries | Where-Object { -not $_.PSIsContainer } | ForEach-Object {
$_.FullName.Substring($releaseRoot.Length + 1).Replace('\', '/')
})
$expectedBundleFiles = @($expectedConptyFiles) + "conpty/herdr-conpty.json"
if (@(Compare-Object $expectedBundleFiles $actualBundleFiles).Count -ne 0) {
return $false
}
foreach ($relative in $expectedConptyFiles) {
$digestProperty = $filesProperty.Value.PSObject.Properties[$relative]
if ($null -eq $digestProperty) {
return $false
}
Test-FileDigest -Path (Join-Path $ReleaseDir ($relative -replace '/', '\')) -ExpectedDigest ([string]$digestProperty.Value)
}
} catch {
return $false
}
return $true
}
function Invoke-WithInstallLock {
param(
[string]$LockPath,
[scriptblock]$Script
)
New-Item -ItemType Directory -Force -Path (Split-Path -Parent $LockPath) | Out-Null
$lock = $null
while ($null -eq $lock) {
try {
$lock = [System.IO.File]::Open(
$LockPath,
[System.IO.FileMode]::OpenOrCreate,
[System.IO.FileAccess]::ReadWrite,
[System.IO.FileShare]::None
)
} catch [System.IO.IOException] {
Start-Sleep -Milliseconds 250
}
}
try {
& $Script
} finally {
$lock.Dispose()
}
}
function Test-IsJunction {
param([string]$Path)
if (-not (Test-Path -LiteralPath $Path)) {
return $false
}
$item = Get-Item -LiteralPath $Path -Force
return ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -and $item.LinkType -eq "Junction"
}
function Set-ManagedJunction {
param(
[string]$LinkPath,
[string]$TargetPath,
[string]$ManagedTargetPrefix,
[bool]$AllowLegacyHerdrBinMigration = $false
)
if (Test-Path -LiteralPath $LinkPath) {
$item = Get-Item -LiteralPath $LinkPath -Force
if (Test-IsJunction -Path $LinkPath) {
$existingTarget = [string]$item.Target
if (-not [string]::IsNullOrWhiteSpace($ManagedTargetPrefix)) {
$ownedPrefix = $ManagedTargetPrefix.TrimEnd("\")
if (-not $existingTarget.StartsWith($ownedPrefix, [System.StringComparison]::OrdinalIgnoreCase)) {
throw "Refusing to retarget junction at $LinkPath because it is not managed by this installer."
}
}
if ($existingTarget.Equals($TargetPath, [System.StringComparison]::OrdinalIgnoreCase)) {
return
}
Remove-Item -LiteralPath $LinkPath -Recurse -Force
} elseif ($item.PSIsContainer) {
if ((Get-ChildItem -LiteralPath $LinkPath -Force | Select-Object -First 1) -ne $null) {
if (-not (Move-LegacyHerdrBinDirectory -Path $LinkPath -AllowMigration $AllowLegacyHerdrBinMigration)) {
throw "Refusing to replace non-empty directory at $LinkPath with a junction."
}
} else {
Remove-Item -LiteralPath $LinkPath -Recurse -Force
}
} else {
throw "Refusing to replace file at $LinkPath with a junction."
}
}
New-Item -ItemType Directory -Force -Path (Split-Path -Parent $LinkPath) | Out-Null
New-Item -ItemType Junction -Path $LinkPath -Target $TargetPath | Out-Null
}
function Move-LegacyHerdrBinDirectory {
param(
[string]$Path,
[bool]$AllowMigration
)
if (-not $AllowMigration) {
return $false
}
$entries = @(Get-ChildItem -LiteralPath $Path -Force)
if (($entries | Where-Object { $_.PSIsContainer } | Select-Object -First 1) -ne $null) {
return $false
}
if (($entries | Where-Object { $_.Name -ieq "herdr.exe" } | Select-Object -First 1) -eq $null) {
return $false
}
$legacyPath = "$Path.legacy.$([System.Guid]::NewGuid().ToString("N"))"
Move-Item -LiteralPath $Path -Destination $legacyPath
Write-Step "Moved legacy Herdr bin directory to $legacyPath."
return $true
}
function Remove-StaleInstallArtifacts {
param([string]$ReleasesDir)
if (-not (Test-Path -LiteralPath $ReleasesDir -PathType Container)) {
return
}
Get-ChildItem -LiteralPath $ReleasesDir -Force -Directory -Filter ".staging.*" -ErrorAction SilentlyContinue |
Remove-Item -Recurse -Force -ErrorAction SilentlyContinue
}
function Remove-OldReleases {
param(
[string]$ReleasesDir,
[string]$CurrentReleaseDir,
[int]$Keep
)
if ($Keep -lt 1 -or -not (Test-Path -LiteralPath $ReleasesDir -PathType Container)) {
return
}
$currentFullPath = [System.IO.Path]::GetFullPath($CurrentReleaseDir)
$releaseDirs = Get-ChildItem -LiteralPath $ReleasesDir -Force -Directory -ErrorAction SilentlyContinue |
Where-Object { -not $_.Name.StartsWith(".staging.") -and -not $_.Name.StartsWith(".backup.") } |
Sort-Object LastWriteTimeUtc -Descending
$kept = 0
foreach ($dir in $releaseDirs) {
$dirFullPath = [System.IO.Path]::GetFullPath($dir.FullName)
if ($dirFullPath.Equals($currentFullPath, [System.StringComparison]::OrdinalIgnoreCase)) {
$kept += 1
continue
}
if ($kept -lt $Keep) {
$kept += 1
continue
}
Remove-Item -LiteralPath $dir.FullName -Recurse -Force -ErrorAction SilentlyContinue
}
}
function Resolve-HerdrVersion {
param(
[object]$Manifest,
[string]$SelectedChannel
)
if ($SelectedChannel -eq "preview") {
if ([string]::IsNullOrWhiteSpace([string]$Manifest.base_version) -or [string]::IsNullOrWhiteSpace([string]$Manifest.build_id)) {
throw "Preview manifest is missing base_version or build_id."
}
return "$($Manifest.base_version)-preview.$($Manifest.build_id)"
}
if ([string]::IsNullOrWhiteSpace([string]$Manifest.version)) {
throw "Stable manifest is missing version."
}
return [string]$Manifest.version
}
if ($env:OS -ne "Windows_NT") {
Write-Error "install.ps1 supports Windows only. Use install.sh on Linux or macOS."
exit 1
}
if (-not [Environment]::Is64BitOperatingSystem) {
Write-Error "Herdr requires 64-bit Windows."
exit 1
}
if ($Channel -eq "stable") {
Write-Error "Windows builds are preview-only for now. Omit -Channel or use -Channel preview."
exit 1
}
$architecture = [System.Runtime.InteropServices.RuntimeInformation,mscorlib]::OSArchitecture.ToString()
switch ($architecture) {
"X64" {
$target = "windows-x86_64"
$targetTriple = "x86_64-pc-windows-msvc"
}
"Arm64" {
$target = "windows-x86_64"
$targetTriple = "x86_64-pc-windows-msvc"
Write-Step "Windows ARM64 detected; installing the x86_64 build under Windows emulation."
}
default {
Write-Error "Unsupported Windows architecture: $architecture"
exit 1
}
}
if ([string]::IsNullOrWhiteSpace($ManifestUrl)) {
$ManifestUrl = if ($Channel -eq "preview") {
"https://herdr.dev/preview.json"
} else {
"https://herdr.dev/latest.json"
}
}
$herdrHome = if ([string]::IsNullOrWhiteSpace($env:HERDR_HOME)) {
Join-Path $env:USERPROFILE ".herdr"
} else {
$env:HERDR_HOME
}
$herdrHome = [System.IO.Path]::GetFullPath($herdrHome)
$standaloneRoot = Join-Path $herdrHome "packages\standalone"
$releasesDir = Join-Path $standaloneRoot "releases"
$currentDir = Join-Path $standaloneRoot "current"
$lockPath = Join-Path $standaloneRoot "install.lock"
$defaultVisibleBinDir = Join-Path $env:LOCALAPPDATA "Programs\Herdr\bin"
$visibleBinDir = if ([string]::IsNullOrWhiteSpace($InstallDir)) {
$defaultVisibleBinDir
} else {
$InstallDir
}
$allowLegacyVisibleBinMigration = $false
try {
$allowLegacyVisibleBinMigration = [System.IO.Path]::GetFullPath($visibleBinDir).TrimEnd("\").Equals(
[System.IO.Path]::GetFullPath($defaultVisibleBinDir).TrimEnd("\"),
[System.StringComparison]::OrdinalIgnoreCase
)
} catch {
$allowLegacyVisibleBinMigration = $false
}
$existingHerdr = Get-HerdrCommandSource
if (-not [string]::IsNullOrWhiteSpace($existingHerdr) -and -not (Test-PathStartsWith -Path $existingHerdr -Prefix $visibleBinDir)) {
Write-Step "Detected existing Herdr command at $existingHerdr"
Write-WarningStep "PATH order decides which Herdr runs. This installer will put $visibleBinDir first for future and current PowerShell sessions."
}
Write-Step "Fetching Herdr $Channel manifest"
$manifest = ConvertTo-ManifestObject -Manifest (Invoke-RestMethod -Uri $ManifestUrl)
if (-not [string]::IsNullOrWhiteSpace($ExpectedBuildId) -and [string]$manifest.build_id -ne $ExpectedBuildId) {
throw "Preview manifest changed while updating. Expected build $ExpectedBuildId but found $($manifest.build_id). Run herdr update again."
}
$versionIdentity = Resolve-HerdrVersion -Manifest $manifest -SelectedChannel $Channel
$asset = Get-ManifestAsset -Manifest $manifest -Target $target
$safeVersionIdentity = $versionIdentity -replace '[^0-9A-Za-z._-]', '-'
$releaseName = "$safeVersionIdentity-$targetTriple"
$releaseDir = Join-Path $releasesDir $releaseName
Write-Step "Installing Herdr $versionIdentity for $targetTriple"
$tempDir = Join-Path ([System.IO.Path]::GetTempPath()) ("herdr-install-" + [System.Guid]::NewGuid().ToString("N"))
New-Item -ItemType Directory -Force -Path $tempDir | Out-Null
try {
Invoke-WithInstallLock -LockPath $lockPath -Script {
Remove-StaleInstallArtifacts -ReleasesDir $releasesDir
if (-not (Test-HerdrReleaseComplete -ReleaseDir $releaseDir -Format $asset.Format)) {
$downloadPath = Join-Path $tempDir "herdr-download.$($asset.Format)"
$stagingDir = Join-Path $releasesDir ".staging.$releaseName.$PID"
Write-Step "Downloading Herdr"
Invoke-WebRequest -Uri $asset.Url -OutFile $downloadPath
Test-FileDigest -Path $downloadPath -ExpectedDigest $asset.Sha256
if ($asset.Format -eq "zip") {
Expand-Archive -LiteralPath $downloadPath -DestinationPath $stagingDir
} else {
New-Item -ItemType Directory -Force -Path $stagingDir | Out-Null
Copy-Item -LiteralPath $downloadPath -Destination (Join-Path $stagingDir "herdr.exe")
}
if (-not (Test-HerdrReleaseComplete -ReleaseDir $stagingDir -Format $asset.Format)) {
throw "Downloaded Herdr package is incomplete or failed ConPTY verification."
}
$stagedHerdr = Join-Path $stagingDir "herdr.exe"
& $stagedHerdr --version *> $null
if ($LASTEXITCODE -ne 0) {
throw "Downloaded Herdr command failed verification: $stagedHerdr --version"
}
$backupDir = $null
if (Test-Path -LiteralPath $releaseDir) {
$backupDir = Join-Path $releasesDir ".backup.$releaseName.$([System.Guid]::NewGuid().ToString('N'))"
[System.IO.Directory]::Move($releaseDir, $backupDir)
}
try {
[System.IO.Directory]::Move($stagingDir, $releaseDir)
} catch {
if ($null -ne $backupDir -and -not (Test-Path -LiteralPath $releaseDir)) {
[System.IO.Directory]::Move($backupDir, $releaseDir)
}
Write-WarningStep "Windows could not activate the downloaded release. Another process may have a package file open, such as antivirus or indexing. No incomplete release was activated. Run herdr update again."
throw
}
if ($null -ne $backupDir) {
Remove-Item -LiteralPath $backupDir -Recurse -Force -ErrorAction SilentlyContinue
}
}
$releaseHerdr = Join-Path $releaseDir "herdr.exe"
& $releaseHerdr --version *> $null
if ($LASTEXITCODE -ne 0) {
throw "Installed Herdr command failed verification: $releaseHerdr --version"
}
Get-ChildItem -LiteralPath $releasesDir -Force -Directory -Filter ".backup.$releaseName.*" -ErrorAction SilentlyContinue |
Remove-Item -Recurse -Force -ErrorAction SilentlyContinue
Set-ManagedJunction -LinkPath $currentDir -TargetPath $releaseDir -ManagedTargetPrefix $releasesDir
Set-ManagedJunction -LinkPath $visibleBinDir -TargetPath $releaseDir -ManagedTargetPrefix $standaloneRoot -AllowLegacyHerdrBinMigration $allowLegacyVisibleBinMigration
Remove-OldReleases -ReleasesDir $releasesDir -CurrentReleaseDir $releaseDir -Keep $Retain
}
} finally {
Remove-Item -LiteralPath $tempDir -Recurse -Force -ErrorAction SilentlyContinue
}
$userEnvironmentKey = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey("Environment")
if ($null -eq $userEnvironmentKey) {
throw "Unable to open the current user's environment registry key."
}
try {
$userPathChanged = Update-PathRegistryEntry -EnvironmentKey $userEnvironmentKey -Entry $visibleBinDir
} finally {
$userEnvironmentKey.Dispose()
}
if ($userPathChanged) {
Publish-EnvironmentChange
Write-Step "PATH updated for future PowerShell sessions."
} else {
Write-Step "$visibleBinDir is already first on PATH."
}
$newProcessPath = Prepend-PathEntry -PathValue $env:Path -Entry $visibleBinDir
if ($newProcessPath -cne $env:Path) {
$env:Path = $newProcessPath
}
$resolvedHerdr = Get-HerdrCommandSource
if (-not (Test-PathStartsWith -Path $resolvedHerdr -Prefix $visibleBinDir)) {
Write-WarningStep "PowerShell still resolves herdr to $resolvedHerdr. Open a new PowerShell window or inspect PATH order manually."
}
Write-Step "Current PowerShell session: herdr"
Write-Step "Future PowerShell windows: open a new PowerShell window and run: herdr"
Write-Host "Herdr $versionIdentity installed successfully."
|