forked from PowerShell/PowerShell
-
Notifications
You must be signed in to change notification settings - Fork 0
/
build.psm1
3212 lines (2774 loc) · 113 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"
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
$dotnetAzureFeed = $dotnetMetadata.Sdk.azureFeed
$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}"}
}
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) {
$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'}
# 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)
) {
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
}
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,
# 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("alpine-x64",
"fxdependent",
"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', '')] # 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'"
}
}
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 = Get-LatestInstalledSDK
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*' -or ($Options.Runtime -like 'fxdependent*' -and $environment.IsWindows)) {
$Arguments += "/property:IsWindows=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) {
$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
}
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.
$incFileName = "powershell_$($Options.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*') {
$sdkToUse = 'Microsoft.NET.Sdk'
if ($Options.Runtime -like 'win7-*' -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 {
$globalToolSrcFolder = Resolve-Path (Join-Path $Options.Top "../Microsoft.PowerShell.GlobalTool.Shim") | Select-Object -ExpandProperty Path
if ($Options.Runtime -eq 'fxdependent') {
$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
$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 = @{}
if ($environment.IsWindows) {
$config = @{ "Microsoft.PowerShell:ExecutionPolicy" = "RemoteSigned";
"WindowsPowerShellCompatibilityModuleDenyList" = @("PSScheduledJob","BestPractices","UpdateServices") }
}
# When building preview, we want the configuration to enable all experiemental features by default
# ARM is cross compiled, so we can't run pwsh to enumerate Experimental Features
if (-not $SkipExperimentalFeatureGeneration -and
(Test-IsPreview $psVersion) -and
-not (Test-IsReleaseCandidate $psVersion) -and
-not $Runtime.Contains("arm") -and
-not ($Runtime -like 'fxdependent*')) {
$json = & $publishPath\pwsh -noprofile -command {
# Special case for DSC code in PS;
# this experimental feature requires new DSC module that is not inbox,
# so we don't want default DSC use case be broken
[System.Collections.ArrayList] $expFeatures = Get-ExperimentalFeature | Where-Object Name -NE PS7DscSupport | ForEach-Object -MemberName Name
$expFeatures | Out-String | Write-Verbose -Verbose
# Make sure ExperimentalFeatures from modules in PSHome are added
# https://github.com/PowerShell/PowerShell/issues/10550
$ExperimentalFeaturesFromGalleryModulesInPSHome = @()
$ExperimentalFeaturesFromGalleryModulesInPSHome | ForEach-Object {
if (!$expFeatures.Contains($_)) {
$null = $expFeatures.Add($_)
}
}
ConvertTo-Json $expFeatures
}
$config += @{ ExperimentalFeatures = ([string[]] ($json | ConvertFrom-Json)) }
}
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
}
# Restore the Pester module
if ($CI) {
Restore-PSPester -Destination (Join-Path $publishPath "Modules")
}
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 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")
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-*' -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 ($InteractiveAuth) {
$RestoreArguments += "--interactive"
}
$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)
{
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", '')]
[string]$Configuration,
[ValidateSet("net6.0")]
[string]$Framework = "net6.0",
# These are duplicated from Start-PSBuild
# We do not use ValidateScript since we want tab completion
[ValidateSet("",
"alpine-x64",
"fxdependent",
"fxdependent-win-desktop",
"linux-arm",
"linux-arm64",
"linux-x64",
"osx-arm64",
"osx-x64",
"win-arm",
"win-arm64",
"win7-x64",
"win7-x86")]
[string]$Runtime,
# Accept a path to the output directory
# If not null or empty, name of the executable will be appended to
# this path, otherwise, to the default path, and then the full path
# of the output executable will be assigned to the Output property
[string]$Output,
[switch]$SMAOnly,
[switch]$PSModuleRestore,
[switch]$ForMinimalSize
)
# Add .NET CLI tools to PATH
Find-Dotnet
if (-not $Configuration) {
$Configuration = 'Debug'
}
Write-Verbose "Using configuration '$Configuration'"
Write-Verbose "Using framework '$Framework'"
if (-not $Runtime) {
if ($environment.IsLinux) {
$Runtime = "linux-x64"
} elseif ($environment.IsMacOS) {
if ($PSVersionTable.OS.Contains('ARM64')) {
$Runtime = "osx-arm64"
}
else {
$Runtime = "osx-x64"
}
} else {
$RID = dotnet --info | ForEach-Object {
if ($_ -match "RID") {
$_ -split "\s+" | Select-Object -Last 1
}
}
# We plan to release packages targeting win7-x64 and win7-x86 RIDs,
# which supports all supported windows platforms.
# So we, will change the RID to win7-<arch>
$Runtime = $RID -replace "win\d+", "win7"
}
if (-not $Runtime) {
Throw "Could not determine Runtime Identifier, please update dotnet"
} else {
Write-Verbose "Using runtime '$Runtime'"
}
}
$PowerShellDir = if ($Runtime -like 'win*' -or ($Runtime -like 'fxdependent*' -and $environment.IsWindows)) {
"powershell-win-core"
} else {
"powershell-unix"
}
$Top = [IO.Path]::Combine($PSScriptRoot, "src", $PowerShellDir)
Write-Verbose "Top project directory is $Top"
$Executable = if ($Runtime -like 'fxdependent*') {
"pwsh.dll"
} elseif ($environment.IsLinux -or $environment.IsMacOS) {
"pwsh"
} elseif ($environment.IsWindows) {
"pwsh.exe"
}
# Build the Output path
if (!$Output) {
if ($Runtime -like 'fxdependent*') {
$Output = [IO.Path]::Combine($Top, "bin", $Configuration, $Framework, "publish", $Executable)
} else {
$Output = [IO.Path]::Combine($Top, "bin", $Configuration, $Framework, $Runtime, "publish", $Executable)
}
} else {
$Output = [IO.Path]::Combine($Output, $Executable)
}
if ($SMAOnly)
{
$Top = [IO.Path]::Combine($PSScriptRoot, "src", "System.Management.Automation")
}
$RootInfo = @{RepoPath = $PSScriptRoot}
# the valid root is the root of the filesystem and the folder PowerShell
$RootInfo['ValidPath'] = Join-Path -Path ([system.io.path]::GetPathRoot($RootInfo.RepoPath)) -ChildPath 'PowerShell'
if($RootInfo.RepoPath -ne $RootInfo.ValidPath)
{
$RootInfo['Warning'] = "Please ensure your repo is at the root of the file system and named 'PowerShell' (example: '$($RootInfo.ValidPath)'), when building and packaging for release!"
$RootInfo['IsValid'] = $false
}
else
{
$RootInfo['IsValid'] = $true
}
return New-PSOptionsObject `
-RootInfo ([PSCustomObject]$RootInfo) `
-Top $Top `
-Runtime $Runtime `
-Configuration $Configuration `
-PSModuleRestore $PSModuleRestore.IsPresent `
-Framework $Framework `
-Output $Output `
-ForMinimalSize $ForMinimalSize
}
# Get the Options of the last build
function Get-PSOptions {
param(
[Parameter(HelpMessage='Defaults to New-PSOption if a build has not occurred.')]
[switch]
$DefaultToNew
)
if (!$script:Options -and $DefaultToNew.IsPresent)
{
return New-PSOptions
}
return $script:Options
}
function Set-PSOptions {
param(
[PSObject]
$Options
)
$script:Options = $Options
}
function Get-PSOutput {
[CmdletBinding()]param(
[hashtable]$Options
)
if ($Options) {
return $Options.Output
} elseif ($script:Options) {
return $script:Options.Output
} else {
return (New-PSOptions).Output
}
}
function Get-PesterTag {
param ( [Parameter(Position=0)][string]$testbase = "$PSScriptRoot/test/powershell" )
$alltags = @{}
$warnings = @()
Get-ChildItem -Recurse $testbase -File | Where-Object {$_.name -match "tests.ps1"}| ForEach-Object {
$fullname = $_.fullname
$tok = $err = $null
$ast = [System.Management.Automation.Language.Parser]::ParseFile($FullName, [ref]$tok,[ref]$err)
$des = $ast.FindAll({
$args[0] -is [System.Management.Automation.Language.CommandAst] `
-and $args[0].CommandElements.GetType() -in @(
[System.Management.Automation.Language.StringConstantExpressionAst],
[System.Management.Automation.Language.ExpandableStringExpressionAst]
) `
-and $args[0].CommandElements[0].Value -eq "Describe"
}, $true)
foreach( $describe in $des) {
$elements = $describe.CommandElements
$lineno = $elements[0].Extent.StartLineNumber