-
Notifications
You must be signed in to change notification settings - Fork 886
Expand file tree
/
Copy pathget-aspire-cli-pr.ps1
More file actions
executable file
·2082 lines (1752 loc) · 80.3 KB
/
get-aspire-cli-pr.ps1
File metadata and controls
executable file
·2082 lines (1752 loc) · 80.3 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
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
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env pwsh
<#
.SYNOPSIS
Download and unpack the Aspire CLI from a specific PR's build artifacts
.DESCRIPTION
Downloads and installs the Aspire CLI from a specific pull request's latest successful build.
Automatically detects the current platform (OS and architecture) and downloads the appropriate artifact.
The script queries the GitHub API to find the latest successful run of the 'ci.yml' workflow
for the specified PR, then downloads and extracts the CLI archive for your platform using 'gh run download'.
Alternatively, you can specify a workflow run ID directly to download from a specific build.
.PARAMETER PRNumber
Pull request number (required)
.PARAMETER WorkflowRunId
Workflow run ID to download from (optional)
.PARAMETER LocalDir
Use pre-downloaded artifacts from a local directory instead of downloading from GitHub.
Mutually exclusive with PRNumber and WorkflowRunId. The directory is auto-detected:
if it contains an aspire-cli-*.tar.gz / .zip archive the archive flow is used; otherwise
it is treated as raw 'dotnet build' / 'dotnet publish' output and the contained
'aspire' or 'aspire.exe' executable is installed directly. NuGet packages (*.nupkg)
in the directory are always installed into the hive.
.PARAMETER HiveLabel
Override the NuGet hive label (default: pr-PRNUMBER, run-RUNID, or local for LocalDir).
.PARAMETER InstallPath
Directory prefix to install (default: $HOME/.aspire on Unix, %USERPROFILE%\.aspire on Windows)
CLI will be installed to InstallPath\bin (or InstallPath/bin on Unix) when installing from archives
or as a dotnet tool with --tool-path.
NuGet packages will be installed to InstallPath\hives\pr-PRNUMBER\packages.
Alias: -i
.PARAMETER InstallMode
How to install the CLI: 'Archive' (default) installs from the cli-native-archives-<rid>
artifact, 'Tool' installs the Aspire.Cli dotnet tool from the PR's RID-specific NuGet artifact,
'WinGet' installs from the generated WinGet manifest artifact, and 'Homebrew' installs from
the generated Homebrew cask artifact.
Alias: -m
.PARAMETER Force
Tool mode only: run dotnet tool update instead of install to move an existing Aspire.Cli tool
to the exact PR package version (allows downgrades).
.PARAMETER OS
Override OS detection (win, linux, linux-musl, osx)
.PARAMETER Architecture
Override architecture detection (x64, arm64)
.PARAMETER HiveOnly
For installs from archives only: only install NuGet packages to the hive, skip CLI download
.PARAMETER SkipPath
Do not add the install path to PATH environment variable (useful for portable installs)
.PARAMETER KeepArchive
Keep downloaded archive files after installation
.PARAMETER Help
Show this help message
.EXAMPLE
.\get-aspire-cli-pr.ps1 1234
.EXAMPLE
.\get-aspire-cli-pr.ps1 1234 -WorkflowRunId 12345678
.EXAMPLE
.\get-aspire-cli-pr.ps1 -LocalDir "C:\path\to\artifacts"
.EXAMPLE
.\get-aspire-cli-pr.ps1 -LocalDir "C:\path\to\artifacts" -HiveLabel my-build
.EXAMPLE
.\get-aspire-cli-pr.ps1 -LocalDir "artifacts\bin\Aspire.Cli\Debug\net10.0"
.EXAMPLE
.\get-aspire-cli-pr.ps1 1234 -InstallPath "C:\my-aspire"
.EXAMPLE
.\get-aspire-cli-pr.ps1 1234 -OS linux -Architecture arm64 -Verbose
.EXAMPLE
.\get-aspire-cli-pr.ps1 1234 -HiveOnly
.EXAMPLE
.\get-aspire-cli-pr.ps1 1234 -WhatIf
.EXAMPLE
.\get-aspire-cli-pr.ps1 1234 -SkipExtension
.EXAMPLE
.\get-aspire-cli-pr.ps1 1234 -UseInsiders
.EXAMPLE
.\get-aspire-cli-pr.ps1 1234 -SkipPath
.EXAMPLE
.\get-aspire-cli-pr.ps1 1234 -InstallMode Tool
.EXAMPLE
.\get-aspire-cli-pr.ps1 1234 -InstallMode Tool -Force
.EXAMPLE
.\get-aspire-cli-pr.ps1 1234 -InstallMode Homebrew
.EXAMPLE
.\get-aspire-cli-pr.ps1 1234 -InstallMode WinGet
.EXAMPLE
.\get-aspire-cli-pr.ps1 -LocalDir "C:\path\to\artifacts" -InstallMode Tool
.EXAMPLE
Piped execution
iex "& { $(irm https://raw.githubusercontent.com/microsoft/aspire/main/eng/scripts/get-aspire-cli-pr.ps1) } <PR_NUMBER>
.NOTES
Requires GitHub CLI (gh) to be installed and authenticated
Requires appropriate permissions to download artifacts from target repository
VS Code extension installation requires VS Code CLI (code) to be available in PATH
.PARAMETER ASPIRE_REPO (environment variable)
Override repository (owner/name). Default: microsoft/aspire
Example: $env:ASPIRE_REPO = 'myfork/aspire'
#>
[CmdletBinding(SupportsShouldProcess)]
param(
[Parameter(Position = 0, HelpMessage = "Pull request number")]
[ValidateRange(1, [int]::MaxValue)]
[int]$PRNumber,
[Parameter(HelpMessage = "Workflow run ID to download from")]
[ValidateRange(1, [long]::MaxValue)]
[long]$WorkflowRunId,
[Parameter(HelpMessage = "Use pre-downloaded artifacts from a local directory instead of downloading from GitHub")]
[string]$LocalDir = "",
[Parameter(HelpMessage = "Override the NuGet hive label (default: pr-<PR>, run-<RUN_ID>, or local for --LocalDir)")]
[string]$HiveLabel = "",
[Parameter(HelpMessage = "Directory prefix to install")]
[Alias("i")]
[string]$InstallPath = "",
[Parameter(HelpMessage = "How to install the CLI: 'Archive' (default), 'Tool', 'WinGet', or 'Homebrew'")]
[Alias("m")]
[ValidateSet("Archive", "Tool", "WinGet", "Homebrew")]
[string]$InstallMode = "Archive",
[Parameter(HelpMessage = "Tool mode updates an existing Aspire.Cli tool; WinGet mode allows replacing an existing Microsoft.Aspire install")]
[switch]$Force,
[Parameter(HelpMessage = "Override OS detection")]
[ValidateSet("", "win", "linux", "linux-musl", "osx")]
[string]$OS = "",
[Parameter(HelpMessage = "Override architecture detection")]
[ValidateSet("", "x64", "arm64")]
[string]$Architecture = "",
[Parameter(HelpMessage = "For installs from archives only: only install NuGet packages to the hive, skip CLI download")]
[switch]$HiveOnly,
[Parameter(HelpMessage = "Skip VS Code extension download and installation")]
[switch]$SkipExtension,
[Parameter(HelpMessage = "Install extension to VS Code Insiders instead of VS Code")]
[switch]$UseInsiders,
[Parameter(HelpMessage = "Do not add the install path to PATH environment variable (useful for portable installs)")]
[switch]$SkipPath,
[Parameter(HelpMessage = "Keep downloaded archive files after installation")]
[switch]$KeepArchive,
[Parameter(HelpMessage = "Show help information")]
[switch]$Help
)
# Global constants
$Script:BuiltNugetsArtifactName = "built-nugets"
$Script:BuiltNugetsRidArtifactName = "built-nugets-for"
$Script:CliArchiveArtifactNamePrefix = "cli-native-archives"
$Script:AspireCliArtifactNamePrefix = "aspire-cli"
$Script:ExtensionArtifactName = "aspire-extension"
$Script:WinGetManifestArtifactName = "winget-manifests-prerelease"
$Script:HomebrewCaskArtifactName = "homebrew-cask-prerelease"
$Script:IsModernPowerShell = $PSVersionTable.PSVersion.Major -ge 6 -and $PSVersionTable.PSEdition -eq "Core"
$Script:HostOS = "unset"
$Script:Repository = if ($env:ASPIRE_REPO -and $env:ASPIRE_REPO.Trim()) { $env:ASPIRE_REPO.Trim() } else { 'microsoft/aspire' }
$Script:GHReposBase = "repos/$($Script:Repository)"
# True if the script is executed from a file (pwsh -File … or .\get-aspire-cli-pr.ps1)
# False if the body is piped / dot‑sourced / iex'd into the current session.
$InvokedFromFile = -not [string]::IsNullOrEmpty($PSCommandPath)
# =============================================================================
# START: Shared code
# =============================================================================
# Consolidated output function with fallback for platforms that don't support Write-Host
function Write-Message {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[AllowEmptyString()]
[string]$Message,
[Parameter()]
[ValidateSet("Verbose", "Info", "Success", "Warning", "Error")]
[string]$Level = "Info"
)
$hasWriteHost = Get-Command Write-Host -ErrorAction SilentlyContinue
switch ($Level) {
"Verbose" {
if ($VerbosePreference -ne "SilentlyContinue") {
Write-Verbose $Message
}
}
"Info" {
if ($hasWriteHost) {
Write-Host $Message -ForegroundColor White
} else {
Write-Output $Message
}
}
"Success" {
if ($hasWriteHost) {
Write-Host $Message -ForegroundColor Green
} else {
Write-Output "SUCCESS: $Message"
}
}
"Warning" {
Write-Warning $Message
}
"Error" {
Write-Error $Message
}
}
}
# Helper function for PowerShell version-specific operations
function Invoke-WithPowerShellVersion {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[scriptblock]$ModernAction,
[Parameter(Mandatory = $true)]
[scriptblock]$LegacyAction
)
if ($Script:IsModernPowerShell) {
& $ModernAction
} else {
& $LegacyAction
}
}
# Function to detect OS
function Get-OperatingSystem {
[CmdletBinding()]
[OutputType([string])]
param()
Write-Message "Detecting OS" -Level Verbose
try {
return Invoke-WithPowerShellVersion -ModernAction {
if ($IsWindows) {
return "win"
}
elseif ($IsLinux) {
try {
$lddOutput = & ldd --version 2>&1 | Out-String
return if ($lddOutput -match "musl") { "linux-musl" } else { "linux" }
}
catch { return "linux" }
}
elseif ($IsMacOS) {
return "osx"
}
else {
return "unsupported"
}
} -LegacyAction {
# PowerShell 5.1 and earlier - more reliable Windows detection
if ($env:OS -eq "Windows_NT" -or [System.Environment]::OSVersion.Platform -eq [System.PlatformID]::Win32NT) {
return "win"
}
$platform = [System.Environment]::OSVersion.Platform
switch ($platform) {
{ $_ -in @([System.PlatformID]::Unix, 4, 6) } { return "linux" }
{ $_ -in @([System.PlatformID]::MacOSX, 128) } { return "osx" }
default { return "unsupported" }
}
}
}
catch {
Write-Message "Failed to detect operating system: $($_.Exception.Message)" -Level Warning
return "unsupported"
}
}
# Enhanced function for cross-platform architecture detection
function Get-MachineArchitecture {
[CmdletBinding()]
[OutputType([string])]
param()
Write-Message "Detecting machine architecture" -Level Verbose
try {
# On Windows PowerShell, use environment variables
if (-not $Script:IsModernPowerShell -or $IsWindows) {
# On PS x86, PROCESSOR_ARCHITECTURE reports x86 even on x64 systems.
# To get the correct architecture, we need to use PROCESSOR_ARCHITEW6432.
# PS x64 doesn't define this, so we fall back to PROCESSOR_ARCHITECTURE.
# Possible values: amd64, x64, x86, arm64, arm
if ( $null -ne $ENV:PROCESSOR_ARCHITEW6432 ) {
return $ENV:PROCESSOR_ARCHITEW6432
}
try {
$osInfo = Get-CimInstance -ClassName CIM_OperatingSystem -ErrorAction Stop
if ($osInfo.OSArchitecture -like "ARM*") {
if ([Environment]::Is64BitOperatingSystem) {
return "arm64"
}
return "arm"
}
}
catch {
Write-Message "Failed to get CIM instance: $($_.Exception.Message)" -Level Verbose
}
if ( $null -ne $ENV:PROCESSOR_ARCHITECTURE ) {
return $ENV:PROCESSOR_ARCHITECTURE
}
}
# For PowerShell 6+ on Unix systems, use .NET runtime information
if ($Script:IsModernPowerShell) {
try {
$runtimeArch = [System.Runtime.InteropServices.RuntimeInformation]::ProcessArchitecture
switch ($runtimeArch) {
"X64" { return "x64" }
"Arm64" { return "arm64" }
default {
Write-Message "Unknown runtime architecture: $runtimeArch" -Level Verbose
# Fall back to uname if available
if (Get-Command uname -ErrorAction SilentlyContinue) {
$unameArch = & uname -m
switch ($unameArch) {
{ @("x86_64", "amd64") -contains $_ } { return "x64" }
{ @("aarch64", "arm64") -contains $_ } { return "arm64" }
default {
throw "Architecture '$unameArch' not supported. If you think this is a bug, report it at https://github.com/microsoft/aspire/issues"
}
}
} else {
throw "Architecture '$runtimeArch' not supported (uname unavailable). If you think this is a bug, report it at https://github.com/microsoft/aspire/issues"
}
}
}
}
catch {
throw "Architecture detection failed: $($_.Exception.Message)"
}
}
throw "Architecture detection failed (no supported detection path). If you think this is a bug, report it at https://github.com/microsoft/aspire/issues"
}
catch {
throw "Architecture detection failed: $($_.Exception.Message)"
}
}
# Convert architecture to CLI architecture format
function Get-CLIArchitectureFromArchitecture {
[CmdletBinding()]
[OutputType([string])]
param(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$Architecture
)
if ($Architecture -eq "<auto>") {
$Architecture = Get-MachineArchitecture
}
$normalizedArch = $Architecture.ToLowerInvariant()
switch ($normalizedArch) {
{ @("amd64", "x64") -contains $_ } {
return "x64"
}
{ $_ -eq "arm64" } {
return "arm64"
}
default {
throw "Architecture '$Architecture' not supported. If you think this is a bug, report it at https://github.com/microsoft/aspire/issues"
}
}
}
function Get-RuntimeIdentifier {
[CmdletBinding()]
[OutputType([string])]
param(
[string]$_OS,
[string]$_Architecture
)
# Determine OS and architecture (either detected or user-specified)
$computedTargetOS = if ([string]::IsNullOrWhiteSpace($_OS)) { $Script:HostOS } else { $_OS }
# Check for unsupported OS
if ($computedTargetOS -eq "unsupported") {
throw "Unsupported operating system. Current platform: $([System.Environment]::OSVersion.Platform)"
}
$computedTargetArch = if ([string]::IsNullOrWhiteSpace($_Architecture)) { Get-CLIArchitectureFromArchitecture "<auto>" } else { Get-CLIArchitectureFromArchitecture $_Architecture }
return "${computedTargetOS}-${computedTargetArch}"
}
# Function to get the CLI executable path based on host OS
function Get-CliExecutablePath {
[CmdletBinding()]
[OutputType([string])]
param(
[Parameter(Mandatory = $true)]
[string]$DestinationPath
)
$exeName = if ($Script:HostOS -eq "win") { "aspire.exe" } else { "aspire" }
return Join-Path $DestinationPath $exeName
}
# Function to back up an existing CLI executable before overwriting it.
# This matches self-update semantics by deleting stale *.old.* backups first.
# On Windows, a running process can still block the rename.
function Backup-ExistingCliExecutable {
[CmdletBinding(SupportsShouldProcess)]
[OutputType([string])]
param(
[Parameter(Mandatory = $true)]
[string]$TargetExePath
)
if (Test-Path $TargetExePath) {
$unixTimestamp = [DateTimeOffset]::UtcNow.ToUnixTimeSeconds()
$backupPath = "$TargetExePath.old.$unixTimestamp"
if ($PSCmdlet.ShouldProcess($TargetExePath, "Backup to $backupPath")) {
Write-Message "Backing up existing CLI: $TargetExePath -> $backupPath" -Level Verbose
Remove-OldCliBackupFiles -TargetExePath $TargetExePath
# Rename existing executable to .old.[timestamp]
try {
Move-Item -Path $TargetExePath -Destination $backupPath -Force -ErrorAction Stop
}
catch {
throw "Failed to back up existing CLI at '$TargetExePath'. The file may be in use by another process. Please close any running Aspire CLI instances and try again. Error: $($_.Exception.Message)"
}
return $backupPath
}
}
return $null
}
# Function to restore CLI executable from backup if installation fails
function Restore-CliExecutableFromBackup {
[CmdletBinding(SupportsShouldProcess)]
param(
[Parameter(Mandatory = $true)]
[string]$BackupPath,
[Parameter(Mandatory = $true)]
[string]$TargetExePath
)
if ($PSCmdlet.ShouldProcess($BackupPath, "Restore to $TargetExePath")) {
Write-Message "Restoring CLI from backup: $BackupPath -> $TargetExePath" -Level Warning
if (Test-Path $TargetExePath) {
Remove-Item -Path $TargetExePath -Force -ErrorAction SilentlyContinue
}
Move-Item -Path $BackupPath -Destination $TargetExePath -Force -ErrorAction Stop
}
}
# Function to clean up old backup files (aspire.exe.old.* or aspire.old.*)
function Remove-OldCliBackupFiles {
[CmdletBinding(SupportsShouldProcess)]
param(
[Parameter(Mandatory = $true)]
[string]$TargetExePath
)
$directory = Split-Path -Parent $TargetExePath
if ([string]::IsNullOrEmpty($directory)) {
return
}
$exeName = Split-Path -Leaf $TargetExePath
$searchPattern = "$exeName.old.*"
$oldBackupFiles = Get-ChildItem -Path $directory -Filter $searchPattern -ErrorAction SilentlyContinue
foreach ($backupFile in $oldBackupFiles) {
if ($PSCmdlet.ShouldProcess($backupFile.FullName, "Delete old backup")) {
try {
Remove-Item -Path $backupFile.FullName -Force -ErrorAction Stop
Write-Message "Deleted old backup file: $($backupFile.FullName)" -Level Verbose
}
catch {
Write-Message "Failed to delete old backup file: $($backupFile.FullName) - $($_.Exception.Message)" -Level Verbose
}
}
}
}
function Expand-AspireCliArchive {
[CmdletBinding(SupportsShouldProcess)]
param(
[string]$ArchiveFile,
[string]$DestinationPath
)
if (-not $PSCmdlet.ShouldProcess($DestinationPath, "Expand archive $ArchiveFile to $DestinationPath")) {
return
}
Write-Message "Unpacking archive to: $DestinationPath" -Level Verbose
# Get the target executable path using shared function
$targetExePath = Get-CliExecutablePath -DestinationPath $DestinationPath
$backupPath = $null
try {
# Create destination directory if it doesn't exist
if (-not (Test-Path $DestinationPath)) {
Write-Message "Creating destination directory: $DestinationPath" -Level Verbose
New-Item -ItemType Directory -Path $DestinationPath -Force -ErrorAction Stop | Out-Null
}
else {
# Back up the existing executable before extraction.
# On Windows, this can still fail if the file is locked by a running process.
$backupPath = Backup-ExistingCliExecutable -TargetExePath $targetExePath
}
Write-Message "Extracting archive: $ArchiveFile" -Level Verbose
# Check archive format based on file extension and extract accordingly
if ($ArchiveFile -match "\.zip$") {
# Use Expand-Archive for ZIP files
if (-not (Get-Command Expand-Archive -ErrorAction SilentlyContinue)) {
throw "Expand-Archive cmdlet not found. Please use PowerShell 5.0 or later to extract ZIP files."
}
Expand-Archive -Path $ArchiveFile -DestinationPath $DestinationPath -Force -ErrorAction Stop
}
elseif ($ArchiveFile -match "\.tar\.gz$") {
# Use tar for tar.gz files
if (-not (Get-Command tar -ErrorAction SilentlyContinue)) {
throw "tar command not found. Please install tar to extract tar.gz files."
}
$currentLocation = Get-Location
try {
Set-Location $DestinationPath
$tarOutput = & tar -xzf $ArchiveFile 2>&1
if ($LASTEXITCODE -ne 0) {
$tarMessage = ($tarOutput | ForEach-Object { $_.ToString() } | Out-String).Trim()
if ([string]::IsNullOrWhiteSpace($tarMessage)) {
throw "Failed to extract tar.gz archive: $ArchiveFile. tar command returned exit code $LASTEXITCODE"
}
throw "Failed to extract tar.gz archive: $ArchiveFile. tar command returned exit code $LASTEXITCODE`: $tarMessage"
}
}
finally {
Set-Location $currentLocation
}
}
else {
throw "Unsupported archive format: $ArchiveFile. Only .zip and .tar.gz files are supported."
}
# Clean up old backup files on successful extraction
if (Test-Path $targetExePath) {
Remove-OldCliBackupFiles -TargetExePath $targetExePath
}
Write-Message "Successfully unpacked archive" -Level Verbose
}
catch {
$unpackErrorMessage = $_.Exception.Message
# If anything goes wrong and we have a backup, restore it
if ($backupPath -and (Test-Path $backupPath)) {
try {
Restore-CliExecutableFromBackup -BackupPath $backupPath -TargetExePath $targetExePath
}
catch {
throw "Failed to unpack archive: $unpackErrorMessage. Restore from backup also failed: $($_.Exception.Message)"
}
}
throw "Failed to unpack archive: $unpackErrorMessage"
}
}
# Simplified installation path determination
function Get-DefaultInstallPrefix {
[CmdletBinding()]
[OutputType([string])]
param()
# Get home directory cross-platform
$homeDirectory = Invoke-WithPowerShellVersion -ModernAction {
if ($env:HOME) {
$env:HOME
} elseif ($IsWindows -and $env:USERPROFILE) {
$env:USERPROFILE
} elseif ($env:USERPROFILE) {
$env:USERPROFILE
} else {
$null
}
} -LegacyAction {
if ($env:USERPROFILE) {
$env:USERPROFILE
} elseif ($env:HOME) {
$env:HOME
} else {
$null
}
}
if ([string]::IsNullOrWhiteSpace($homeDirectory)) {
throw "Unable to determine user home directory. Please specify -InstallPath parameter."
}
$defaultPath = Join-Path $homeDirectory ".aspire"
return [System.IO.Path]::GetFullPath($defaultPath)
}
# Simplified PATH environment update
function Test-PathContainsDirectory {
[CmdletBinding()]
[OutputType([bool])]
param(
[AllowEmptyString()]
[string]$PathValue,
[Parameter(Mandatory = $true)]
[string]$Directory
)
if ([string]::IsNullOrEmpty($PathValue)) {
return $false
}
return $PathValue.Split([System.IO.Path]::PathSeparator, [StringSplitOptions]::RemoveEmptyEntries) -contains $Directory
}
function Update-PathEnvironment {
[CmdletBinding(SupportsShouldProcess)]
param(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$CliBinDir
)
$pathSeparator = [System.IO.Path]::PathSeparator
if (Test-PathContainsDirectory -PathValue $env:PATH -Directory $CliBinDir) {
Write-Message "Path $CliBinDir already exists in PATH, skipping addition" -Level Info
} else {
# Update current session PATH
$currentPathArray = if ($env:PATH) { $env:PATH.Split($pathSeparator, [StringSplitOptions]::RemoveEmptyEntries) } else { @() }
if ($PSCmdlet.ShouldProcess("PATH environment variable", "Add $CliBinDir to current session")) {
$env:PATH = (@($CliBinDir) + $currentPathArray) -join $pathSeparator
Write-Message "Added $CliBinDir to PATH for current session" -Level Info
}
}
# Update persistent PATH for Windows.
# PR installs deliberately skip the persistent user PATH write: a PR build is a per-session
# dogfood activation. Writing it into HKCU\Environment would silently demote a developer's
# daily/stable install on every new shell until they hunt down the stale entry. The
# activation hint printed elsewhere shows how to opt in manually.
$isPrPath = $CliBinDir -match '[/\\]dogfood[/\\]pr-[^/\\]+[/\\]bin$'
if ($Script:HostOS -eq "win" -and -not $isPrPath) {
try {
$userPath = [Environment]::GetEnvironmentVariable("PATH", [EnvironmentVariableTarget]::User)
if (-not $userPath) { $userPath = "" }
$userPathArray = if ($userPath) { $userPath.Split($pathSeparator, [StringSplitOptions]::RemoveEmptyEntries) } else { @() }
if ($userPathArray -notcontains $CliBinDir) {
if ($PSCmdlet.ShouldProcess("User PATH environment variable", "Add $CliBinDir")) {
$newUserPath = (@($CliBinDir) + $userPathArray) -join $pathSeparator
[Environment]::SetEnvironmentVariable("PATH", $newUserPath, [EnvironmentVariableTarget]::User)
Write-Message "Added $CliBinDir to user PATH environment variable" -Level Info
}
}
Write-Message "" -Level Info
Write-Message "The aspire cli is now available for use in this and new sessions." -Level Success
}
catch {
Write-Message "Failed to update persistent PATH environment variable: $($_.Exception.Message)" -Level Warning
Write-Message "You may need to manually add $CliBinDir to your PATH environment variable" -Level Info
}
} elseif ($Script:HostOS -eq "win" -and $isPrPath) {
Write-Message "PR install: leaving user PATH untouched; the activation hint below shows the PATH line to use." -Level Info
}
# GitHub Actions support
if ($env:GITHUB_ACTIONS -eq "true" -and $env:GITHUB_PATH) {
try {
if ($PSCmdlet.ShouldProcess("GITHUB_PATH environment variable", "Add $CliBinDir to GITHUB_PATH")) {
Add-Content -Path $env:GITHUB_PATH -Value $CliBinDir
Write-Message "Added $CliBinDir to GITHUB_PATH for GitHub Actions" -Level Success
}
}
catch {
Write-Message "Failed to update GITHUB_PATH: $($_.Exception.Message)" -Level Warning
}
}
}
# Function to create a temporary directory with conflict resolution
function New-TempDirectory {
[CmdletBinding(SupportsShouldProcess)]
[OutputType([string])]
param(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$Prefix
)
if ($PSCmdlet.ShouldProcess("temporary directory", "Create temporary directory with prefix '$Prefix'")) {
# Create a temporary directory for downloads with conflict resolution
$tempBaseName = "$Prefix-$([System.Guid]::NewGuid().ToString("N").Substring(0, 8))"
$tempDir = Join-Path ([System.IO.Path]::GetTempPath()) $tempBaseName
# Handle potential conflicts
$attempt = 1
while (Test-Path $tempDir) {
$tempDir = Join-Path ([System.IO.Path]::GetTempPath()) "$tempBaseName-$attempt"
$attempt++
if ($attempt -gt 10) {
throw "Unable to create temporary directory after 10 attempts"
}
}
Write-Message "Creating temporary directory: $tempDir" -Level Verbose
try {
New-Item -ItemType Directory -Path $tempDir -Force -ErrorAction Stop | Out-Null
return $tempDir
}
catch {
throw "Failed to create temporary directory: $tempDir - $($_.Exception.Message)"
}
}
else {
# Return a WhatIf path when -WhatIf is used
return Join-Path ([System.IO.Path]::GetTempPath()) "$Prefix-whatif"
}
}
# Cleanup function for temporary directory
function Remove-TempDirectory {
[CmdletBinding(SupportsShouldProcess)]
param(
[Parameter()]
[string]$TempDir
)
if (-not [string]::IsNullOrWhiteSpace($TempDir) -and (Test-Path $TempDir)) {
if (-not $KeepArchive) {
Write-Message "Cleaning up temporary files..." -Level Verbose
try {
if ($PSCmdlet.ShouldProcess($TempDir, "Remove temporary directory")) {
Remove-Item $TempDir -Recurse -Force -ErrorAction Stop
}
}
catch {
Write-Message "Failed to clean up temporary directory: $TempDir - $($_.Exception.Message)" -Level Warning
}
}
else {
Write-Message "Archive files kept in: $TempDir" -Level Info
}
}
}
# =============================================================================
# END: Shared code
# =============================================================================
# Function to check if gh command is available
function Test-GitHubCLIDependency {
[CmdletBinding()]
param()
if (-not (Get-Command gh -ErrorAction SilentlyContinue)) {
Write-Message "GitHub CLI (gh) is required but not installed. Please install it first." -Level Error
Write-Message "Installation instructions: https://cli.github.com/" -Level Info
throw "GitHub CLI (gh) dependency not met"
}
$ghVersion = & gh --version 2>&1
if ($LASTEXITCODE -ne 0) {
throw "GitHub CLI (gh) command failed with exit code $LASTEXITCODE`: $ghVersion"
} else {
$firstLine = ($ghVersion | Select-Object -First 1)
Write-Message "GitHub CLI (gh) found: $firstLine" -Level Verbose
}
}
# Function to check VS Code CLI dependency
function Test-VSCodeCLIDependency {
[CmdletBinding()]
param(
[switch]$UseInsiders
)
$vscodeCmd = if ($UseInsiders) { "code-insiders" } else { "code" }
$vscodeName = if ($UseInsiders) { "VS Code Insiders" } else { "VS Code" }
if (-not (Get-Command $vscodeCmd -ErrorAction SilentlyContinue)) {
Write-Message "$vscodeName CLI ($vscodeCmd) is not available in PATH. Extension installation will be skipped." -Level Warning
Write-Message "To install $vscodeName extensions, ensure $vscodeName is installed and the '$vscodeCmd' command is available." -Level Info
return $false
}
Write-Message "$vscodeName CLI ($vscodeCmd) found" -Level Verbose
return $true
}
# Simplified installation path determination
function Get-InstallPrefix {
[CmdletBinding()]
[OutputType([string])]
param(
[Parameter()]
[string]$InstallPrefix
)
if (-not [string]::IsNullOrWhiteSpace($InstallPrefix)) {
# Validate that the path is not just whitespace and can be created
try {
$resolvedPath = [System.IO.Path]::GetFullPath($InstallPrefix)
return $resolvedPath
}
catch {
throw "Invalid installation path: $InstallPrefix - $($_.Exception.Message)"
}
}
return Get-DefaultInstallPrefix
}
# Function to make GitHub API calls with proper error handling
function Invoke-GitHubAPICall {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string]$Endpoint,
[Parameter()]
[string]$JqFilter = "",
[Parameter()]
[string]$ErrorMessage = "Failed to call GitHub API"
)
$ghCommand = @("gh", "api", $Endpoint)
if (-not [string]::IsNullOrWhiteSpace($JqFilter)) {
$ghCommand += @("--jq", $JqFilter)
}
Write-Message "Calling GitHub API: $($ghCommand -join ' ')" -Level Verbose
$output = & $ghCommand[0] $ghCommand[1..($ghCommand.Length-1)] 2>&1
if ($LASTEXITCODE -ne 0) {
throw "$ErrorMessage (API endpoint: $Endpoint): $output"
}
return $output
}
# Function to get PR head SHA
function Get-PRHeadSHA {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[int]$PRNumber
)
Write-Message "Getting HEAD SHA for PR #$PRNumber" -Level Verbose
if ($Script:Repository -notmatch '^([^/]+)/([^/]+)$') {
throw "Invalid repository format '$Script:Repository'. Expected 'owner/name'."
}
$owner = $Matches[1]
$name = $Matches[2]
$graphqlQuery = 'query($owner:String!, $name:String!, $number:Int!) { repository(owner:$owner, name:$name) { pullRequest(number:$number) { headRefOid } } }'
$ghCommand = @(
"gh", "api", "graphql",
"-f", "query=$graphqlQuery",
"-f", "owner=$owner",
"-f", "name=$name",
"-F", "number=$PRNumber",
"--jq", ".data.repository.pullRequest.headRefOid"
)
Write-Message "Calling GitHub API: $($ghCommand -join ' ')" -Level Verbose
$graphQlError = $null
try {
$headSha = & $ghCommand[0] $ghCommand[1..($ghCommand.Length-1)] 2>$null
if ($LASTEXITCODE -ne 0) {
$graphQlError = "gh exited with code $LASTEXITCODE"
} elseif ([string]::IsNullOrWhiteSpace($headSha) -or $headSha -eq "null") {
$graphQlError = "GraphQL returned empty or null result"
} else {
# Normalize to a single trimmed string in case of unexpected multi-line output
$headSha = ($headSha | Select-Object -First 1).Trim()
}
}
catch {
$graphQlError = $_.Exception.Message
}
if ($graphQlError) {
Write-Message "GraphQL PR head lookup failed, falling back to REST API: $graphQlError" -Level Verbose
try {
$headSha = Invoke-GitHubAPICall -Endpoint "$Script:GHReposBase/pulls/$PRNumber" -JqFilter ".head.sha" -ErrorMessage "Failed to get HEAD SHA for PR #$PRNumber using REST fallback"
}
catch {
throw "Failed to get HEAD SHA for PR #$PRNumber with GraphQL query: $graphQlError`nREST fallback error: $($_.Exception.Message)"
}
}
if ([string]::IsNullOrWhiteSpace($headSha) -or $headSha -eq "null") {
Write-Message "This could mean:" -Level Info
Write-Message " - The PR number does not exist" -Level Info
Write-Message " - You don't have access to the repository" -Level Info
throw "Could not retrieve HEAD SHA for PR #$PRNumber"
}
Write-Message "PR #$PRNumber HEAD SHA: $headSha" -Level Verbose
return $headSha.Trim()
}
# Function to extract version suffix from downloaded NuGet packages
function Get-VersionSuffixFromPackages {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string]$DownloadDir
)
if ($WhatIfPreference) {
# Return a non-PR-shaped sentinel so the -LocalDir auto-detect regex at the
# call site (^pr\.(\d+)\.[0-9a-g]+$) does NOT match and the caller falls
# through to hive_label="local". A "pr.<N>.gSHA"-shaped mock would always
# match and force hive_label="pr-1234" in every -WhatIf run, regardless of
# what is actually in -LocalDir.
return "local"
}
# Look for any .nupkg file and extract version from its name
$nupkgFiles = Get-ChildItem -Path $DownloadDir -Filter "*.nupkg" -Recurse | Select-Object -First 1
if (-not $nupkgFiles) {
Write-Message "No .nupkg files found to extract version from" -Level Verbose
throw "No NuGet packages found to extract version information from"
}