forked from PowerShell/PowerShell
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpackaging.psm1
3800 lines (3186 loc) · 142 KB
/
packaging.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.
$Environment = Get-EnvironmentInformation
$RepoRoot = (Resolve-Path -Path "$PSScriptRoot/../..").Path
$packagingStrings = Import-PowerShellDataFile "$PSScriptRoot\packaging.strings.psd1"
Import-Module "$PSScriptRoot\..\Xml" -ErrorAction Stop -Force
$DebianDistributions = @("ubuntu.16.04", "ubuntu.18.04", "debian.9", "debian.10", "debian.11")
$RedhatDistributions = @("rhel.7","centos.8")
$script:netCoreRuntime = 'net5.0'
function Start-PSPackage {
[CmdletBinding(DefaultParameterSetName='Version',SupportsShouldProcess=$true)]
param(
# PowerShell packages use Semantic Versioning https://semver.org/
[Parameter(ParameterSetName = "Version")]
[string]$Version,
[Parameter(ParameterSetName = "ReleaseTag")]
[ValidatePattern("^v\d+\.\d+\.\d+(-\w+(\.\d+)?)?$")]
[ValidateNotNullOrEmpty()]
[string]$ReleaseTag,
# Package name
[ValidatePattern("^powershell")]
[string]$Name = "powershell",
# Ubuntu, CentOS, Fedora, macOS, and Windows packages are supported
[ValidateSet("msix", "deb", "osxpkg", "rpm", "msi", "zip", "zip-pdb", "nupkg", "tar", "tar-arm", "tar-arm64", "tar-alpine", "fxdependent", "fxdependent-win-desktop")]
[string[]]$Type,
# Generate windows downlevel package
[ValidateSet("win7-x86", "win7-x64", "win-arm", "win-arm64")]
[ValidateScript({$Environment.IsWindows})]
[string] $WindowsRuntime,
[Switch] $Force,
[Switch] $SkipReleaseChecks,
[switch] $NoSudo,
[switch] $LTS
)
DynamicParam {
if ("zip" -eq $Type -or "fxdependent" -eq $Type -or "fxdependent-win-desktop" -eq $Type) {
# Add a dynamic parameter '-IncludeSymbols' when the specified package type is 'zip' only.
# The '-IncludeSymbols' parameter can be used to indicate that the package should only contain powershell binaries and symbols.
$ParameterAttr = New-Object "System.Management.Automation.ParameterAttribute"
$Attributes = New-Object "System.Collections.ObjectModel.Collection``1[System.Attribute]"
$Attributes.Add($ParameterAttr) > $null
$Parameter = New-Object "System.Management.Automation.RuntimeDefinedParameter" -ArgumentList ("IncludeSymbols", [switch], $Attributes)
$Dict = New-Object "System.Management.Automation.RuntimeDefinedParameterDictionary"
$Dict.Add("IncludeSymbols", $Parameter) > $null
return $Dict
}
}
End {
$IncludeSymbols = $null
if ($PSBoundParameters.ContainsKey('IncludeSymbols')) {
Write-Log 'setting IncludeSymbols'
$IncludeSymbols = $PSBoundParameters['IncludeSymbols']
}
# Runtime and Configuration settings required by the package
($Runtime, $Configuration) = if ($WindowsRuntime) {
$WindowsRuntime, "Release"
} elseif ($Type -eq "tar-alpine") {
New-PSOptions -Configuration "Release" -Runtime "alpine-x64" -WarningAction SilentlyContinue | ForEach-Object { $_.Runtime, $_.Configuration }
} elseif ($Type -eq "tar-arm") {
New-PSOptions -Configuration "Release" -Runtime "Linux-ARM" -WarningAction SilentlyContinue | ForEach-Object { $_.Runtime, $_.Configuration }
} elseif ($Type -eq "tar-arm64") {
New-PSOptions -Configuration "Release" -Runtime "Linux-ARM64" -WarningAction SilentlyContinue | ForEach-Object { $_.Runtime, $_.Configuration }
} else {
New-PSOptions -Configuration "Release" -WarningAction SilentlyContinue | ForEach-Object { $_.Runtime, $_.Configuration }
}
if ($Environment.IsWindows) {
# Runtime will be one of win7-x64, win7-x86, "win-arm" and "win-arm64" on Windows.
# Build the name suffix for universal win-plat packages.
switch ($Runtime) {
"win-arm" { $NameSuffix = "win-arm32" }
"win-arm64" { $NameSuffix = "win-arm64" }
default { $NameSuffix = $_ -replace 'win\d+', 'win' }
}
}
if ($Type -eq 'fxdependent') {
$NameSuffix = "win-fxdependent"
Write-Log "Packaging : '$Type'; Packaging Configuration: '$Configuration'"
} elseif ($Type -eq 'fxdependent-win-desktop') {
$NameSuffix = "win-fxdependentWinDesktop"
Write-Log "Packaging : '$Type'; Packaging Configuration: '$Configuration'"
} else {
Write-Log "Packaging RID: '$Runtime'; Packaging Configuration: '$Configuration'"
}
$Script:Options = Get-PSOptions
$actualParams = @()
$crossGenCorrect = $false
if ($Runtime -match "arm") {
# crossgen doesn't support arm32/64
$crossGenCorrect = $true
}
elseif ($Script:Options.CrossGen) {
$actualParams += '-CrossGen'
$crossGenCorrect = $true
}
$PSModuleRestoreCorrect = $false
# Require PSModuleRestore for packaging without symbols
# But Disallow it when packaging with symbols
if (!$IncludeSymbols.IsPresent -and $Script:Options.PSModuleRestore) {
$actualParams += '-PSModuleRestore'
$PSModuleRestoreCorrect = $true
}
elseif ($IncludeSymbols.IsPresent -and !$Script:Options.PSModuleRestore) {
$PSModuleRestoreCorrect = $true
}
else {
$actualParams += '-PSModuleRestore'
}
$precheckFailed = if ($Type -like 'fxdependent*' -or $Type -eq 'tar-alpine') {
## We do not check for runtime and crossgen for framework dependent package.
-not $Script:Options -or ## Start-PSBuild hasn't been executed yet
-not $PSModuleRestoreCorrect -or ## Last build didn't specify '-PSModuleRestore' correctly
$Script:Options.Configuration -ne $Configuration -or ## Last build was with configuration other than 'Release'
$Script:Options.Framework -ne $script:netCoreRuntime ## Last build wasn't for CoreCLR
} else {
-not $Script:Options -or ## Start-PSBuild hasn't been executed yet
-not $crossGenCorrect -or ## Last build didn't specify '-CrossGen' correctly
-not $PSModuleRestoreCorrect -or ## Last build didn't specify '-PSModuleRestore' correctly
$Script:Options.Runtime -ne $Runtime -or ## Last build wasn't for the required RID
$Script:Options.Configuration -ne $Configuration -or ## Last build was with configuration other than 'Release'
$Script:Options.Framework -ne $script:netCoreRuntime ## Last build wasn't for CoreCLR
}
# Make sure the most recent build satisfies the package requirement
if ($precheckFailed) {
# It's possible that the most recent build doesn't satisfy the package requirement but
# an earlier build does.
# It's also possible that the last build actually satisfies the package requirement but
# then `Start-PSPackage` runs from a new PS session or `build.psm1` was reloaded.
#
# In these cases, the user will be asked to build again even though it's technically not
# necessary. However, we want it that way -- being very explict when generating packages.
# This check serves as a simple gate to ensure that the user knows what he is doing, and
# also ensure `Start-PSPackage` does what the user asks/expects, because once packages
# are generated, it'll be hard to verify if they were built from the correct content.
$params = @('-Clean')
# CrossGen cannot be done for framework dependent package as it is runtime agnostic.
if ($Type -notlike 'fxdependent*') {
$params += '-CrossGen'
}
if (!$IncludeSymbols.IsPresent) {
$params += '-PSModuleRestore'
}
$actualParams += '-Runtime ' + $Script:Options.Runtime
if ($Type -eq 'fxdependent') {
$params += '-Runtime', 'fxdependent'
} elseif ($Type -eq 'fxdependent-win-desktop') {
$params += '-Runtime', 'fxdependent-win-desktop'
} else {
$params += '-Runtime', $Runtime
}
$params += '-Configuration', $Configuration
$actualParams += '-Configuration ' + $Script:Options.Configuration
Write-Warning "Build started with unexpected parameters 'Start-PSBuild $actualParams"
throw "Please ensure you have run 'Start-PSBuild $params'!"
}
if ($SkipReleaseChecks.IsPresent) {
Write-Warning "Skipping release checks."
}
elseif (!$Script:Options.RootInfo.IsValid){
throw $Script:Options.RootInfo.Warning
}
# If ReleaseTag is specified, use the given tag to calculate Vesrion
if ($PSCmdlet.ParameterSetName -eq "ReleaseTag") {
$Version = $ReleaseTag -Replace '^v'
}
# Use Git tag if not given a version
if (-not $Version) {
$Version = (git --git-dir="$RepoRoot/.git" describe) -Replace '^v'
}
$Source = Split-Path -Path $Script:Options.Output -Parent
# Copy the ThirdPartyNotices.txt so it's part of the package
Copy-Item "$RepoRoot/ThirdPartyNotices.txt" -Destination $Source -Force
# If building a symbols package, we add a zip of the parent to publish
if ($IncludeSymbols.IsPresent)
{
$publishSource = $Source
$buildSource = Split-Path -Path $Source -Parent
$Source = New-TempFolder
$symbolsSource = New-TempFolder
try
{
# Copy files which go into the root package
Get-ChildItem -Path $publishSource | Copy-Item -Destination $Source -Recurse
$signingXml = [xml] (Get-Content (Join-Path $PSScriptRoot "..\releaseBuild\signing.xml" -Resolve))
# Only include the files we sign for compliance scanning, those are the files we build.
$filesToInclude = $signingXml.SignConfigXML.job.file.src | Where-Object { -not $_.endswith('pwsh.exe') -and ($_.endswith(".dll") -or $_.endswith(".exe")) } | ForEach-Object { ($_ -split '\\')[-1] }
$filesToInclude += $filesToInclude | ForEach-Object { $_ -replace '.dll', '.pdb' }
Get-ChildItem -Path $buildSource | Where-Object { $_.Name -in $filesToInclude } | Copy-Item -Destination $symbolsSource -Recurse
# Zip symbols.zip to the root package
$zipSource = Join-Path $symbolsSource -ChildPath '*'
$zipPath = Join-Path -Path $Source -ChildPath 'symbols.zip'
Save-PSOptions -PSOptionsPath (Join-Path -Path $source -ChildPath 'psoptions.json') -Options $Script:Options
Compress-Archive -Path $zipSource -DestinationPath $zipPath
}
finally
{
Remove-Item -Path $symbolsSource -Recurse -Force -ErrorAction SilentlyContinue
}
}
Write-Log "Packaging Source: '$Source'"
# Decide package output type
if (-not $Type) {
$Type = if ($Environment.IsLinux) {
if ($Environment.LinuxInfo.ID -match "ubuntu") {
"deb", "nupkg", "tar"
} elseif ($Environment.IsRedHatFamily) {
"rpm", "nupkg"
} elseif ($Environment.IsSUSEFamily) {
"rpm", "nupkg"
} else {
throw "Building packages for $($Environment.LinuxInfo.PRETTY_NAME) is unsupported!"
}
} elseif ($Environment.IsMacOS) {
"osxpkg", "nupkg", "tar"
} elseif ($Environment.IsWindows) {
"msi", "nupkg", "msix"
}
Write-Warning "-Type was not specified, continuing with $Type!"
}
Write-Log "Packaging Type: $Type"
# Add the symbols to the suffix
# if symbols are specified to be included
if ($IncludeSymbols.IsPresent -and $NameSuffix) {
$NameSuffix = "symbols-$NameSuffix"
}
elseif ($IncludeSymbols.IsPresent) {
$NameSuffix = "symbols"
}
switch ($Type) {
"zip" {
$Arguments = @{
PackageNameSuffix = $NameSuffix
PackageSourcePath = $Source
PackageVersion = $Version
Force = $Force
}
if ($PSCmdlet.ShouldProcess("Create Zip Package")) {
New-ZipPackage @Arguments
}
}
"zip-pdb" {
$Arguments = @{
PackageNameSuffix = $NameSuffix
PackageSourcePath = $Source
PackageVersion = $Version
Force = $Force
}
if ($PSCmdlet.ShouldProcess("Create Symbols Zip Package")) {
New-PdbZipPackage @Arguments
}
}
{ $_ -like "fxdependent*" } {
## Remove PDBs from package to reduce size.
if(-not $IncludeSymbols.IsPresent) {
Get-ChildItem $Source -Filter *.pdb | Remove-Item -Force
}
if ($Environment.IsWindows) {
$Arguments = @{
PackageNameSuffix = $NameSuffix
PackageSourcePath = $Source
PackageVersion = $Version
Force = $Force
}
if ($PSCmdlet.ShouldProcess("Create Zip Package")) {
New-ZipPackage @Arguments
}
} elseif ($IsLinux) {
$Arguments = @{
PackageSourcePath = $Source
Name = $Name
PackageNameSuffix = 'fxdependent'
Version = $Version
Force = $Force
}
if ($PSCmdlet.ShouldProcess("Create tar.gz Package")) {
New-TarballPackage @Arguments
}
}
}
"msi" {
$TargetArchitecture = "x64"
if ($Runtime -match "-x86") {
$TargetArchitecture = "x86"
}
$Arguments = @{
ProductNameSuffix = $NameSuffix
ProductSourcePath = $Source
ProductVersion = $Version
AssetsPath = "$RepoRoot\assets"
# Product Code needs to be unique for every PowerShell version since it is a unique identifier for the particular product release
ProductCode = New-Guid
ProductTargetArchitecture = $TargetArchitecture
Force = $Force
}
if ($PSCmdlet.ShouldProcess("Create MSI Package")) {
New-MSIPackage @Arguments
}
}
"msix" {
$Arguments = @{
ProductNameSuffix = $NameSuffix
ProductSourcePath = $Source
ProductVersion = $Version
Architecture = $WindowsRuntime.Split('-')[1]
Force = $Force
}
if ($PSCmdlet.ShouldProcess("Create MSIX Package")) {
New-MSIXPackage @Arguments
}
}
'nupkg' {
$Arguments = @{
PackageNameSuffix = $NameSuffix
PackageSourcePath = $Source
PackageVersion = $Version
PackageRuntime = $Runtime
PackageConfiguration = $Configuration
Force = $Force
}
if ($PSCmdlet.ShouldProcess("Create NuPkg Package")) {
New-NugetContentPackage @Arguments
}
}
"tar" {
$Arguments = @{
PackageSourcePath = $Source
Name = $Name
Version = $Version
Force = $Force
}
if ($PSCmdlet.ShouldProcess("Create tar.gz Package")) {
New-TarballPackage @Arguments
}
}
"tar-arm" {
$Arguments = @{
PackageSourcePath = $Source
Name = $Name
Version = $Version
Force = $Force
Architecture = "arm32"
ExcludeSymbolicLinks = $true
}
if ($PSCmdlet.ShouldProcess("Create tar.gz Package")) {
New-TarballPackage @Arguments
}
}
"tar-arm64" {
$Arguments = @{
PackageSourcePath = $Source
Name = $Name
Version = $Version
Force = $Force
Architecture = "arm64"
ExcludeSymbolicLinks = $true
}
if ($PSCmdlet.ShouldProcess("Create tar.gz Package")) {
New-TarballPackage @Arguments
}
}
"tar-alpine" {
$Arguments = @{
PackageSourcePath = $Source
Name = $Name
Version = $Version
Force = $Force
Architecture = "alpine-x64"
ExcludeSymbolicLinks = $true
}
if ($PSCmdlet.ShouldProcess("Create tar.gz Package")) {
New-TarballPackage @Arguments
}
}
'deb' {
$Arguments = @{
Type = 'deb'
PackageSourcePath = $Source
Name = $Name
Version = $Version
Force = $Force
NoSudo = $NoSudo
LTS = $LTS
}
foreach ($Distro in $Script:DebianDistributions) {
$Arguments["Distribution"] = $Distro
if ($PSCmdlet.ShouldProcess("Create DEB Package for $Distro")) {
New-UnixPackage @Arguments
}
}
}
'rpm' {
$Arguments = @{
Type = 'rpm'
PackageSourcePath = $Source
Name = $Name
Version = $Version
Force = $Force
NoSudo = $NoSudo
LTS = $LTS
}
foreach ($Distro in $Script:RedhatDistributions) {
$Arguments["Distribution"] = $Distro
if ($PSCmdlet.ShouldProcess("Create RPM Package for $Distro")) {
New-UnixPackage @Arguments
}
}
}
default {
$Arguments = @{
Type = $_
PackageSourcePath = $Source
Name = $Name
Version = $Version
Force = $Force
NoSudo = $NoSudo
LTS = $LTS
}
if ($PSCmdlet.ShouldProcess("Create $_ Package")) {
New-UnixPackage @Arguments
}
}
}
if ($IncludeSymbols.IsPresent)
{
# Source is a temporary folder when -IncludeSymbols is present. So, we should remove it.
Remove-Item -Path $Source -Recurse -Force -ErrorAction SilentlyContinue
}
}
}
function New-TarballPackage {
[CmdletBinding(SupportsShouldProcess=$true)]
param (
[Parameter(Mandatory)]
[string] $PackageSourcePath,
# Must start with 'powershell' but may have any suffix
[Parameter(Mandatory)]
[ValidatePattern("^powershell")]
[string] $Name,
# Suffix of the Name
[string] $PackageNameSuffix,
[Parameter(Mandatory)]
[string] $Version,
[Parameter()]
[string] $Architecture = "x64",
[switch] $Force,
[switch] $ExcludeSymbolicLinks
)
if ($PackageNameSuffix) {
$packageName = "$Name-$Version-{0}-$Architecture-$PackageNameSuffix.tar.gz"
} else {
$packageName = "$Name-$Version-{0}-$Architecture.tar.gz"
}
if ($Environment.IsWindows) {
throw "Must be on Linux or macOS to build 'tar.gz' packages!"
} elseif ($Environment.IsLinux) {
$packageName = $packageName -f "linux"
} elseif ($Environment.IsMacOS) {
$packageName = $packageName -f "osx"
}
$packagePath = Join-Path -Path $PWD -ChildPath $packageName
Write-Verbose "Create package $packageName"
Write-Verbose "Package destination path: $packagePath"
if (Test-Path -Path $packagePath) {
if ($Force -or $PSCmdlet.ShouldProcess("Overwrite existing package file")) {
Write-Verbose "Overwrite existing package file at $packagePath" -Verbose
Remove-Item -Path $packagePath -Force -ErrorAction Stop -Confirm:$false
}
}
$Staging = "$PSScriptRoot/staging"
New-StagingFolder -StagingPath $Staging -PackageSourcePath $PackageSourcePath
if (-not $ExcludeSymbolicLinks.IsPresent) {
New-PSSymbolicLinks -Distribution 'ubuntu.16.04' -Staging $Staging
}
if (Get-Command -Name tar -CommandType Application -ErrorAction Ignore) {
if ($Force -or $PSCmdlet.ShouldProcess("Create tarball package")) {
$options = "-czf"
if ($PSBoundParameters.ContainsKey('Verbose') -and $PSBoundParameters['Verbose'].IsPresent) {
# Use the verbose mode '-v' if '-Verbose' is specified
$options = "-czvf"
}
try {
Push-Location -Path $Staging
tar $options $packagePath .
} finally {
Pop-Location
}
if (Test-Path -Path $packagePath) {
Write-Log "You can find the tarball package at $packagePath"
return (Get-Item $packagePath)
} else {
throw "Failed to create $packageName"
}
}
} else {
throw "Failed to create the package because the application 'tar' cannot be found"
}
}
function New-TempFolder
{
$tempPath = [System.IO.Path]::GetTempPath()
$tempFolder = Join-Path -Path $tempPath -ChildPath ([System.IO.Path]::GetRandomFileName())
if (!(Test-Path -Path $tempFolder))
{
$null = New-Item -Path $tempFolder -ItemType Directory
}
return $tempFolder
}
function New-PSSignedBuildZip
{
param(
[Parameter(Mandatory)]
[string]$BuildPath,
[Parameter(Mandatory)]
[string]$SignedFilesPath,
[Parameter(Mandatory)]
[string]$DestinationFolder,
[parameter(HelpMessage='VSTS variable to set for path to zip')]
[string]$VstsVariableName
)
Update-PSSignedBuildFolder -BuildPath $BuildPath -SignedFilesPath $SignedFilesPath
# Remove '$signedFilesPath' now that signed binaries are copied
if (Test-Path $signedFilesPath)
{
Remove-Item -Recurse -Force -Path $signedFilesPath
}
New-PSBuildZip -BuildPath $BuildPath -DestinationFolder $DestinationFolder -VstsVariableName $VstsVariableName
}
function New-PSBuildZip
{
param(
[Parameter(Mandatory)]
[string]$BuildPath,
[Parameter(Mandatory)]
[string]$DestinationFolder,
[parameter(HelpMessage='VSTS variable to set for path to zip')]
[string]$VstsVariableName
)
$name = Split-Path -Path $BuildPath -Leaf
$zipLocationPath = Join-Path -Path $DestinationFolder -ChildPath "$name-signed.zip"
Compress-Archive -Path $BuildPath\* -DestinationPath $zipLocationPath
if ($VstsVariableName)
{
# set VSTS variable with path to package files
Write-Log "Setting $VstsVariableName to $zipLocationPath"
Write-Host "##vso[task.setvariable variable=$VstsVariableName]$zipLocationPath"
}
else
{
return $zipLocationPath
}
}
function Update-PSSignedBuildFolder
{
param(
[Parameter(Mandatory)]
[string]$BuildPath,
[Parameter(Mandatory)]
[string]$SignedFilesPath
)
# Replace unsigned binaries with signed
$signedFilesFilter = Join-Path -Path $SignedFilesPath -ChildPath '*'
Get-ChildItem -Path $signedFilesFilter -Recurse -File | Select-Object -ExpandProperty FullName | ForEach-Object -Process {
$relativePath = $_.ToLowerInvariant().Replace($SignedFilesPath.ToLowerInvariant(),'')
$destination = Join-Path -Path $BuildPath -ChildPath $relativePath
Write-Log "replacing $destination with $_"
Copy-Item -Path $_ -Destination $destination -Force
}
}
function Expand-PSSignedBuild
{
param(
[Parameter(Mandatory)]
[string]$BuildZip,
[Switch]$SkipPwshExeCheck
)
$psModulePath = Split-Path -Path $PSScriptRoot
# Expand signed build
$buildPath = Join-Path -Path $psModulePath -ChildPath 'ExpandedBuild'
$null = New-Item -Path $buildPath -ItemType Directory -Force
Expand-Archive -Path $BuildZip -DestinationPath $buildPath -Force
# Remove the zip file that contains only those files from the parent folder of 'publish'.
# That zip file is used for compliance scan.
Remove-Item -Path (Join-Path -Path $buildPath -ChildPath '*.zip') -Recurse
if ($SkipPwshExeCheck)
{
$windowsExecutablePath = (Join-Path $buildPath -ChildPath 'pwsh.dll')
}
else
{
$windowsExecutablePath = (Join-Path $buildPath -ChildPath 'pwsh.exe')
}
Restore-PSModuleToBuild -PublishPath $buildPath
$psOptionsPath = Join-Path $buildPath -ChildPath 'psoptions.json'
Restore-PSOptions -PSOptionsPath $psOptionsPath -Remove
$options = Get-PSOptions
$options.PSModuleRestore = $true
if (Test-Path -Path $windowsExecutablePath)
{
$options.Output = $windowsExecutablePath
}
else
{
throw 'Could not find pwsh'
}
Set-PSOptions -Options $options
}
function New-UnixPackage {
[CmdletBinding(SupportsShouldProcess=$true)]
param(
[Parameter(Mandatory)]
[ValidateSet("deb", "osxpkg", "rpm")]
[string]$Type,
[Parameter(Mandatory)]
[string]$PackageSourcePath,
# Must start with 'powershell' but may have any suffix
[Parameter(Mandatory)]
[ValidatePattern("^powershell")]
[string]$Name,
[Parameter(Mandatory)]
[string]$Version,
# Package iteration version (rarely changed)
# This is a string because strings are appended to it
[string]$Iteration = "1",
[Switch]
$Force,
[switch]
$NoSudo,
[switch]
$LTS
)
DynamicParam {
if ($Type -eq "deb" -or $Type -eq 'rpm') {
# Add a dynamic parameter '-Distribution' when the specified package type is 'deb'.
# The '-Distribution' parameter can be used to indicate which Debian distro this pacakge is targeting.
$ParameterAttr = New-Object "System.Management.Automation.ParameterAttribute"
if($type -eq 'deb')
{
$ValidateSetAttr = New-Object "System.Management.Automation.ValidateSetAttribute" -ArgumentList $Script:DebianDistributions
}
else
{
$ValidateSetAttr = New-Object "System.Management.Automation.ValidateSetAttribute" -ArgumentList $Script:RedHatDistributions
}
$Attributes = New-Object "System.Collections.ObjectModel.Collection``1[System.Attribute]"
$Attributes.Add($ParameterAttr) > $null
$Attributes.Add($ValidateSetAttr) > $null
$Parameter = New-Object "System.Management.Automation.RuntimeDefinedParameter" -ArgumentList ("Distribution", [string], $Attributes)
$Dict = New-Object "System.Management.Automation.RuntimeDefinedParameterDictionary"
$Dict.Add("Distribution", $Parameter) > $null
return $Dict
}
}
End {
# This allows sudo install to be optional; needed when running in containers / as root
# Note that when it is null, Invoke-Expression (but not &) must be used to interpolate properly
$sudo = if (!$NoSudo) { "sudo" }
# Validate platform
$ErrorMessage = "Must be on {0} to build '$Type' packages!"
switch ($Type) {
"deb" {
$packageVersion = Get-LinuxPackageSemanticVersion -Version $Version
if (!$Environment.IsUbuntu -and !$Environment.IsDebian) {
throw ($ErrorMessage -f "Ubuntu or Debian")
}
if ($PSBoundParameters.ContainsKey('Distribution')) {
$DebDistro = $PSBoundParameters['Distribution']
} elseif ($Environment.IsUbuntu16) {
$DebDistro = "ubuntu.16.04"
} elseif ($Environment.IsUbuntu18) {
$DebDistro = "ubuntu.18.04"
} elseif ($Environment.IsDebian9) {
$DebDistro = "debian.9"
} else {
throw "The current Debian distribution is not supported."
}
# iteration is "debian_revision"
# usage of this to differentiate distributions is allowed by non-standard
$Iteration += ".$DebDistro"
}
"rpm" {
if ($PSBoundParameters.ContainsKey('Distribution')) {
$DebDistro = $PSBoundParameters['Distribution']
} elseif ($Environment.IsRedHatFamily) {
$DebDistro = "rhel.7"
} else {
throw "The current distribution is not supported."
}
$packageVersion = Get-LinuxPackageSemanticVersion -Version $Version
if (!$Environment.IsRedHatFamily -and !$Environment.IsSUSEFamily) {
throw ($ErrorMessage -f "Redhat or SUSE Family")
}
}
"osxpkg" {
$packageVersion = $Version
if (!$Environment.IsMacOS) {
throw ($ErrorMessage -f "macOS")
}
$DebDistro = 'macOS'
}
}
# Determine if the version is a preview version
$IsPreview = Test-IsPreview -Version $Version -IsLTS:$LTS
# Preview versions have preview in the name
$Name = if($LTS) {
"powershell-lts"
}
elseif ($IsPreview) {
"powershell-preview"
}
else {
"powershell"
}
# Verify dependencies are installed and in the path
Test-Dependencies
$Description = $packagingStrings.Description
# Break the version down into its components, we are interested in the major version
$VersionMatch = [regex]::Match($Version, '(\d+)(?:.(\d+)(?:.(\d+)(?:-preview(?:.(\d+))?)?)?)?')
$MajorVersion = $VersionMatch.Groups[1].Value
# Suffix is used for side-by-side preview/release package installation
$Suffix = if ($IsPreview) { $MajorVersion + "-preview" } elseif ($LTS) { $MajorVersion + "-lts" } else { $MajorVersion }
# Setup staging directory so we don't change the original source directory
$Staging = "$PSScriptRoot/staging"
if ($PSCmdlet.ShouldProcess("Create staging folder")) {
New-StagingFolder -StagingPath $Staging -PackageSourcePath $PackageSourcePath
}
# Follow the Filesystem Hierarchy Standard for Linux and macOS
$Destination = if ($Environment.IsLinux) {
"/opt/microsoft/powershell/$Suffix"
} elseif ($Environment.IsMacOS) {
"/usr/local/microsoft/powershell/$Suffix"
}
# Destination for symlink to powershell executable
$Link = Get-PwshExecutablePath -IsPreview:$IsPreview
$links = @(New-LinkInfo -LinkDestination $Link -LinkTarget "$Destination/pwsh")
if($LTS) {
$links += New-LinkInfo -LinkDestination (Get-PwshExecutablePath -IsLTS:$LTS) -LinkTarget "$Destination/pwsh"
}
if ($PSCmdlet.ShouldProcess("Create package file system"))
{
# Generate After Install and After Remove scripts
$AfterScriptInfo = New-AfterScripts -Link $Link -Distribution $DebDistro
New-PSSymbolicLinks -Distribution $DebDistro -Staging $Staging
# there is a weird bug in fpm
# if the target of the powershell symlink exists, `fpm` aborts
# with a `utime` error on macOS.
# so we move it to make symlink broken
# refers to executable, does not vary by channel
$symlink_dest = "$Destination/pwsh"
$hack_dest = "./_fpm_symlink_hack_powershell"
if ($Environment.IsMacOS) {
if (Test-Path $symlink_dest) {
Write-Warning "Move $symlink_dest to $hack_dest (fpm utime bug)"
Start-NativeExecution ([ScriptBlock]::Create("$sudo mv $symlink_dest $hack_dest"))
}
}
# Generate gzip of man file
$ManGzipInfo = New-ManGzip -IsPreview:$IsPreview -IsLTS:$LTS
# Change permissions for packaging
Write-Log "Setting permissions..."
Start-NativeExecution {
find $Staging -type d | xargs chmod 755
find $Staging -type f | xargs chmod 644
chmod 644 $ManGzipInfo.GzipFile
# refers to executable, does not vary by channel
chmod 755 "$Staging/pwsh" #only the executable file should be granted the execution permission
}
}
# Add macOS powershell launcher
if ($Type -eq "osxpkg")
{
Write-Log "Adding macOS launch application..."
if ($PSCmdlet.ShouldProcess("Add macOS launch application"))
{
# Generate launcher app folder
$AppsFolder = New-MacOSLauncher -Version $Version
}
}
$packageDependenciesParams = @{}
if ($DebDistro)
{
$packageDependenciesParams['Distribution']=$DebDistro
}
# Setup package dependencies
$Dependencies = @(Get-PackageDependencies @packageDependenciesParams)
$Arguments = Get-FpmArguments `
-Name $Name `
-Version $packageVersion `
-Iteration $Iteration `
-Description $Description `
-Type $Type `
-Dependencies $Dependencies `
-AfterInstallScript $AfterScriptInfo.AfterInstallScript `
-AfterRemoveScript $AfterScriptInfo.AfterRemoveScript `
-Staging $Staging `
-Destination $Destination `
-ManGzipFile $ManGzipInfo.GzipFile `
-ManDestination $ManGzipInfo.ManFile `
-LinkInfo $Links `
-AppsFolder $AppsFolder `
-Distribution $DebDistro `
-ErrorAction Stop
# Build package
try {
if ($PSCmdlet.ShouldProcess("Create $type package")) {
Write-Log "Creating package with fpm..."
$Output = Start-NativeExecution { fpm $Arguments }
}
} finally {
if ($Environment.IsMacOS) {
Write-Log "Starting Cleanup for mac packaging..."
if ($PSCmdlet.ShouldProcess("Cleanup macOS launcher"))
{
Clear-MacOSLauncher
}
# this is continuation of a fpm hack for a weird bug
if (Test-Path $hack_dest) {
Write-Warning "Move $hack_dest to $symlink_dest (fpm utime bug)"
Start-NativeExecution -sb ([ScriptBlock]::Create("$sudo mv $hack_dest $symlink_dest")) -VerboseOutputOnError
}
}
if ($AfterScriptInfo.AfterInstallScript) {
Remove-Item -ErrorAction 'silentlycontinue' $AfterScriptInfo.AfterInstallScript -Force
}
if ($AfterScriptInfo.AfterRemoveScript) {
Remove-Item -ErrorAction 'silentlycontinue' $AfterScriptInfo.AfterRemoveScript -Force
}
Remove-Item -Path $ManGzipInfo.GzipFile -Force -ErrorAction SilentlyContinue
}
# Magic to get path output
$createdPackage = Get-Item (Join-Path $PWD (($Output[-1] -split ":path=>")[-1] -replace '["{}]'))
if ($Environment.IsMacOS) {
if ($PSCmdlet.ShouldProcess("Add distribution information and Fix PackageName"))
{
$createdPackage = New-MacOsDistributionPackage -FpmPackage $createdPackage -IsPreview:$IsPreview
}
}
if (Test-Path $createdPackage)
{
Write-Verbose "Created package: $createdPackage" -Verbose
return $createdPackage
}
else
{
throw "Failed to create $createdPackage"
}
}
}
Function New-LinkInfo
{
[CmdletBinding(SupportsShouldProcess=$true)]
param(
[Parameter(Mandatory)]
[string]
$LinkDestination,
[Parameter(Mandatory)]
[string]
$linkTarget
)
$linkDir = Join-Path -Path '/tmp' -ChildPath ([System.IO.Path]::GetRandomFileName())
$null = New-Item -ItemType Directory -Path $linkDir