-
Notifications
You must be signed in to change notification settings - Fork 7.4k
/
build.psm1
3753 lines (3218 loc) · 134 KB
/
build.psm1
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
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
param(
# Skips a check that prevents building PowerShell on unsupported Linux distributions
[parameter(Mandatory = $false)][switch]$SkipLinuxDistroCheck = $false
)
. "$PSScriptRoot\tools\buildCommon\startNativeExecution.ps1"
# CI runs with PowerShell 5.0, so don't use features like ?: && ||
Set-StrictMode -Version 3.0
# On Unix paths is separated by colon
# On Windows paths is separated by semicolon
$script:TestModulePathSeparator = [System.IO.Path]::PathSeparator
$script:Options = $null
$dotnetMetadata = Get-Content $PSScriptRoot/DotnetRuntimeMetadata.json | ConvertFrom-Json
$dotnetCLIChannel = $dotnetMetadata.Sdk.Channel
$dotnetCLIQuality = $dotnetMetadata.Sdk.Quality
# __DOTNET_RUNTIME_FEED and __DOTNET_RUNTIME_FEED_KEY are private variables used in release builds
$dotnetAzureFeed = if ([string]::IsNullOrWhiteSpace($env:__DOTNET_RUNTIME_FEED)) { $dotnetMetadata.Sdk.azureFeed } else { $env:__DOTNET_RUNTIME_FEED }
$dotnetAzureFeedSecret = $env:__DOTNET_RUNTIME_FEED_KEY
$dotnetSDKVersionOveride = $dotnetMetadata.Sdk.sdkImageOverride
$dotnetCLIRequiredVersion = $(Get-Content $PSScriptRoot/global.json | ConvertFrom-Json).Sdk.Version
# Track if tags have been sync'ed
$tagsUpToDate = $false
# Sync Tags
# When not using a branch in PowerShell/PowerShell, tags will not be fetched automatically
# Since code that uses Get-PSCommitID and Get-PSLatestTag assume that tags are fetched,
# This function can ensure that tags have been fetched.
# This function is used during the setup phase in tools/ci.psm1
function Sync-PSTags
{
param(
[Switch]
$AddRemoteIfMissing
)
$powerShellRemoteUrls = @(
'https://github.com/PowerShell/PowerShell'
'[email protected]:PowerShell/PowerShell'
)
$defaultRemoteUrl = "$($powerShellRemoteUrls[0]).git"
$upstreamRemoteDefaultName = 'upstream'
$remotes = Start-NativeExecution {git --git-dir="$PSScriptRoot/.git" remote}
$upstreamRemote = $null
foreach($remote in $remotes)
{
$url = Start-NativeExecution {git --git-dir="$PSScriptRoot/.git" remote get-url $remote}
if ($url.EndsWith('.git')) { $url = $url.Substring(0, $url.Length - 4) }
if($url -in $powerShellRemoteUrls)
{
$upstreamRemote = $remote
break
}
}
if(!$upstreamRemote -and $AddRemoteIfMissing.IsPresent -and $remotes -notcontains $upstreamRemoteDefaultName)
{
$null = Start-NativeExecution {git --git-dir="$PSScriptRoot/.git" remote add $upstreamRemoteDefaultName $defaultRemoteUrl}
$upstreamRemote = $upstreamRemoteDefaultName
}
elseif(!$upstreamRemote)
{
Write-Error "Please add a remote to PowerShell\PowerShell. Example: git remote add $upstreamRemoteDefaultName $defaultRemoteUrl" -ErrorAction Stop
}
$null = Start-NativeExecution {git --git-dir="$PSScriptRoot/.git" fetch --tags --quiet $upstreamRemote}
$script:tagsUpToDate=$true
}
# Gets the latest tag for the current branch
function Get-PSLatestTag
{
[CmdletBinding()]
param()
# This function won't always return the correct value unless tags have been sync'ed
# So, Write a warning to run Sync-PSTags
if(!$tagsUpToDate)
{
Write-Warning "Run Sync-PSTags to update tags"
}
return (Start-NativeExecution {git --git-dir="$PSScriptRoot/.git" describe --abbrev=0})
}
function Get-PSVersion
{
[CmdletBinding()]
param(
[switch]
$OmitCommitId
)
if($OmitCommitId.IsPresent)
{
return (Get-PSLatestTag) -replace '^v'
}
else
{
return (Get-PSCommitId) -replace '^v'
}
}
function Get-PSCommitId
{
[CmdletBinding()]
param()
# This function won't always return the correct value unless tags have been sync'ed
# So, Write a warning to run Sync-PSTags
if(!$tagsUpToDate)
{
Write-Warning "Run Sync-PSTags to update tags"
}
return (Start-NativeExecution {git --git-dir="$PSScriptRoot/.git" describe --dirty --abbrev=60})
}
function Get-EnvironmentInformation
{
$environment = @{'IsWindows' = [System.Environment]::OSVersion.Platform -eq [System.PlatformID]::Win32NT}
# PowerShell will likely not be built on pre-1709 nanoserver
if ('System.Management.Automation.Platform' -as [type]) {
$environment += @{'IsCoreCLR' = [System.Management.Automation.Platform]::IsCoreCLR}
$environment += @{'IsLinux' = [System.Management.Automation.Platform]::IsLinux}
$environment += @{'IsMacOS' = [System.Management.Automation.Platform]::IsMacOS}
} else {
$environment += @{'IsCoreCLR' = $false}
$environment += @{'IsLinux' = $false}
$environment += @{'IsMacOS' = $false}
}
if ($environment.IsWindows)
{
$environment += @{'IsAdmin' = (New-Object Security.Principal.WindowsPrincipal ([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)}
$environment += @{'nugetPackagesRoot' = "${env:USERPROFILE}\.nuget\packages", "${env:NUGET_PACKAGES}"}
$environment += @{ 'OSArchitecture' = [System.Runtime.InteropServices.RuntimeInformation]::ProcessArchitecture }
}
else
{
$environment += @{'nugetPackagesRoot' = "${env:HOME}/.nuget/packages"}
}
if ($environment.IsMacOS) {
$environment += @{'UsingHomebrew' = [bool](Get-Command brew -ErrorAction ignore)}
$environment += @{'UsingMacports' = [bool](Get-Command port -ErrorAction ignore)}
$environment += @{
'OSArchitecture' = if ((uname -v) -match 'ARM64') { 'arm64' } else { 'x64' }
}
if (-not($environment.UsingHomebrew -or $environment.UsingMacports)) {
throw "Neither Homebrew nor MacPorts is installed on this system, visit https://brew.sh/ or https://www.macports.org/ to continue"
}
}
if ($environment.IsLinux) {
$environment += @{ 'OSArchitecture' = [System.Runtime.InteropServices.RuntimeInformation]::ProcessArchitecture }
$LinuxInfo = Get-Content /etc/os-release -Raw | ConvertFrom-StringData
$lsb_release = Get-Command lsb_release -Type Application -ErrorAction Ignore | Select-Object -First 1
if ($lsb_release) {
$LinuxID = & $lsb_release -is
}
else {
$LinuxID = ""
}
$environment += @{'LinuxInfo' = $LinuxInfo}
$environment += @{'IsDebian' = $LinuxInfo.ID -match 'debian' -or $LinuxInfo.ID -match 'kali'}
$environment += @{'IsDebian9' = $environment.IsDebian -and $LinuxInfo.VERSION_ID -match '9'}
$environment += @{'IsDebian10' = $environment.IsDebian -and $LinuxInfo.VERSION_ID -match '10'}
$environment += @{'IsDebian11' = $environment.IsDebian -and $LinuxInfo.PRETTY_NAME -match 'bullseye'}
$environment += @{'IsUbuntu' = $LinuxInfo.ID -match 'ubuntu' -or $LinuxID -match 'Ubuntu'}
$environment += @{'IsUbuntu16' = $environment.IsUbuntu -and $LinuxInfo.VERSION_ID -match '16.04'}
$environment += @{'IsUbuntu18' = $environment.IsUbuntu -and $LinuxInfo.VERSION_ID -match '18.04'}
$environment += @{'IsUbuntu20' = $environment.IsUbuntu -and $LinuxInfo.VERSION_ID -match '20.04'}
$environment += @{'IsCentOS' = $LinuxInfo.ID -match 'centos' -and $LinuxInfo.VERSION_ID -match '7'}
$environment += @{'IsFedora' = $LinuxInfo.ID -match 'fedora' -and $LinuxInfo.VERSION_ID -ge 24}
$environment += @{'IsOpenSUSE' = $LinuxInfo.ID -match 'opensuse'}
$environment += @{'IsSLES' = $LinuxInfo.ID -match 'sles'}
$environment += @{'IsRedHat' = $LinuxInfo.ID -match 'rhel'}
$environment += @{'IsRedHat7' = $environment.IsRedHat -and $LinuxInfo.VERSION_ID -match '7' }
$environment += @{'IsOpenSUSE13' = $environment.IsOpenSUSE -and $LinuxInfo.VERSION_ID -match '13'}
$environment += @{'IsOpenSUSE42.1' = $environment.IsOpenSUSE -and $LinuxInfo.VERSION_ID -match '42.1'}
$environment += @{'IsDebianFamily' = $environment.IsDebian -or $environment.IsUbuntu}
$environment += @{'IsRedHatFamily' = $environment.IsCentOS -or $environment.IsFedora -or $environment.IsRedHat}
$environment += @{'IsSUSEFamily' = $environment.IsSLES -or $environment.IsOpenSUSE}
$environment += @{'IsAlpine' = $LinuxInfo.ID -match 'alpine'}
$environment += @{'IsMariner' = $LinuxInfo.ID -match 'mariner'}
# Workaround for temporary LD_LIBRARY_PATH hack for Fedora 24
# https://github.com/PowerShell/PowerShell/issues/2511
if ($environment.IsFedora -and (Test-Path ENV:\LD_LIBRARY_PATH)) {
Remove-Item -Force ENV:\LD_LIBRARY_PATH
Get-ChildItem ENV:
}
if( -not(
$environment.IsDebian -or
$environment.IsUbuntu -or
$environment.IsRedHatFamily -or
$environment.IsSUSEFamily -or
$environment.IsAlpine -or
$environment.IsMariner)
) {
if ($SkipLinuxDistroCheck) {
Write-Warning "The current OS : $($LinuxInfo.ID) is not supported for building PowerShell."
} else {
throw "The current OS : $($LinuxInfo.ID) is not supported for building PowerShell. Import this module with '-ArgumentList `$true' to bypass this check."
}
}
}
return [PSCustomObject] $environment
}
$environment = Get-EnvironmentInformation
# Autoload (in current session) temporary modules used in our tests
$TestModulePath = Join-Path $PSScriptRoot "test/tools/Modules"
if ( -not $env:PSModulePath.Contains($TestModulePath) ) {
$env:PSModulePath = $TestModulePath+$TestModulePathSeparator+$($env:PSModulePath)
}
<#
.Synopsis
Tests if a version is preview
.EXAMPLE
Test-IsPreview -version '6.1.0-sometthing' # returns true
Test-IsPreview -version '6.1.0' # returns false
#>
function Test-IsPreview
{
param(
[parameter(Mandatory)]
[string]
$Version,
[switch]$IsLTS
)
if ($IsLTS.IsPresent) {
## If we are building a LTS package, then never consider it preview.
return $false
}
return $Version -like '*-*'
}
<#
.Synopsis
Tests if a version is a Release Candidate
.EXAMPLE
Test-IsReleaseCandidate -version '6.1.0-sometthing' # returns false
Test-IsReleaseCandidate -version '6.1.0-rc.1' # returns true
Test-IsReleaseCandidate -version '6.1.0' # returns false
#>
function Test-IsReleaseCandidate
{
param(
[parameter(Mandatory)]
[string]
$Version
)
if ($Version -like '*-rc.*')
{
return $true
}
return $false
}
$optimizedFddRegex = 'fxdependent-(linux|win|win7|osx)-(x64|x86|arm64|arm)'
function Start-PSBuild {
[CmdletBinding(DefaultParameterSetName="Default")]
param(
# When specified this switch will stops running dev powershell
# to help avoid compilation error, because file are in use.
[switch]$StopDevPowerShell,
[switch]$Restore,
# Accept a path to the output directory
# When specified, --output <path> will be passed to dotnet
[string]$Output,
[switch]$ResGen,
[switch]$TypeGen,
[switch]$Clean,
[Parameter(ParameterSetName="Legacy")]
[switch]$PSModuleRestore,
[Parameter(ParameterSetName="Default")]
[switch]$NoPSModuleRestore,
[switch]$CI,
[switch]$ForMinimalSize,
# Skips the step where the pwsh that's been built is used to create a configuration
# Useful when changing parsing/compilation, since bugs there can mean we can't get past this step
[switch]$SkipExperimentalFeatureGeneration,
# this switch will re-build only System.Management.Automation.dll
# it's useful for development, to do a quick changes in the engine
[switch]$SMAOnly,
# Use nuget.org instead of the PowerShell specific feed
[switch]$UseNuGetOrg,
# These runtimes must match those in project.json
# We do not use ValidateScript since we want tab completion
# If this parameter is not provided it will get determined automatically.
[ValidateSet("linux-musl-x64",
"fxdependent",
"fxdependent-noopt-linux-musl-x64",
"fxdependent-linux-x64",
"fxdependent-linux-arm64",
"fxdependent-win-desktop",
"linux-arm",
"linux-arm64",
"linux-x64",
"osx-arm64",
"osx-x64",
"win-arm",
"win-arm64",
"win7-x64",
"win7-x86")]
[string]$Runtime,
[ValidateSet('Debug', 'Release', 'CodeCoverage', 'StaticAnalysis', '')] # We might need "Checked" as well
[string]$Configuration,
[ValidatePattern("^v\d+\.\d+\.\d+(-\w+(\.\d{1,2})?)?$")]
[ValidateNotNullOrEmpty()]
[string]$ReleaseTag,
[switch]$Detailed,
[switch]$InteractiveAuth,
[switch]$SkipRoslynAnalyzers,
[string]$PSOptionsPath
)
if ($ReleaseTag -and $ReleaseTag -notmatch "^v\d+\.\d+\.\d+(-(preview|rc)(\.\d{1,2})?)?$") {
Write-Warning "Only preview or rc are supported for releasing pre-release version of PowerShell"
}
if ($PSCmdlet.ParameterSetName -eq "Default" -and !$NoPSModuleRestore)
{
$PSModuleRestore = $true
}
if ($Runtime -eq "linux-arm" -and $environment.IsLinux -and -not $environment.IsUbuntu) {
throw "Cross compiling for linux-arm is only supported on Ubuntu environment"
}
if ("win-arm","win-arm64" -contains $Runtime -and -not $environment.IsWindows) {
throw "Cross compiling for win-arm or win-arm64 is only supported on Windows environment"
}
if ($ForMinimalSize) {
if ($Runtime -and "linux-x64", "win7-x64", "osx-x64" -notcontains $Runtime) {
throw "Build for the minimal size is enabled only for following runtimes: 'linux-x64', 'win7-x64', 'osx-x64'"
}
}
if ($UseNuGetOrg) {
Switch-PSNugetConfig -Source Public
} else {
Write-Verbose -Message "Using default feeds which are Microsoft, use `-UseNuGetOrg` to switch to Public feeds" -Verbose
}
function Stop-DevPowerShell {
Get-Process pwsh* |
Where-Object {
$_.Modules |
Where-Object {
$_.FileName -eq (Resolve-Path $script:Options.Output).Path
}
} |
Stop-Process -Verbose
}
if ($Clean) {
Write-Log -message "Cleaning your working directory. You can also do it with 'git clean -fdX --exclude .vs/PowerShell/v16/Server/sqlite3'"
Push-Location $PSScriptRoot
try {
# Excluded sqlite3 folder is due to this Roslyn issue: https://github.com/dotnet/roslyn/issues/23060
# Excluded src/Modules/nuget.config as this is required for release build.
# Excluded nuget.config as this is required for release build.
git clean -fdX --exclude .vs/PowerShell/v16/Server/sqlite3 --exclude src/Modules/nuget.config --exclude nuget.config
} finally {
Pop-Location
}
}
# Add .NET CLI tools to PATH
Find-Dotnet
# Verify we have git in place to do the build, and abort if the precheck failed
$precheck = precheck 'git' "Build dependency 'git' not found in PATH. See <URL: https://docs.github.com/en/github/getting-started-with-github/set-up-git#setting-up-git >"
if (-not $precheck) {
return
}
# Verify we have .NET SDK in place to do the build, and abort if the precheck failed
$precheck = precheck 'dotnet' "Build dependency 'dotnet' not found in PATH. Run Start-PSBootstrap. Also see <URL: https://dotnet.github.io/getting-started/ >"
if (-not $precheck) {
return
}
# Verify if the dotnet in-use is the required version
$dotnetCLIInstalledVersion = Find-RequiredSDK $dotnetCLIRequiredVersion
If ($dotnetCLIInstalledVersion -ne $dotnetCLIRequiredVersion) {
Write-Warning @"
The currently installed .NET Command Line Tools is not the required version.
Installed version: $dotnetCLIInstalledVersion
Required version: $dotnetCLIRequiredVersion
Fix steps:
1. Remove the installed version from:
- on windows '`$env:LOCALAPPDATA\Microsoft\dotnet'
- on macOS and linux '`$env:HOME/.dotnet'
2. Run Start-PSBootstrap or Install-Dotnet
3. Start-PSBuild -Clean
`n
"@
return
}
# set output options
$OptionsArguments = @{
Output=$Output
Runtime=$Runtime
Configuration=$Configuration
Verbose=$true
SMAOnly=[bool]$SMAOnly
PSModuleRestore=$PSModuleRestore
ForMinimalSize=$ForMinimalSize
}
$script:Options = New-PSOptions @OptionsArguments
if ($StopDevPowerShell) {
Stop-DevPowerShell
}
# setup arguments
# adding ErrorOnDuplicatePublishOutputFiles=false due to .NET SDk issue: https://github.com/dotnet/sdk/issues/15748
# removing --no-restore due to .NET SDK issue: https://github.com/dotnet/sdk/issues/18999
# $Arguments = @("publish","--no-restore","/property:GenerateFullPaths=true", "/property:ErrorOnDuplicatePublishOutputFiles=false")
$Arguments = @("publish","/property:GenerateFullPaths=true", "/property:ErrorOnDuplicatePublishOutputFiles=false")
if ($Output -or $SMAOnly) {
$Arguments += "--output", (Split-Path $Options.Output)
}
# Add --self-contained due to "warning NETSDK1179: One of '--self-contained' or '--no-self-contained' options are required when '--runtime' is used."
if ($Options.Runtime -like 'fxdependent*') {
$Arguments += "--no-self-contained"
# The UseAppHost = true property creates ".exe" for the fxdependent packages.
# We need this in the package as Start-Job needs it.
$Arguments += "/property:UseAppHost=true"
}
else {
$Arguments += "--self-contained"
}
if ($Options.Runtime -like 'win*') {
# Starting in .NET 8, the .NET SDK won't recognize version-specific RIDs by default, such as win7-x64,
# see https://learn.microsoft.com/dotnet/core/compatibility/sdk/8.0/rid-graph for details.
# It will cause huge amount of changes in our build infrastructure because our building and packaging
# scripts have the 'win7-xx' assumption regarding the target runtime.
#
# As a workaround, we use the old full RID graph during the build so that we can continue to use the
# 'win7-x64' and 'win7-x86' RIDs.
$Arguments += "/property:UseRidGraph=true"
}
if ($Options.Runtime -like 'win*' -or ($Options.Runtime -like 'fxdependent*' -and $environment.IsWindows)) {
$Arguments += "/property:IsWindows=true"
if(!$environment.IsWindows) {
$Arguments += "/property:EnableWindowsTargeting=true"
}
}
else {
$Arguments += "/property:IsWindows=false"
}
# Framework Dependent builds do not support ReadyToRun as it needs a specific runtime to optimize for.
# The property is set in Powershell.Common.props file.
# We override the property through the build command line.
if(($Options.Runtime -like 'fxdependent*' -or $ForMinimalSize) -and $Options.Runtime -notmatch $optimizedFddRegex) {
$Arguments += "/property:PublishReadyToRun=false"
}
$Arguments += "--configuration", $Options.Configuration
$Arguments += "--framework", $Options.Framework
if ($Detailed.IsPresent)
{
$Arguments += '--verbosity', 'd'
}
if (-not $SMAOnly -and $Options.Runtime -notlike 'fxdependent*') {
# libraries should not have runtime
$Arguments += "--runtime", $Options.Runtime
} elseif ($Options.Runtime -match $optimizedFddRegex) {
$runtime = $Options.Runtime -replace 'fxdependent-', ''
$Arguments += "--runtime", $runtime
}
if ($ReleaseTag) {
$ReleaseTagToUse = $ReleaseTag -Replace '^v'
$Arguments += "/property:ReleaseTag=$ReleaseTagToUse"
}
if ($SkipRoslynAnalyzers) {
$Arguments += "/property:RunAnalyzersDuringBuild=false"
}
# handle Restore
Restore-PSPackage -Options $Options -Force:$Restore -InteractiveAuth:$InteractiveAuth
# handle ResGen
# Heuristic to run ResGen on the fresh machine
if ($ResGen -or -not (Test-Path "$PSScriptRoot/src/Microsoft.PowerShell.ConsoleHost/gen")) {
Write-Log -message "Run ResGen (generating C# bindings for resx files)"
Start-ResGen
}
# Handle TypeGen
# .inc file name must be different for Windows and Linux to allow build on Windows and WSL.
$runtime = $Options.Runtime
if ($Options.Runtime -match $optimizedFddRegex) {
$runtime = $Options.Runtime -replace 'fxdependent-', ''
}
$incFileName = "powershell_$runtime.inc"
if ($TypeGen -or -not (Test-Path "$PSScriptRoot/src/TypeCatalogGen/$incFileName")) {
Write-Log -message "Run TypeGen (generating CorePsTypeCatalog.cs)"
Start-TypeGen -IncFileName $incFileName
}
# Get the folder path where pwsh.exe is located.
if ((Split-Path $Options.Output -Leaf) -like "pwsh*") {
$publishPath = Split-Path $Options.Output -Parent
}
else {
$publishPath = $Options.Output
}
try {
# Relative paths do not work well if cwd is not changed to project
Push-Location $Options.Top
if ($Options.Runtime -notlike 'fxdependent*' -or $Options.Runtime -match $optimizedFddRegex) {
Write-Verbose "Building without shim" -Verbose
$sdkToUse = 'Microsoft.NET.Sdk'
if (($Options.Runtime -like 'win7-*' -or $Options.Runtime -eq 'win-arm64') -and !$ForMinimalSize) {
## WPF/WinForm and the PowerShell GraphicalHost assemblies are included
## when 'Microsoft.NET.Sdk.WindowsDesktop' is used.
$sdkToUse = 'Microsoft.NET.Sdk.WindowsDesktop'
}
$Arguments += "/property:SDKToUse=$sdkToUse"
Write-Log -message "Run dotnet $Arguments from $PWD"
Start-NativeExecution { dotnet $Arguments }
Write-Log -message "PowerShell output: $($Options.Output)"
} else {
Write-Verbose "Building with shim" -Verbose
$globalToolSrcFolder = Resolve-Path (Join-Path $Options.Top "../Microsoft.PowerShell.GlobalTool.Shim") | Select-Object -ExpandProperty Path
if ($Options.Runtime -eq 'fxdependent' -or $Options.Runtime -eq 'fxdependent-noopt-linux-musl-x64') {
$Arguments += "/property:SDKToUse=Microsoft.NET.Sdk"
} elseif ($Options.Runtime -eq 'fxdependent-win-desktop') {
$Arguments += "/property:SDKToUse=Microsoft.NET.Sdk.WindowsDesktop"
}
Write-Log -message "Run dotnet $Arguments from $PWD"
Start-NativeExecution { dotnet $Arguments }
Write-Log -message "PowerShell output: $($Options.Output)"
try {
Push-Location $globalToolSrcFolder
if ($Options.Runtime -like 'fxdependent*') {
if ($Arguments -contains '/property:UseAppHost=true') {
$Arguments = @($Arguments | Where-Object { $_ -notlike '/property:UseAppHost=true' })
}
}
if ($Arguments -notcontains '--output') {
$Arguments += "--output", $publishPath
}
Write-Log -message "Run dotnet $Arguments from $PWD to build global tool entry point"
Start-NativeExecution { dotnet $Arguments }
}
finally {
Pop-Location
}
}
} finally {
Pop-Location
}
# No extra post-building task will run if '-SMAOnly' is specified, because its purpose is for a quick update of S.M.A.dll after full build.
if ($SMAOnly) {
return
}
# publish reference assemblies
try {
Push-Location "$PSScriptRoot/src/TypeCatalogGen"
$refAssemblies = Get-Content -Path $incFileName | Where-Object { $_ -like "*microsoft.netcore.app*" } | ForEach-Object { $_.TrimEnd(';') }
$refDestFolder = Join-Path -Path $publishPath -ChildPath "ref"
if (Test-Path $refDestFolder -PathType Container) {
Remove-Item $refDestFolder -Force -Recurse -ErrorAction Stop
}
New-Item -Path $refDestFolder -ItemType Directory -Force -ErrorAction Stop > $null
Copy-Item -Path $refAssemblies -Destination $refDestFolder -Force -ErrorAction Stop
} finally {
Pop-Location
}
if ($ReleaseTag) {
$psVersion = $ReleaseTag
}
else {
$psVersion = git --git-dir="$PSScriptRoot/.git" describe
}
if ($environment.IsLinux) {
if ($environment.IsRedHatFamily -or $environment.IsDebian) {
# Symbolic links added here do NOT affect packaging as we do not build on Debian.
# add two symbolic links to system shared libraries that libmi.so is dependent on to handle
# platform specific changes. This is the only set of platforms needed for this currently
# as Ubuntu has these specific library files in the platform and macOS builds for itself
# against the correct versions.
if ($environment.IsDebian10 -or $environment.IsDebian11){
$sslTarget = "/usr/lib/x86_64-linux-gnu/libssl.so.1.1"
$cryptoTarget = "/usr/lib/x86_64-linux-gnu/libcrypto.so.1.1"
}
elseif ($environment.IsDebian9){
# NOTE: Debian 8 doesn't need these symlinks
$sslTarget = "/usr/lib/x86_64-linux-gnu/libssl.so.1.0.2"
$cryptoTarget = "/usr/lib/x86_64-linux-gnu/libcrypto.so.1.0.2"
}
else { #IsRedHatFamily
$sslTarget = "/lib64/libssl.so.10"
$cryptoTarget = "/lib64/libcrypto.so.10"
}
if ( ! (Test-Path "$publishPath/libssl.so.1.0.0")) {
$null = New-Item -Force -ItemType SymbolicLink -Target $sslTarget -Path "$publishPath/libssl.so.1.0.0" -ErrorAction Stop
}
if ( ! (Test-Path "$publishPath/libcrypto.so.1.0.0")) {
$null = New-Item -Force -ItemType SymbolicLink -Target $cryptoTarget -Path "$publishPath/libcrypto.so.1.0.0" -ErrorAction Stop
}
}
}
# download modules from powershell gallery.
# - PowerShellGet, PackageManagement, Microsoft.PowerShell.Archive
if ($PSModuleRestore) {
Restore-PSModuleToBuild -PublishPath $publishPath
}
# publish powershell.config.json
$config = [ordered]@{}
if ($Options.Runtime -like "*win*") {
# Execution Policy and WinCompat feature are only supported on Windows.
$config.Add("Microsoft.PowerShell:ExecutionPolicy", "RemoteSigned")
$config.Add("WindowsPowerShellCompatibilityModuleDenyList", @("PSScheduledJob", "BestPractices", "UpdateServices"))
}
if (-not $SkipExperimentalFeatureGeneration -and
(Test-IsPreview $psVersion) -and
-not (Test-IsReleaseCandidate $psVersion)
) {
if ((Test-ShouldGenerateExperimentalFeatures -Runtime $Options.Runtime)) {
Write-Verbose "Build experimental feature list by running 'Get-ExperimentalFeature'" -Verbose
$json = & $publishPath\pwsh -noprofile -command {
$expFeatures = Get-ExperimentalFeature | ForEach-Object -MemberName Name
ConvertTo-Json $expFeatures
}
} else {
Write-Verbose "Build experimental feature list by using the pre-generated JSON files" -Verbose
$ExperimentalFeatureJsonFilePath = if ($Options.Runtime -like "*win*") {
"$PSScriptRoot/experimental-feature-windows.json"
} else {
"$PSScriptRoot/experimental-feature-linux.json"
}
if (-not (Test-Path $ExperimentalFeatureJsonFilePath)) {
throw "ExperimentalFeatureJsonFilePath: $ExperimentalFeatureJsonFilePath does not exist"
}
$json = Get-Content -Raw $ExperimentalFeatureJsonFilePath
}
$config.Add('ExperimentalFeatures', [string[]]($json | ConvertFrom-Json));
} else {
Write-Warning -Message "Experimental features are not enabled in powershell.config.json file"
}
if ($config.Count -gt 0) {
$configPublishPath = Join-Path -Path $publishPath -ChildPath "powershell.config.json"
Set-Content -Path $configPublishPath -Value ($config | ConvertTo-Json) -Force -ErrorAction Stop
} else {
Write-Warning "No powershell.config.json generated for $publishPath"
}
# Restore the Pester module
if ($CI) {
Restore-PSPester -Destination (Join-Path $publishPath "Modules")
}
Clear-NativeDependencies -PublishFolder $publishPath
if ($PSOptionsPath) {
$resolvedPSOptionsPath = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($PSOptionsPath)
$parent = Split-Path -Path $resolvedPSOptionsPath
if (!(Test-Path $parent)) {
$null = New-Item -ItemType Directory -Path $parent
}
Save-PSOptions -PSOptionsPath $PSOptionsPath -Options $Options
}
}
function Switch-PSNugetConfig {
param(
[Parameter(Mandatory = $true, ParameterSetName = 'user')]
[Parameter(Mandatory = $true, ParameterSetName = 'nouser')]
[ValidateSet('Public', 'Private', 'NuGetOnly')]
[string] $Source,
[Parameter(Mandatory = $true, ParameterSetName = 'user')]
[string] $UserName,
[Parameter(Mandatory = $true, ParameterSetName = 'user')]
[string] $ClearTextPAT
)
Clear-PipelineNugetAuthentication
$extraParams = @()
if ($UserName) {
$extraParams = @{
UserName = $UserName
ClearTextPAT = $ClearTextPAT
}
}
$dotnetSdk = [NugetPackageSource] @{Url = 'https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet9/nuget/v2'; Name = 'dotnet' }
$gallery = [NugetPackageSource] @{Url = 'https://www.powershellgallery.com/api/v2/'; Name = 'psgallery' }
$nugetorg = [NugetPackageSource] @{Url = 'https://api.nuget.org/v3/index.json'; Name = 'nuget.org' }
if ( $Source -eq 'Public') {
New-NugetConfigFile -NugetPackageSource $nugetorg, $dotnetSdk -Destination "$PSScriptRoot/" @extraParams
New-NugetConfigFile -NugetPackageSource $gallery -Destination "$PSScriptRoot/src/Modules/" @extraParams
New-NugetConfigFile -NugetPackageSource $gallery -Destination "$PSScriptRoot/test/tools/Modules/" @extraParams
} elseif ( $Source -eq 'NuGetOnly') {
New-NugetConfigFile -NugetPackageSource $nugetorg -Destination "$PSScriptRoot/" @extraParams
New-NugetConfigFile -NugetPackageSource $gallery -Destination "$PSScriptRoot/src/Modules/" @extraParams
New-NugetConfigFile -NugetPackageSource $gallery -Destination "$PSScriptRoot/test/tools/Modules/" @extraParams
} elseif ( $Source -eq 'Private') {
$powerShellPackages = [NugetPackageSource] @{Url = 'https://pkgs.dev.azure.com/powershell/PowerShell/_packaging/PowerShell/nuget/v3/index.json'; Name = 'powershell' }
New-NugetConfigFile -NugetPackageSource $powerShellPackages -Destination "$PSScriptRoot/" @extraParams
New-NugetConfigFile -NugetPackageSource $powerShellPackages -Destination "$PSScriptRoot/src/Modules/" @extraParams
New-NugetConfigFile -NugetPackageSource $powerShellPackages -Destination "$PSScriptRoot/test/tools/Modules/" @extraParams
} else {
throw "Unknown source: $Source"
}
if ($UserName -or $ClearTextPAT) {
Set-PipelineNugetAuthentication
}
}
function Test-ShouldGenerateExperimentalFeatures
{
param(
[Parameter(Mandatory)]
$Runtime
)
if ($env:PS_RELEASE_BUILD) {
return $false
}
if ($Runtime -like 'fxdependent*') {
return $false
}
$runtimePattern = 'unknown-'
if ($environment.IsWindows) {
$runtimePattern = '^win.*-'
}
if ($environment.IsMacOS) {
$runtimePattern = '^osx.*-'
}
if ($environment.IsLinux) {
$runtimePattern = '^linux.*-'
}
$runtimePattern += $environment.OSArchitecture.ToString()
Write-Verbose "runtime pattern check: $Runtime -match $runtimePattern" -Verbose
if ($Runtime -match $runtimePattern) {
Write-Verbose "Generating experimental feature list" -Verbose
return $true
}
Write-Verbose "Skipping generating experimental feature list" -Verbose
return $false
}
function Restore-PSPackage
{
[CmdletBinding()]
param(
[ValidateNotNullOrEmpty()]
[Parameter()]
[string[]] $ProjectDirs,
[ValidateNotNullOrEmpty()]
[Parameter()]
$Options = (Get-PSOptions -DefaultToNew),
[switch] $Force,
[switch] $InteractiveAuth,
[switch] $PSModule
)
if (-not $ProjectDirs)
{
$ProjectDirs = @($Options.Top, "$PSScriptRoot/src/TypeCatalogGen", "$PSScriptRoot/src/ResGen", "$PSScriptRoot/src/Modules", "$PSScriptRoot/tools/wix")
if ($Options.Runtime -like 'fxdependent*') {
$ProjectDirs += "$PSScriptRoot/src/Microsoft.PowerShell.GlobalTool.Shim"
}
}
if ($Force -or (-not (Test-Path "$($Options.Top)/obj/project.assets.json"))) {
if ($Options.Runtime -eq 'fxdependent-win-desktop') {
$sdkToUse = 'Microsoft.NET.Sdk.WindowsDesktop'
}
else {
$sdkToUse = 'Microsoft.NET.Sdk'
if (($Options.Runtime -like 'win7-*' -or $Options.Runtime -eq 'win-arm64') -and !$Options.ForMinimalSize) {
$sdkToUse = 'Microsoft.NET.Sdk.WindowsDesktop'
}
}
if ($PSModule.IsPresent) {
$RestoreArguments = @("--verbosity")
}
elseif ($Options.Runtime -notlike 'fxdependent*') {
$RestoreArguments = @("--runtime", $Options.Runtime, "/property:SDKToUse=$sdkToUse", "--verbosity")
} else {
$RestoreArguments = @("/property:SDKToUse=$sdkToUse", "--verbosity")
}
if ($VerbosePreference -eq 'Continue') {
$RestoreArguments += "detailed"
} else {
$RestoreArguments += "quiet"
}
if ($Options.Runtime -like 'win*') {
$RestoreArguments += "/property:EnableWindowsTargeting=True"
$RestoreArguments += "/property:UseRidGraph=True"
}
if ($InteractiveAuth) {
$RestoreArguments += "--interactive"
}
if ($env:ENABLE_MSBUILD_BINLOGS -eq 'true') {
$RestoreArguments += '-bl'
}
$ProjectDirs | ForEach-Object {
$project = $_
Write-Log -message "Run dotnet restore $project $RestoreArguments"
$retryCount = 0
$maxTries = 5
while($retryCount -lt $maxTries)
{
try
{
Start-NativeExecution { dotnet restore $project $RestoreArguments }
}
catch
{
Write-Log -message "Failed to restore $project, retrying..."
$retryCount++
if($retryCount -ge $maxTries)
{
if ($env:ENABLE_MSBUILD_BINLOGS -eq 'true') {
if ( Test-Path ./msbuild.binlog ) {
if (!(Test-Path $env:OB_OUTPUTDIRECTORY -PathType Container)) {
$null = New-Item -path $env:OB_OUTPUTDIRECTORY -ItemType Directory -Force -Verbose
}
$projectName = Split-Path -Leaf -Path $project
$binlogFileName = "${projectName}.msbuild.binlog"
if ($IsMacOS) {
$resolvedPath = (Resolve-Path -Path ./msbuild.binlog).ProviderPath
Write-Host "##vso[artifact.upload containerfolder=$binLogFileName;artifactname=$binLogFileName]$resolvedPath"
} else {
Copy-Item -Path ./msbuild.binlog -Destination "$env:OB_OUTPUTDIRECTORY/${projectName}.msbuild.binlog" -Verbose
}
}
}
throw
}
continue
}
Write-Log -message "Done restoring $project"
break
}
}
}
}
function Restore-PSModuleToBuild
{
param(
[Parameter(Mandatory)]
[string]
$PublishPath
)
Write-Log -message "Restore PowerShell modules to $publishPath"
$modulesDir = Join-Path -Path $publishPath -ChildPath "Modules"
Copy-PSGalleryModules -Destination $modulesDir -CsProjPath "$PSScriptRoot\src\Modules\PSGalleryModules.csproj"
# Remove .nupkg.metadata files
Get-ChildItem $PublishPath -Filter '.nupkg.metadata' -Recurse | ForEach-Object { Remove-Item $_.FullName -ErrorAction SilentlyContinue -Force }
}
function Restore-PSPester
{
param(
[ValidateNotNullOrEmpty()]
[string] $Destination = ([IO.Path]::Combine((Split-Path (Get-PSOptions -DefaultToNew).Output), "Modules"))
)
Save-Module -Name Pester -Path $Destination -Repository PSGallery -MaximumVersion 4.99
}
function Compress-TestContent {
[CmdletBinding()]
param(
$Destination
)
$null = Publish-PSTestTools
$powerShellTestRoot = Join-Path $PSScriptRoot 'test'
Add-Type -AssemblyName System.IO.Compression.FileSystem
$resolvedPath = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Destination)
[System.IO.Compression.ZipFile]::CreateFromDirectory($powerShellTestRoot, $resolvedPath)
}
function New-PSOptions {
[CmdletBinding()]
param(
[ValidateSet('Debug', 'Release', 'CodeCoverage', 'StaticAnalysis', '')]
[string]$Configuration,
[ValidateSet("net9.0")]
[string]$Framework = "net9.0",
# These are duplicated from Start-PSBuild
# We do not use ValidateScript since we want tab completion
[ValidateSet("",
"linux-musl-x64",
"fxdependent",
"fxdependent-noopt-linux-musl-x64",
"fxdependent-linux-x64",
"fxdependent-linux-arm64",
"fxdependent-win-desktop",
"linux-arm",
"linux-arm64",