forked from Badgerati/Pode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pode.build.ps1
1712 lines (1396 loc) · 58.2 KB
/
pode.build.ps1
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
<#
.SYNOPSIS
Build script for the Pode project, defining tasks for compilation, testing, packaging, and deployment.
.DESCRIPTION
This script uses Invoke-Build to automate the Pode project build process across different environments (Windows, macOS, Linux).
It includes tasks for setting up dependencies, compiling .NET targets, running tests, generating documentation, and packaging.
.PARAMETER Version
Specifies the project version for stamping, packaging, and documentation. Defaults to '0.0.0'.
.PARAMETER PesterVerbosity
Sets the verbosity level for Pester tests. Options: None, Normal, Detailed, Diagnostic.
.PARAMETER PowerShellVersion
Defines the target PowerShell version for installation, e.g., 'lts' or a specific version.
.PARAMETER ReleaseNoteVersion
Specifies the release version for generating release notes.
.PARAMETER UICulture
Sets the culture for running tests, defaulting to 'en-US'.
.PARAMETER TargetFrameworks
Specifies the target .NET frameworks for building the project, e.g., netstandard2.0, net8.0.
.PARAMETER SdkVersion
Sets the SDK version used for building .NET projects, defaulting to net8.0.
.NOTES
This build script requires Invoke-Build. Below is a list of all available tasks:
- Default: Lists all available tasks.
- StampVersion: Stamps the specified version onto the module.
- PrintChecksum: Generates and displays a checksum of the ZIP archive.
- ChocoDeps: Installs Chocolatey (for Windows).
- BuildDeps: Installs dependencies required for building/compiling.
- TestDeps: Installs dependencies required for testing.
- DocsDeps: Installs dependencies required for documentation generation.
- IndexSamples: Indexes sample files for documentation.
- Build: Builds the .NET Listener for specified frameworks.
- DeliverableFolder: Creates a folder for deliverables.
- Compress: Compresses the module into a ZIP format for distribution.
- ChocoPack: Creates a Chocolatey package of the module (Windows only).
- DockerPack: Builds Docker images for the module.
- Pack: Packages the module, including ZIP, Chocolatey, and Docker.
- PackageFolder: Creates the `pkg` folder for module packaging.
- TestNoBuild: Runs tests without building, including Pester tests.
- Test: Runs tests after building the project.
- CheckFailedTests: Checks if any tests failed and throws an error if so.
- PushCodeCoverage: Pushes code coverage results to a coverage service.
- Docs: Serves the documentation locally for review.
- DocsHelpBuild: Builds function help documentation.
- DocsBuild: Builds the documentation for distribution.
- Clean: Cleans the build environment, removing all generated files.
- CleanDeliverable: Removes the `deliverable` folder.
- CleanPkg: Removes the `pkg` folder.
- CleanLibs: Removes the `Libs` folder under `src`.
- CleanListener: Removes the Listener folder.
- CleanDocs: Cleans up generated documentation files.
- Install-Module: Installs the Pode module locally.
- Remove-Module: Removes the Pode module from the local registry.
- SetupPowerShell: Sets up the PowerShell environment for the build.
- ReleaseNotes: Generates release notes based on merged pull requests.
.EXAMPLE
Invoke-Build -Task Default
# Displays a list of all available tasks.
Invoke-Build -Task Build -Version '1.2.3'
# Compiles the project for the specified version.
Invoke-Build -Task Test
# Runs tests on the project, including Pester tests.
Invoke-Build -Task Docs
# Builds and serves the documentation locally.
.LINK
For more information, visit https://github.com/Badgerati/Pode
#>
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingWriteHost', '')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingCmdletAliases', '')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingInvokeExpression', '')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUSeDeclaredVarsMoreThanAssignments', '')]
param(
[string]
$Version = '0.0.0',
[string]
[ValidateSet('None', 'Normal' , 'Detailed', 'Diagnostic')]
$PesterVerbosity = 'Normal',
[string]
$PowerShellVersion = 'lts',
[string]
$ReleaseNoteVersion,
[string]
$UICulture = 'en-US',
[string[]]
[ValidateSet('netstandard2.0', 'net8.0', 'net9.0', 'net10.0')]
$TargetFrameworks = @('netstandard2.0', 'net8.0', 'net9.0'),
[string]
[ValidateSet('netstandard2.0', 'net8.0', 'net9.0', 'net10.0')]
$SdkVersion = 'net9.0'
)
# Dependency Versions
$Versions = @{
Pester = '5.6.1'
MkDocs = '1.6.1'
PSCoveralls = '1.0.0'
DotNet = $SdkVersion
MkDocsTheme = '9.5.44'
PlatyPS = '0.14.2'
}
# Helper Functions
<#
.SYNOPSIS
Checks if the current environment is running on Windows.
.DESCRIPTION
This function determines if the current PowerShell session is running on Windows.
It inspects `$PSVersionTable.Platform` and `$PSVersionTable.PSEdition` to verify the OS,
returning `$true` for Windows and `$false` for other platforms.
.OUTPUTS
[bool] - Returns `$true` if the current environment is Windows, otherwise `$false`.
.EXAMPLE
if (Test-PodeBuildIsWindows) {
Write-Host "This script is running on Windows."
}
.NOTES
- Useful for cross-platform scripts to conditionally execute Windows-specific commands.
- The `$PSVersionTable.Platform` variable may be `$null` in certain cases, so `$PSEdition` is used as an additional check.
#>
function Test-PodeBuildIsWindows {
$v = $PSVersionTable
return ($v.Platform -ilike '*win*' -or ($null -eq $v.Platform -and $v.PSEdition -ieq 'desktop'))
}
<#
.SYNOPSIS
Checks if the script is running in a GitHub Actions environment.
.DESCRIPTION
This function verifies if the script is running in a GitHub Actions environment
by checking if the `GITHUB_REF` environment variable is defined and not empty.
It returns `$true` if the variable is present, indicating a GitHub Actions environment.
.OUTPUTS
[bool] - Returns `$true` if the script is running on GitHub Actions, otherwise `$false`.
.EXAMPLE
if (Test-PodeBuildIsGitHub) {
Write-Host "Running in GitHub Actions."
}
.NOTES
- This function is useful for CI/CD pipelines to identify if the script is running in GitHub Actions.
- Assumes that `GITHUB_REF` is always set in a GitHub Actions environment.
#>
function Test-PodeBuildIsGitHub {
return (![string]::IsNullOrWhiteSpace($env:GITHUB_REF))
}
<#
.SYNOPSIS
Checks if code coverage is enabled for the build.
.DESCRIPTION
This function checks if code coverage is enabled by evaluating the `PODE_RUN_CODE_COVERAGE`
environment variable. If the variable contains '1' or 'true' (case-insensitive), it returns `$true`;
otherwise, it returns `$false`.
.OUTPUTS
[bool] - Returns `$true` if code coverage is enabled, otherwise `$false`.
.EXAMPLE
if (Test-PodeBuildCanCodeCoverage) {
Write-Host "Code coverage is enabled for this build."
}
.NOTES
- Useful for conditional logic in build scripts that should only execute code coverage-related tasks if enabled.
- The `PODE_RUN_CODE_COVERAGE` variable is typically set by the CI/CD environment or the user.
#>
function Test-PodeBuildCanCodeCoverage {
return (@('1', 'true') -icontains $env:PODE_RUN_CODE_COVERAGE)
}
<#
.SYNOPSIS
Returns the name of the CI/CD service being used for the build.
.DESCRIPTION
This function returns a string representing the CI/CD service in use.
Currently, it always returns 'github-actions', indicating that the build
is running in GitHub Actions.
.OUTPUTS
[string] - The name of the CI/CD service, which is 'github-actions'.
.EXAMPLE
$service = Get-PodeBuildService
Write-Host "The build service is: $service"
# Output: The build service is: github-actions
.NOTES
- This function is useful for identifying the CI/CD service in logs or reporting.
- Future modifications could extend this function to detect other CI/CD services.
#>
function Get-PodeBuildService {
return 'github-actions'
}
<#
.SYNOPSIS
Checks if a specified command is available on the system.
.DESCRIPTION
This function checks if a given command is available in the system's PATH.
On Windows, it uses `Get-Command`, and on Unix-based systems, it uses `which`.
It returns `$true` if the command exists and `$false` if it does not.
.PARAMETER cmd
The name of the command to check for availability (e.g., 'choco', 'brew').
.OUTPUTS
[bool] - Returns `$true` if the command is found, otherwise `$false`.
.EXAMPLE
if (Test-PodeBuildCommand -Cmd 'git') {
Write-Host "Git is available."
}
.NOTES
- This function supports both Windows and Unix-based platforms.
- Requires `Test-PodeBuildIsWindows` to detect the OS type.
#>
function Test-PodeBuildCommand($cmd) {
$path = $null
if (Test-PodeBuildIsWindows) {
$path = (Get-Command $cmd -ErrorAction Ignore)
}
else {
$path = (which $cmd)
}
return (![string]::IsNullOrWhiteSpace($path))
}
<#
.SYNOPSIS
Retrieves the branch name from the GitHub Actions environment variable.
.DESCRIPTION
This function extracts the branch name from the `GITHUB_REF` environment variable,
which is commonly set in GitHub Actions workflows. It removes the 'refs/heads/' prefix
from the branch reference, leaving only the branch name.
.OUTPUTS
[string] - The name of the GitHub branch.
.EXAMPLE
$branch = Get-PodeBuildBranch
Write-Host "Current branch: $branch"
# Output example: Current branch: main
.NOTES
- Only relevant in environments where `GITHUB_REF` is defined (e.g., GitHub Actions).
- Returns an empty string if `GITHUB_REF` is not set.
#>
function Get-PodeBuildBranch {
return ($env:GITHUB_REF -ireplace 'refs\/heads\/', '')
}
<#
.SYNOPSIS
Installs a specified package using the appropriate package manager for the OS.
.DESCRIPTION
This function installs a specified package at a given version using platform-specific
package managers. For Windows, it uses Chocolatey (`choco`). On Unix-based systems,
it checks for `brew`, `apt-get`, and `yum` to handle installations. The function sets
the security protocol to TLS 1.2 to ensure secure connections during the installation.
.PARAMETER name
The name of the package to install (e.g., 'git').
.PARAMETER version
The version of the package to install, required only for Chocolatey on Windows.
.OUTPUTS
None.
.EXAMPLE
Invoke-PodeBuildInstall -Name 'git' -Version '2.30.0'
# Installs version 2.30.0 of Git on Windows if Chocolatey is available.
.NOTES
- Requires administrator or sudo privileges on Unix-based systems.
- This function supports package installation on both Windows and Unix-based systems.
- If `choco` is available, it will use `choco` for Windows, and `brew`, `apt-get`, or `yum` for Unix-based systems.
#>
function Invoke-PodeBuildInstall($name, $version) {
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
if (Test-PodeBuildIsWindows) {
if (Test-PodeBuildCommand 'choco') {
choco install $name --version $version -y --no-progress
}
}
else {
if (Test-PodeBuildCommand 'brew') {
brew install $name
}
elseif (Test-PodeBuildCommand 'apt-get') {
sudo apt-get install $name -y
}
elseif (Test-PodeBuildCommand 'yum') {
sudo yum install $name -y
}
}
}
<#
.SYNOPSIS
Installs a specified PowerShell module if it is not already installed at the required version.
.DESCRIPTION
This function checks if the specified PowerShell module is available in the current session
at the specified version. If not, it installs the module using the PowerShell Gallery, setting
the security protocol to TLS 1.2. The module is installed in the current user's scope.
.PARAMETER name
The name of the PowerShell module to check and install.
.OUTPUTS
None.
.EXAMPLE
Install-PodeBuildModule -Name 'Pester'
# Installs the 'Pester' module if the specified version is not already installed.
.NOTES
- Uses `$Versions` hashtable to look up the required version for the module.
- Requires internet access to download modules from the PowerShell Gallery.
- The `-SkipPublisherCheck` parameter bypasses publisher verification; use with caution.
#>
function Install-PodeBuildModule($name) {
if ($null -ne ((Get-Module -ListAvailable $name) | Where-Object { $_.Version -ieq $Versions[$name] })) {
return
}
Write-Host "Installing $($name) v$($Versions[$name])"
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Install-Module -Name "$($name)" -Scope CurrentUser -RequiredVersion "$($Versions[$name])" -Force -SkipPublisherCheck
}
<#
.SYNOPSIS
Converts a .NET target framework identifier to a numeric version.
.DESCRIPTION
This function maps common .NET target framework identifiers (e.g., 'netstandard2.0', 'net9.0') to their
numeric equivalents. It is used to ensure compatibility by returning the framework version number as an integer.
.PARAMETER TargetFrameworks
The target framework identifier (e.g., 'netstandard2.0', 'net9.0').
.OUTPUTS
[int] - The numeric version of the target framework. Defaults to 2 if an unrecognized framework is provided.
.EXAMPLE
$version = Get-PodeBuildTargetFramework -TargetFrameworks 'net9.0'
Write-Host "Target framework version: $version"
# Output: Target framework version: 6
.NOTES
- Returns 2 (netstandard2.0) by default if the input framework is not recognized.
- This function is useful in build scripts that require target framework versioning.
#>
function Get-PodeBuildTargetFramework {
param(
[string]
$TargetFrameworks
)
switch ($TargetFrameworks) {
'netstandard2.0' { return 2 }
'net8.0' { return 8 }
'net9.0' { return 9 }
'net10.0' { return 10 }
default {
Write-Warning "$TargetFrameworks is not a valid Framework. Rollback to netstandard2.0"
return 2
}
}
}
<#
.SYNOPSIS
Converts a .NET target framework version number to a framework identifier.
.DESCRIPTION
This function maps a numeric version to a .NET target framework identifier (e.g., '2' to 'netstandard2.0').
If the version number is not recognized, it defaults to 'netstandard2.0'.
.PARAMETER Version
The numeric version of the .NET target framework (e.g., 2, 6, 8).
.OUTPUTS
[string] - The target framework identifier (e.g., 'netstandard2.0').
.EXAMPLE
$frameworkName = Get-PodeBuildTargetFrameworkName -Version 9
Write-Host "Target framework name: $frameworkName"
# Output: Target framework name: net9.0
.NOTES
- Returns 'netstandard2.0' by default if an unrecognized version is provided.
- Useful for converting numeric framework versions to identifier strings in build processes.
#>
function Get-PodeBuildTargetFrameworkName {
param(
$Version
)
switch ( $Version) {
'2' { return 'netstandard2.0' }
'8' { return 'net8.0' }
'9' { return 'net9.0' }
'10' { return 'net10.0' }
default {
Write-Warning "$Version is not a valid Framework. Rollback to netstandard2.0"
return 'netstandard2.0'
}
}
}
function Invoke-PodeBuildDotnetBuild {
param (
[string]$target
)
# Retrieve the installed SDK versions
$sdkVersions = dotnet --list-sdks | ForEach-Object { $_.Split('[')[0].Trim() }
if ([string]::IsNullOrEmpty($AvailableSdkVersion)) {
$majorVersions = $sdkVersions | ForEach-Object { ([version]$_).Major } | Sort-Object -Descending | Select-Object -Unique
}
else {
$majorVersions = $sdkVersions.Where( { ([version]$_).Major -ge (Get-PodeBuildTargetFramework -TargetFrameworks $AvailableSdkVersion) } ) | Sort-Object -Descending | Select-Object -Unique
}
# Map target frameworks to minimum SDK versions
if ($null -eq $majorVersions) {
Write-Error "The requested '$AvailableSdkVersion' framework is not available."
return
}
$requiredSdkVersion = Get-PodeBuildTargetFramework -TargetFrameworks $target
# Determine if the target framework is compatible
$isCompatible = $majorVersions -ge $requiredSdkVersion
if ($isCompatible) {
Write-Output "SDK for target framework '$target' is compatible with the '$AvailableSdkVersion' framework."
}
else {
Write-Warning "SDK for target framework '$target' is not compatible with the '$AvailableSdkVersion' framework. Skipping build."
return
}
# Optionally set assembly version
if ($Version) {
Write-Output "Assembly Version: $Version"
$AssemblyVersion = "-p:Version=$Version"
}
else {
$AssemblyVersion = ''
}
# Use dotnet publish for .NET Core and .NET 5+
dotnet publish --configuration Release --self-contained --framework $target $AssemblyVersion --output ../Libs/$target
if (!$?) {
throw "Build failed for target framework '$target'."
}
}
<#
.SYNOPSIS
Retrieves the end-of-life (EOL) and supported versions of PowerShell.
.DESCRIPTION
This function queries an online API to retrieve the EOL and supported versions of PowerShell.
It uses the `Invoke-RestMethod` cmdlet to access data from endoflife.date and returns an object
with comma-separated lists of supported and EOL PowerShell versions based on the current date.
.OUTPUTS
[hashtable] - A hashtable containing:
- `eol`: Comma-separated string of EOL PowerShell versions.
- `supported`: Comma-separated string of supported PowerShell versions.
.EXAMPLE
$pwshEOLInfo = Get-PodeBuildPwshEOL
Write-Host "Supported PowerShell versions: $($pwshEOLInfo.supported)"
Write-Host "EOL PowerShell versions: $($pwshEOLInfo.eol)"
.NOTES
- Requires internet access to query the endoflife.date API.
- If the request fails, the function returns an empty string for both `eol` and `supported`.
- API URL: https://endoflife.date/api/powershell.json
#>
function Get-PodeBuildPwshEOL {
$uri = 'https://endoflife.date/api/powershell.json'
try {
$eol = Invoke-RestMethod -Uri $uri -Headers @{ Accept = 'application/json' }
return @{
eol = ($eol | Where-Object { [datetime]$_.eol -lt [datetime]::Now }).cycle -join ','
supported = ($eol | Where-Object { [datetime]$_.eol -ge [datetime]::Now }).cycle -join ','
}
}
catch {
Write-Warning "Invoke-RestMethod to $uri failed: $($_.ErrorDetails.Message)"
return @{
eol = ''
supported = ''
}
}
}
<#
.SYNOPSIS
Checks if the current OS is Windows.
.DESCRIPTION
This function detects whether the current operating system is Windows by checking
the `$IsWindows` automatic variable, the presence of the `$env:ProgramFiles` variable,
and the PowerShell Edition in `$PSVersionTable`. This function returns `$true` if
any of these indicate Windows.
.OUTPUTS
[bool] - Returns `$true` if the OS is Windows, otherwise `$false`.
.EXAMPLE
if (Test-PodeBuildOSWindows) {
Write-Host "Running on Windows"
}
.NOTES
- Useful for distinguishing between Windows and Unix-based systems for conditional logic.
- May return `$true` in environments where Windows-related environment variables are present.
#>
function Test-PodeBuildOSWindows {
return ($IsWindows -or
![string]::IsNullOrEmpty($env:ProgramFiles) -or
(($PSVersionTable.Keys -contains 'PSEdition') -and ($PSVersionTable.PSEdition -eq 'Desktop')))
}
<#
.SYNOPSIS
Retrieves the current OS name in a PowerShell-compatible format.
.DESCRIPTION
This function identifies the current operating system and returns a standardized string
representing the OS name ('win' for Windows, 'linux' for Linux, and 'osx' for macOS).
It relies on the `Test-PodeBuildOSWindows` function for Windows detection and `$IsLinux`
and `$IsMacOS` for Linux and macOS, respectively.
.OUTPUTS
[string] - A string representing the OS name:
- 'win' for Windows
- 'linux' for Linux
- 'osx' for macOS
.EXAMPLE
$osName = Get-PodeBuildOSPwshName
Write-Host "Operating system name: $osName"
.NOTES
- This function enables cross-platform compatibility by standardizing OS name detection.
- For accurate results, ensure `$IsLinux` and `$IsMacOS` variables are defined for Unix-like systems.
#>
function Get-PodeBuildOSPwshName {
if (Test-PodeBuildOSWindows) {
return 'win'
}
if ($IsLinux) {
return 'linux'
}
if ($IsMacOS) {
return 'osx'
}
}
<#
.SYNOPSIS
Determines the OS architecture for the current system.
.DESCRIPTION
This function detects the operating system's architecture and converts it into a format
compatible with PowerShell installation requirements. It handles both Windows and Unix-based
systems and maps various architecture identifiers to PowerShell-supported names (e.g., 'x64', 'arm64').
.OUTPUTS
[string] - The architecture string, such as 'x64', 'x86', 'arm64', or 'arm32'.
.EXAMPLE
$arch = Get-PodeBuildOSPwshArchitecture
Write-Host "Current architecture: $arch"
.NOTES
- For Windows, the architecture is derived from the `PROCESSOR_ARCHITECTURE` environment variable.
- For Unix-based systems, the architecture is determined using the `uname -m` command.
- If the architecture is not supported, the function throws an exception.
#>
function Get-PodeBuildOSPwshArchitecture {
# Initialize architecture variable
$arch = [string]::Empty
# Detect architecture on Windows
if (Test-PodeBuildOSWindows) {
$arch = $env:PROCESSOR_ARCHITECTURE
}
# Detect architecture on Unix-based systems (Linux/macOS)
if ($IsLinux -or $IsMacOS) {
$arch = uname -m
}
# Output detected architecture for debugging
Write-Host "OS Architecture: $($arch)"
# Convert detected architecture to a PowerShell-compatible format
switch ($arch.ToLowerInvariant()) {
'amd64' { return 'x64' } # 64-bit architecture (AMD64)
'x86' { return 'x86' } # 32-bit architecture
'x86_64' { return 'x64' } # 64-bit architecture (x86_64)
'armv7*' { return 'arm32' } # 32-bit ARM architecture
'aarch64*' { return 'arm64' } # 64-bit ARM architecture
'arm64' { return 'arm64' } # Explicit ARM64
'arm64*' { return 'arm64' } # Pattern matching for ARM64
'armv8*' { return 'arm64' } # ARM v8 series
default { throw "Unsupported architecture: $($arch)" } # Throw exception for unsupported architectures
}
}
<#
.SYNOPSIS
Converts a PowerShell tag to a version number.
.DESCRIPTION
This function retrieves PowerShell build information for a specified tag by querying
an online API. It then extracts and returns the release version associated with the tag.
.PARAMETER PowerShellVersion
The PowerShell version tag to retrieve build information for (e.g., 'lts', 'stable', or a specific version).
.OUTPUTS
[string] - The extracted version number corresponding to the provided tag.
.EXAMPLE
$version = Convert-PodeBuildOSPwshTagToVersion
Write-Host "Resolved PowerShell version: $version"
.NOTES
This function depends on internet connectivity to query the build information API.
#>
function Convert-PodeBuildOSPwshTagToVersion {
# Query PowerShell build info API with the specified tag
$result = Invoke-RestMethod -Uri "https://aka.ms/pwsh-buildinfo-$($PowerShellVersion)"
# Extract and return the release tag without the leading 'v'
return $result.ReleaseTag -ireplace '^v'
}
<#
.SYNOPSIS
Installs PowerShell on a Windows system.
.DESCRIPTION
This function installs PowerShell by copying files from a specified target directory
to the standard installation folder on a Windows system. It first removes any existing
installation in the Target directory.
.PARAMETER Target
The directory containing the PowerShell installation files.
.EXAMPLE
Install-PodeBuildPwshWindows -Target 'C:\Temp\PowerShell'
# Installs PowerShell from the 'C:\Temp\PowerShell' directory.
.NOTES
This function requires administrative privileges to modify the Program Files directory.
#>
function Install-PodeBuildPwshWindows {
param (
[string]
$Target
)
# Define the installation folder path
$installFolder = "$($env:ProgramFiles)\PowerShell\7"
# Remove the existing installation, if any
if (Test-Path $installFolder) {
Remove-Item $installFolder -Recurse -Force -ErrorAction Stop
}
# Copy the new PowerShell files to the installation folder
Copy-Item -Path "$($Target)\" -Destination "$($installFolder)\" -Recurse -ErrorAction Stop
}
<#
.SYNOPSIS
Installs PowerShell on a Unix-based system.
.DESCRIPTION
This function installs PowerShell on Unix-based systems by copying files from a specified Target directory,
setting appropriate permissions, and creating a symbolic link to the PowerShell binary.
.PARAMETER Target
The directory containing the PowerShell installation files.
.EXAMPLE
Install-PodeBuildPwshUnix -Target '/tmp/powershell'
# Installs PowerShell from the '/tmp/powershell' directory.
.NOTES
- This function requires administrative privileges to create symbolic links in system directories.
- The `sudo` command is used if the script is not run as root.
#>
function Install-PodeBuildPwshUnix {
param (
[string]
$Target
)
# Define the full path to the PowerShell binary
$targetFullPath = Join-Path -Path $Target -ChildPath 'pwsh'
# Set executable permissions on the PowerShell binary
$null = chmod 755 $targetFullPath
# Determine the symbolic link location based on the operating system
$symlink = $null
if ($IsMacOS) {
$symlink = '/usr/local/bin/pwsh'
}
else {
$symlink = '/usr/bin/pwsh'
}
# Check if the script is run as root
$uid = id -u
if ($uid -ne '0') {
$sudo = 'sudo'
}
else {
$sudo = ''
}
# Create a symbolic link to the PowerShell binary
& $sudo ln -fs $targetFullPath $symlink
}
<#
.SYNOPSIS
Retrieves the currently installed PowerShell version.
.DESCRIPTION
This function runs the `pwsh -v` command and parses the output to return only the version number.
This is useful for verifying the PowerShell version in the build environment.
.OUTPUTS
[string] - The current PowerShell version.
.EXAMPLE
$version = Get-PodeBuildCurrentPwshVersion
Write-Host "Current PowerShell version: $version"
.NOTES
This function assumes that `pwsh` is available in the system PATH.
#>
function Get-PodeBuildCurrentPwshVersion {
# Run pwsh command, split by spaces, and return the version component
return ("$(pwsh -v)" -split ' ')[1].Trim()
}
<#
.SYNOPSIS
Builds a Docker image and tags it for the Pode project.
.DESCRIPTION
This function uses the Docker CLI to build an image for Pode, then tags it for GitHub Packages.
The function takes a tag and a Dockerfile path as parameters to build and tag the Docker image.
.PARAMETER Tag
The Docker image tag, typically a version number or label (e.g., 'latest').
.PARAMETER File
The path to the Dockerfile to use for building the image.
.EXAMPLE
Invoke-PodeBuildDockerBuild -Tag '1.0.0' -File './Dockerfile'
# Builds a Docker image using './Dockerfile' and tags it as 'badgerati/pode:1.0.0'.
.NOTES
Requires Docker to be installed and available in the system PATH.
#>
function Invoke-PodeBuildDockerBuild {
param (
[string]
$Tag,
[string]
$File
)
# Build the Docker image with the specified tag and Dockerfile
docker build -t badgerati/pode:$Tag -f $File .
if (!$?) {
throw "docker build failed for $($Tag)"
}
# Tag the image for GitHub Packages
docker tag badgerati/pode:$Tag docker.pkg.github.com/badgerati/pode/pode:$Tag
if (!$?) {
throw "docker tag failed for $($Tag)"
}
}
<#
.SYNOPSIS
Splits the PSModulePath environment variable into an array of paths.
.DESCRIPTION
This function checks the operating system and splits the PSModulePath variable based on the appropriate separator:
';' for Windows and ':' for Unix-based systems.
.OUTPUTS
[string[]] - An array of paths from the PSModulePath variable.
.EXAMPLE
$paths = Split-PodeBuildPwshPath
foreach ($path in $paths) {
Write-Host $path
}
.NOTES
This function enables cross-platform support by handling path separators for Windows and Unix-like systems.
#>
function Split-PodeBuildPwshPath {
# Check if OS is Windows, then split PSModulePath by ';', otherwise use ':'
if (Test-PodeBuildOSWindows) {
return $env:PSModulePath -split ';'
}
else {
return $env:PSModulePath -split ':'
}
}
# Check if the script is running under Invoke-Build
if (($null -eq $PSCmdlet.MyInvocation) -or ($PSCmdlet.MyInvocation.BoundParameters.ContainsKey('BuildRoot') -and ($null -eq $BuildRoot))) {
Write-Host 'This script is intended to be run with Invoke-Build. Please use Invoke-Build to execute the tasks defined in this script.' -ForegroundColor Yellow
return
}
Add-BuildTask Default {
Write-Host 'Tasks in the Build Script:' -ForegroundColor DarkMagenta
Write-Host
Write-Host 'Primary Tasks:' -ForegroundColor Green
Write-Host '- Default: Lists all available tasks.'
Write-Host '- Build: Builds the .NET Listener for specified frameworks.'
Write-Host '- Pack: Packages the module, including ZIP, Chocolatey, and Docker.'
Write-Host '- Test: Runs tests after building the project.'
Write-Host '- Clean: Cleans the build environment, removing all generated files.'
Write-Host '- Install-Module: Installs the Pode module locally.'
Write-Host '- Remove-Module: Removes the Pode module from the local registry.'
Write-Host '- DocsBuild: Builds the documentation for distribution.'
Write-Host '- TestNoBuild: Runs tests without building, including Pester tests.'
Write-Host
Write-Host 'Other Tasks:' -ForegroundColor Green
Write-Host '- StampVersion: Stamps the specified version onto the module.'
Write-Host '- PrintChecksum: Generates and displays a checksum of the ZIP archive.'
Write-Host '- ChocoDeps: Installs Chocolatey (for Windows).'
Write-Host '- BuildDeps: Installs dependencies required for building/compiling.'
Write-Host '- TestDeps: Installs dependencies required for testing.'
Write-Host '- DocsDeps: Installs dependencies required for documentation generation.'
Write-Host '- IndexSamples: Indexes sample files for documentation.'
Write-Host '- DeliverableFolder: Creates a folder for deliverables.'
Write-Host '- Compress: Compresses the module into a ZIP format for distribution.'
Write-Host '- ChocoPack: Creates a Chocolatey package of the module (Windows only).'
Write-Host '- DockerPack: Builds Docker images for the module.'
Write-Host "- PackageFolder: Creates the `pkg` folder for module packaging."
Write-Host '- CheckFailedTests: Checks if any tests failed and throws an error if so.'
Write-Host '- PushCodeCoverage: Pushes code coverage results to a coverage service.'
Write-Host '- Docs: Serves the documentation locally for review.'
Write-Host '- DocsHelpBuild: Builds function help documentation.'
Write-Host "- CleanDeliverable: Removes the `deliverable` folder."
Write-Host "- CleanPkg: Removes the `pkg` folder."
Write-Host "- CleanLibs: Removes the `Libs` folder under `src`."
Write-Host '- CleanListener: Removes the Listener folder.'
Write-Host '- CleanDocs: Cleans up generated documentation files.'
Write-Host '- SetupPowerShell: Sets up the PowerShell environment for the build.'
Write-Host '- ReleaseNotes: Generates release notes based on merged pull requests.'
}
<#
# Helper Tasks
#>
# Synopsis: Stamps the version onto the Module
Add-BuildTask StampVersion {
$pwshVersions = Get-PodeBuildPwshEOL
(Get-Content ./pkg/Pode.psd1) | ForEach-Object { $_ -replace '\$version\$', $Version -replace '\$versionsUntested\$', $pwshVersions.eol -replace '\$versionsSupported\$', $pwshVersions.supported -replace '\$buildyear\$', ((get-date).Year) } | Set-Content ./pkg/Pode.psd1
(Get-Content ./pkg/Pode.Internal.psd1) | ForEach-Object { $_ -replace '\$version\$', $Version } | Set-Content ./pkg/Pode.Internal.psd1
(Get-Content ./packers/choco/pode_template.nuspec) | ForEach-Object { $_ -replace '\$version\$', $Version } | Set-Content ./packers/choco/pode.nuspec
(Get-Content ./packers/choco/tools/ChocolateyInstall_template.ps1) | ForEach-Object { $_ -replace '\$version\$', $Version } | Set-Content ./packers/choco/tools/ChocolateyInstall.ps1
}
# Synopsis: Generating a Checksum of the Zip
Add-BuildTask PrintChecksum {
$Script:Checksum = (Get-FileHash "./deliverable/$Version-Binaries.zip" -Algorithm SHA256).Hash
Write-Host "Checksum: $($Checksum)"
}
<#
# Dependencies
#>
# Synopsis: Installs Chocolatey
Add-BuildTask ChocoDeps -If (Test-PodeBuildIsWindows) {
if (!(Test-PodeBuildCommand 'choco')) {
Set-ExecutionPolicy Bypass -Scope Process -Force
Invoke-Expression ([System.Net.WebClient]::new().DownloadString('https://chocolatey.org/install.ps1'))
}
}
# Synopsis: Install dependencies for compiling/building
Add-BuildTask BuildDeps {
# install dotnet
if (Test-PodeBuildIsWindows) {
$dotnet = 'dotnet'
}
elseif (Test-PodeBuildCommand 'brew') {
$dotnet = 'dotnet-sdk'
}
else {
$dotnet = "dotnet-sdk-$SdkVersion"
}
try {
$sdkVersions = dotnet --list-sdks | ForEach-Object { $_.Split('[')[0].Trim() }
}
catch {
Invoke-PodeBuildInstall $dotnet $SdkVersion
$sdkVersions = dotnet --list-sdks | ForEach-Object { $_.Split('[')[0].Trim() }
}
$majorVersions = ($sdkVersions | ForEach-Object { ([version]$_).Major } | Sort-Object -Descending | Select-Object -Unique)[0]
$script:AvailableSdkVersion = Get-PodeBuildTargetFrameworkName -Version $majorVersions
if ($majorVersions -lt (Get-PodeBuildTargetFramework -TargetFrameworks $SdkVersion)) {
Invoke-PodeBuildInstall $dotnet $SdkVersion
$sdkVersions = dotnet --list-sdks | ForEach-Object { $_.Split('[')[0].Trim() }
$majorVersions = ($sdkVersions | ForEach-Object { ([version]$_).Major } | Sort-Object -Descending | Select-Object -Unique)[0]
$script:AvailableSdkVersion = Get-PodeBuildTargetFrameworkName -Version $majorVersions
if ($majorVersions -lt (Get-PodeBuildTargetFramework -TargetFrameworks $SdkVersion)) {
Write-Error "The requested framework '$SdkVersion' is not available."
return
}
}
elseif ($majorVersions -gt (Get-PodeBuildTargetFramework -TargetFrameworks $SdkVersion)) {
Write-Warning "The requested SDK version '$SdkVersion' is superseded by the installed '$($script:AvailableSdkVersion)' framework."