-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathResolve-PSModuleVersion.Helpers.psm1
More file actions
885 lines (751 loc) · 32.2 KB
/
Copy pathResolve-PSModuleVersion.Helpers.psm1
File metadata and controls
885 lines (751 loc) · 32.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
function Split-CommaSeparatedList {
<#
.SYNOPSIS
Splits a comma-separated string into a trimmed, non-empty array.
.EXAMPLE
Split-CommaSeparatedList -Value 'Major, Minor, Patch'
Returns @('Major', 'Minor', 'Patch').
#>
[CmdletBinding()]
[OutputType([string[]])]
param(
# The comma-separated string to split.
[Parameter()]
[string] $Value
)
($Value -split ',') | ForEach-Object { $_.Trim() } | Where-Object { $_ }
}
function Resolve-DefaultBump {
<#
.SYNOPSIS
Validates and returns the configured default version bump.
.OUTPUTS
System.String
.EXAMPLE
Resolve-DefaultBump -DefaultBump 'patch'
#>
[CmdletBinding()]
[OutputType([string])]
param(
# The default bump name.
[Parameter(Mandatory)]
[AllowEmptyString()]
[string] $DefaultBump
)
$validDefaultBumps = @('patch', 'minor', 'major')
if ($validDefaultBumps -cnotcontains $DefaultBump) {
throw (
"Invalid Publish.Module.DefaultBump: [$DefaultBump]. " +
"Valid values are: $($validDefaultBumps -join ', ')."
)
}
$DefaultBump
}
function Read-ActionInput {
<#
.SYNOPSIS
Reads and validates action inputs from environment variables.
.DESCRIPTION
Reads the module name and settings JSON from GitHub Actions environment variables.
Falls back to the repository name when the module name input is not provided.
.OUTPUTS
PSCustomObject with Name and SettingsJson properties.
.EXAMPLE
$actionInput = Read-ActionInput
#>
[CmdletBinding()]
[OutputType([PSCustomObject])]
param()
LogGroup 'Load inputs' {
$env:GITHUB_REPOSITORY_NAME = $env:GITHUB_REPOSITORY -replace '.+/'
$name = if ([string]::IsNullOrEmpty($env:PSMODULE_RESOLVE_PSMODULEVERSION_INPUT_Name)) {
$env:GITHUB_REPOSITORY_NAME
} else {
$env:PSMODULE_RESOLVE_PSMODULEVERSION_INPUT_Name
}
Write-Host "Module name: [$name]"
$settingsJson = $env:PSMODULE_RESOLVE_PSMODULEVERSION_INPUT_Settings
if ([string]::IsNullOrWhiteSpace($settingsJson)) {
throw 'Settings input is required.'
}
[PSCustomObject]@{
Name = $name
SettingsJson = $settingsJson
}
}
}
function Get-PublishConfiguration {
<#
.SYNOPSIS
Parses the settings JSON into a publish configuration object.
.DESCRIPTION
Extracts publish module settings including the default bump, version prefix,
release type, and label classification arrays.
.OUTPUTS
PSCustomObject with publish configuration properties.
.EXAMPLE
$config = Get-PublishConfiguration -SettingsJson $actionInput.SettingsJson
#>
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '',
Justification = 'Parameter is used inside LogGroup script block.')]
[CmdletBinding()]
[OutputType([PSCustomObject])]
param(
# The JSON string containing the module settings.
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string] $SettingsJson
)
LogGroup 'Resolve configuration' {
$settings = $SettingsJson | ConvertFrom-Json
$publishModule = $settings.Publish.Module
$defaultBump = Resolve-DefaultBump -DefaultBump ([string]$publishModule.DefaultBump)
$config = [PSCustomObject]@{
DefaultBump = $defaultBump
IncrementalPrerelease = [bool]$publishModule.IncrementalPrerelease
DatePrereleaseFormat = [string]$publishModule.DatePrereleaseFormat
VersionPrefix = [string]$publishModule.VersionPrefix
ReleaseType = [string]$publishModule.ReleaseType
IgnoreLabels = Split-CommaSeparatedList ([string]$publishModule.IgnoreLabels)
MajorLabels = Split-CommaSeparatedList ([string]$publishModule.MajorLabels)
MinorLabels = Split-CommaSeparatedList ([string]$publishModule.MinorLabels)
PatchLabels = Split-CommaSeparatedList ([string]$publishModule.PatchLabels)
}
Write-Host '-------------------------------------------------'
Write-Host ([PSCustomObject]@{
DefaultBump = $config.DefaultBump
IncrementalPrerelease = $config.IncrementalPrerelease
DatePrereleaseFormat = $config.DatePrereleaseFormat
VersionPrefix = $config.VersionPrefix
ReleaseType = $config.ReleaseType
IgnoreLabels = $config.IgnoreLabels -join ', '
MajorLabels = $config.MajorLabels -join ', '
MinorLabels = $config.MinorLabels -join ', '
PatchLabels = $config.PatchLabels -join ', '
} | Format-List | Out-String)
Write-Host '-------------------------------------------------'
$config
}
}
function Get-GitHubPullRequest {
<#
.SYNOPSIS
Reads normalized pull-request context from settings, with event-payload fallback.
.DESCRIPTION
The settings action resolves the pull request associated with a default-branch push
before this action runs. When no pull request exists, a direct push or manual
dispatch on the default branch still receives release context so it resolves the
configured default bump.
.OUTPUTS
PSCustomObject with pull-request metadata, or a default-branch direct-release
context with no pull-request number.
.EXAMPLE
$pullRequest = Get-GitHubPullRequest -SettingsJson $actionInput.SettingsJson
#>
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', 'SettingsJson',
Justification = 'Parameter is used inside a LogGroup script block.')]
[CmdletBinding()]
[OutputType([PSCustomObject])]
param(
# The complete settings object, including normalized workflow context.
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string] $SettingsJson
)
LogGroup 'Event information' {
$settings = $SettingsJson | ConvertFrom-Json
$context = $settings.Context
if ($context) {
$contextPullRequest = $context.PullRequest
if ($contextPullRequest) {
Write-Host "Using normalized pull request context for #$($contextPullRequest.Number)."
return [PSCustomObject]@{
Number = $contextPullRequest.Number
HeadRef = $contextPullRequest.HeadRef
Labels = @($contextPullRequest.Labels)
}
}
if ($context.IsPushToDefaultBranch -or $context.IsManualDispatchToDefaultBranch) {
Write-Host 'Using direct default-branch release context with the configured default bump.'
return [PSCustomObject]@{
Number = $null
HeadRef = $context.DefaultBranch
Labels = @()
IsDirectRelease = $true
}
}
}
$eventJsonInput = $env:PSMODULE_RESOLVE_PSMODULEVERSION_INPUT_EventJson
$githubEvent = if (-not [string]::IsNullOrWhiteSpace($eventJsonInput)) {
$eventJsonInput | ConvertFrom-Json
} else {
Get-Content $env:GITHUB_EVENT_PATH | ConvertFrom-Json
}
$pr = $githubEvent.pull_request
if (-not $pr) {
Write-Host 'GitHub event does not contain pull_request data and no release context was normalized.'
return $null
}
$labels = @()
$labels += $pr.labels.name
Write-Host '-------------------------------------------------'
Write-Host ([PSCustomObject]@{
PRHeadRef = $pr.head.ref
Labels = $labels -join ', '
} | Format-List | Out-String)
Write-Host '-------------------------------------------------'
[PSCustomObject]@{
HeadRef = $pr.head.ref
Labels = $labels
}
}
}
function Resolve-ReleaseDecision {
<#
.SYNOPSIS
Determines whether to publish a release and what kind of version bump to apply.
.DESCRIPTION
Evaluates the PR labels against the configured label categories and release type
to produce a complete release decision.
.OUTPUTS
PSCustomObject with ShouldPublish, CreateRelease, CreatePrerelease, MajorRelease,
MinorRelease, PatchRelease, HasVersionBump, and PrereleaseName properties.
.EXAMPLE
$decision = Resolve-ReleaseDecision -Configuration $config -PullRequest $pullRequest
#>
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '',
Justification = 'Parameter is used inside LogGroup script block.')]
[CmdletBinding()]
[OutputType([PSCustomObject])]
param(
# The publish configuration object.
[Parameter(Mandatory)]
[PSCustomObject] $Configuration,
# The pull request data object.
[Parameter(Mandatory)]
[PSCustomObject] $PullRequest
)
LogGroup 'Determine release configuration' {
$prereleaseName = $PullRequest.HeadRef -replace '[^a-zA-Z0-9]'
$labels = $PullRequest.Labels
$releaseType = $Configuration.ReleaseType
$defaultBump = Resolve-DefaultBump -DefaultBump ([string]$Configuration.DefaultBump)
$validReleaseTypes = @('Release', 'Prerelease', 'None')
if ([string]::IsNullOrWhiteSpace($releaseType)) {
throw "Settings.Publish.Module.ReleaseType is required. Valid values are: $($validReleaseTypes -join ', ')"
}
if ($releaseType -notin $validReleaseTypes) {
throw "Invalid ReleaseType: [$releaseType]. Valid values are: $($validReleaseTypes -join ', ')"
}
$createRelease = $releaseType -eq 'Release'
$createPrerelease = $releaseType -eq 'Prerelease'
$shouldPublish = $createRelease -or $createPrerelease
$isCleanupOnly = $releaseType -eq 'None'
if ($isCleanupOnly) {
return [PSCustomObject]@{
ShouldPublish = $false
CreateRelease = $false
CreatePrerelease = $false
MajorRelease = $false
MinorRelease = $false
PatchRelease = $false
HasVersionBump = $false
PrereleaseName = $prereleaseName
}
}
$ignoreRelease = ($labels | Where-Object { $Configuration.IgnoreLabels -contains $_ }).Count -gt 0
if ($ignoreRelease -and $shouldPublish) {
Write-Host 'Ignoring release creation due to ignore label.'
$shouldPublish = $false
}
$majorLabels = @($labels | Where-Object { $Configuration.MajorLabels -contains $_ })
$minorLabels = @($labels | Where-Object { $Configuration.MinorLabels -contains $_ })
$patchLabels = @($labels | Where-Object { $Configuration.PatchLabels -contains $_ })
$versionLabels = @($majorLabels + $minorLabels + $patchLabels)
if ($versionLabels.Count -gt 1) {
throw "Conflicting version labels: [$($versionLabels -join ', ')]. Apply exactly one version label."
}
if ($ignoreRelease -and $versionLabels.Count -gt 0) {
throw "The ignore label cannot be combined with a version label: [$($versionLabels -join ', ')]."
}
$majorRelease = $majorLabels.Count -eq 1
$minorRelease = $minorLabels.Count -eq 1
$patchRelease = $patchLabels.Count -eq 1
if (-not $majorRelease -and -not $minorRelease -and -not $patchRelease) {
switch -CaseSensitive ($defaultBump) {
'major' { $majorRelease = $true }
'minor' { $minorRelease = $true }
'patch' { $patchRelease = $true }
}
}
$hasVersionBump = $majorRelease -or $minorRelease -or $patchRelease
if ($ignoreRelease) {
$createRelease = $false
$createPrerelease = $false
$shouldPublish = $false
}
if (-not $shouldPublish) {
$createPrerelease = $true
}
Write-Host '-------------------------------------------------'
Write-Host ([PSCustomObject]@{
ReleaseType = $releaseType
ShouldPublish = $shouldPublish
CreateRelease = $createRelease
CreatePrerelease = $createPrerelease
DefaultBump = $defaultBump
Major = $majorRelease
Minor = $minorRelease
Patch = $patchRelease
} | Format-List | Out-String)
Write-Host '-------------------------------------------------'
[PSCustomObject]@{
ShouldPublish = $shouldPublish
CreateRelease = $createRelease
CreatePrerelease = $createPrerelease
MajorRelease = $majorRelease
MinorRelease = $minorRelease
PatchRelease = $patchRelease
HasVersionBump = $hasVersionBump
PrereleaseName = $prereleaseName
}
}
}
function ConvertFrom-GitHubReleaseJson {
<#
.SYNOPSIS
Converts the JSON output of 'gh release list' into a flat array of release objects.
.DESCRIPTION
Normalizes the release listing so a repository with no releases, or a command that
produced no output at all, yields an empty array instead of $null.
.OUTPUTS
Array of release objects. Empty when there are no releases.
.EXAMPLE
$releases = ConvertFrom-GitHubReleaseJson -Json '[{"tagName":"v1.0.0"}]'
#>
[CmdletBinding()]
[OutputType([object[]], [array])]
param(
# The raw JSON returned by 'gh release list'. Empty or null when the command produced no output.
[Parameter()]
[AllowNull()]
[AllowEmptyString()]
[string] $Json
)
if ([string]::IsNullOrWhiteSpace($Json)) {
return @()
}
@($Json | ConvertFrom-Json)
}
function Get-GitHubRelease {
<#
.SYNOPSIS
Retrieves all releases from the current GitHub repository.
.DESCRIPTION
Lists the releases of the current repository. A repository that has no releases yet
produces no output, so callers normalize the result with @() before using it.
.OUTPUTS
Array of release objects. Nothing when the repository has no releases.
.EXAMPLE
$releases = @(Get-GitHubRelease)
#>
[CmdletBinding()]
[OutputType([array])]
param()
LogGroup 'Get releases - GitHub' {
$releasesJson = gh release list --json 'createdAt,isDraft,isLatest,isPrerelease,name,publishedAt,tagName'
if ($LASTEXITCODE -ne 0) {
Write-Error 'Failed to list releases for the repo.'
exit $LASTEXITCODE
}
$releases = ConvertFrom-GitHubReleaseJson -Json $releasesJson
Write-Host '-------------------------------------------------'
Write-Host "Found [$($releases.Count)] releases."
Write-Host ($releases | Select-Object -Property name, isPrerelease, isLatest, publishedAt |
Format-Table | Out-String)
Write-Host '-------------------------------------------------'
$releases
}
}
function Get-LatestGitHubVersion {
<#
.SYNOPSIS
Extracts the latest stable version from a GitHub releases list.
.DESCRIPTION
Returns the version of the release marked as latest. A repository that has no releases
yet - or that has releases but none marked as latest - resolves to '0.0.0' so a brand-new
module can still be versioned before its first release exists.
.OUTPUTS
PSSemVer representing the latest GitHub release version.
.EXAMPLE
$ghVersion = Get-LatestGitHubVersion -Releases $releases
#>
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '',
Justification = 'Parameter is used inside LogGroup script block.')]
[CmdletBinding()]
[OutputType([object])]
param(
# The GitHub releases array to search. Empty or null when the repository has no releases.
[Parameter()]
[AllowNull()]
[AllowEmptyCollection()]
[array] $Releases = @()
)
LogGroup 'Get latest version - GitHub' {
$latestRelease = $Releases | Where-Object { $_.isLatest -eq $true }
$tagName = [string]$latestRelease.tagName
$version = if (-not [string]::IsNullOrEmpty($tagName)) {
New-PSSemVer -Version $tagName
} else {
Write-Warning "Could not find the latest GitHub release. Using '0.0.0'."
New-PSSemVer -Version '0.0.0'
}
Write-Host "GitHub version: [$($version.ToString())]"
$version
}
}
function Get-LatestPSGalleryVersion {
<#
.SYNOPSIS
Finds the latest stable version of a module in the PowerShell Gallery.
.DESCRIPTION
Queries the PowerShell Gallery for the latest published version of the module.
Retries up to five times with a ten-second delay between attempts.
.OUTPUTS
PSSemVer representing the latest PSGallery version.
.EXAMPLE
$psGalleryVersion = Get-LatestPSGalleryVersion -ModuleName 'MyModule'
#>
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '',
Justification = 'Parameter is used inside LogGroup script block.')]
[CmdletBinding()]
[OutputType([object])]
param(
# The name of the module to find in the PowerShell Gallery.
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string] $ModuleName
)
LogGroup 'Get latest version - PSGallery' {
$retryCount = 5
$retryDelaySeconds = 10
$latest = $null
for ($i = 1; $i -le $retryCount; $i++) {
try {
Write-Host "Finding module [$ModuleName] in the PowerShell Gallery."
$latest = Find-PSResource -Name $ModuleName -Repository PSGallery -Verbose:$false
Write-Host ($latest | Format-Table | Out-String)
break
} catch {
if ($i -eq $retryCount) {
Write-Warning "Failed to find the module [$ModuleName] in the PowerShell Gallery."
Write-Warning $_.Exception.Message
}
Start-Sleep -Seconds $retryDelaySeconds
}
}
$version = if ($latest.Version) {
New-PSSemVer -Version ($latest.Version).ToString()
} else {
Write-Warning "Could not find module online. Using '0.0.0'."
New-PSSemVer -Version '0.0.0'
}
Write-Host "PSGallery version: [$($version.ToString())]"
$version
}
}
function Get-LatestPublishedVersion {
<#
.SYNOPSIS
Returns the highest version between GitHub and the PowerShell Gallery.
.DESCRIPTION
Compares the two known published versions and returns the highest one. A missing
(null) version is treated as '0.0.0', so a module that has never been released to
GitHub or published to the PowerShell Gallery resolves to a '0.0.0' baseline.
.OUTPUTS
PSSemVer representing the highest known published version.
.EXAMPLE
$latestVersion = Get-LatestPublishedVersion -GitHubVersion $ghVersion -PSGalleryVersion $psGalleryVersion
#>
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '',
Justification = 'Parameter is used inside LogGroup script block.')]
[CmdletBinding()]
[OutputType([object])]
param(
# The latest version found in GitHub releases. Null when the repository has no releases.
[Parameter()]
[AllowNull()]
[object] $GitHubVersion,
# The latest version found in the PowerShell Gallery. Null when the module is unpublished.
[Parameter()]
[AllowNull()]
[object] $PSGalleryVersion
)
LogGroup 'Latest version' {
$candidates = @($PSGalleryVersion, $GitHubVersion) |
Where-Object { $null -ne $_ -and -not [string]::IsNullOrWhiteSpace([string]$_) }
$latestVersion = if ($candidates.Count -gt 0) {
New-PSSemVer -Version ($candidates | Sort-Object -Descending | Select-Object -First 1)
} else {
Write-Warning "No published version found in GitHub or the PowerShell Gallery. Using '0.0.0'."
New-PSSemVer -Version '0.0.0'
}
Write-Host "Latest version: [$($latestVersion.ToString())]"
$latestVersion
}
}
function Get-NextPrereleaseNumber {
<#
.SYNOPSIS
Calculates the next incremental prerelease number across GitHub and PSGallery.
.DESCRIPTION
Queries both GitHub releases and the PowerShell Gallery for existing prereleases
matching the base version and prerelease name, then returns the next number
zero-padded to three digits.
.OUTPUTS
String. A zero-padded three-digit number (e.g. '001').
.EXAMPLE
$number = Get-NextPrereleaseNumber -ModuleName 'MyModule' -BaseVersion '1.2.3' -PrereleaseName 'mybranch' -Releases $releases
#>
[CmdletBinding()]
[OutputType([string])]
param(
# The module name to query in the PowerShell Gallery.
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string] $ModuleName,
# The base version string without prerelease (e.g. '1.2.3').
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string] $BaseVersion,
# The sanitized prerelease name derived from the branch name.
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string] $PrereleaseName,
# The GitHub releases list. Empty or null when the repository has no releases.
[Parameter()]
[AllowNull()]
[AllowEmptyCollection()]
[array] $Releases = @()
)
$params = @{
Name = $ModuleName
Version = '*'
Prerelease = $true
Repository = 'PSGallery'
Verbose = $false
ErrorAction = 'SilentlyContinue'
}
$matchingPSGalleryPrereleases = Find-PSResource @params |
Where-Object { "$($_.Version.Major).$($_.Version.Minor).$($_.Version.Build)" -eq $BaseVersion } |
Where-Object { $_.Prerelease -like "$PrereleaseName*" }
$latestPSGalleryNumber = $matchingPSGalleryPrereleases.Prerelease | ForEach-Object {
[long]($_ -replace $PrereleaseName)
} | Sort-Object | Select-Object -Last 1
Write-Host "PSGallery prerelease: [$latestPSGalleryNumber]"
$matchingGHPrereleases = $Releases |
Where-Object { $_.tagName -like "*$BaseVersion*" } |
Where-Object { $_.tagName -like "*$PrereleaseName*" }
$latestGHNumber = $matchingGHPrereleases.tagName | ForEach-Object {
$tagWithoutDots = $_ -replace '\.'
[long](($tagWithoutDots -split $PrereleaseName, 2)[-1])
} | Sort-Object | Select-Object -Last 1
Write-Host "GitHub prerelease: [$latestGHNumber]"
if ($null -eq $latestPSGalleryNumber) { $latestPSGalleryNumber = 0 }
if ($null -eq $latestGHNumber) { $latestGHNumber = 0 }
$nextNumber = [Math]::Max($latestPSGalleryNumber, $latestGHNumber) + 1
([string]$nextNumber).PadLeft(3, '0')
}
function Get-NextModuleVersion {
<#
.SYNOPSIS
Calculates the next module version based on the release decision.
.DESCRIPTION
Increments the current version according to the version bump type (major, minor, or patch),
then optionally appends a prerelease suffix with support for date-based and incremental numbering.
.OUTPUTS
PSSemVer representing the resolved next version.
.EXAMPLE
$newVersion = Get-NextModuleVersion -LatestVersion $latestVersion -Decision $decision `
-Configuration $config -ModuleName 'MyModule' -Releases $releases
#>
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '',
Justification = 'Parameter is used inside LogGroup script block.')]
[CmdletBinding()]
[OutputType([object])]
param(
# The current latest published version. Null resolves to a '0.0.0' baseline.
[Parameter()]
[AllowNull()]
[object] $LatestVersion,
# The release decision object.
[Parameter(Mandatory)]
[PSCustomObject] $Decision,
# The publish configuration object.
[Parameter(Mandatory)]
[PSCustomObject] $Configuration,
# The name of the module.
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string] $ModuleName,
# The GitHub releases list, used for incremental prerelease calculation.
# Empty or null when the repository has no releases.
[Parameter()]
[AllowNull()]
[AllowEmptyCollection()]
[array] $Releases = @()
)
LogGroup 'Calculate new version' {
$baseVersion = if ($null -eq $LatestVersion -or [string]::IsNullOrWhiteSpace([string]$LatestVersion)) {
Write-Warning "No latest version was resolved. Using '0.0.0' as the baseline."
'0.0.0'
} else {
$LatestVersion
}
$newVersion = New-PSSemVer -Version $baseVersion
$newVersion.Prefix = $Configuration.VersionPrefix
if ($Decision.MajorRelease) {
Write-Host 'Incrementing major version.'
$newVersion.BumpMajor()
} elseif ($Decision.MinorRelease) {
Write-Host 'Incrementing minor version.'
$newVersion.BumpMinor()
} elseif ($Decision.PatchRelease) {
Write-Host 'Incrementing patch version.'
$newVersion.BumpPatch()
}
Write-Host "Partial new version: [$newVersion]"
if ($Decision.CreatePrerelease -and $Decision.HasVersionBump) {
$prereleaseName = $Decision.PrereleaseName
Write-Host "Adding a prerelease tag using the branch name [$prereleaseName]."
$newVersion.Prerelease = $prereleaseName
if (-not [string]::IsNullOrEmpty($Configuration.DatePrereleaseFormat)) {
Write-Host "Using date-based prerelease format: [$($Configuration.DatePrereleaseFormat)]."
$newVersion.Prerelease += "$(Get-Date -Format $Configuration.DatePrereleaseFormat)"
}
if ($Configuration.IncrementalPrerelease -or -not $Decision.ShouldPublish) {
$baseVersionString = "$($newVersion.Major).$($newVersion.Minor).$($newVersion.Patch)"
$params = @{
ModuleName = $ModuleName
BaseVersion = $baseVersionString
PrereleaseName = $prereleaseName
Releases = $Releases
}
$newVersion.Prerelease += Get-NextPrereleaseNumber @params
}
}
Write-Host "New version: [$($newVersion.ToString())]"
$newVersion
}
}
function Get-ResolvedModuleVersion {
<#
.SYNOPSIS
Resolves the next module version and resumes an incomplete stable release when possible.
.DESCRIPTION
Normally the highest version from GitHub Releases and the PowerShell Gallery is the
version baseline. If Gallery contains exactly the stable version implied by the latest
GitHub release and this run's version bump, Gallery publication succeeded but GitHub
release creation did not. In that case, return the Gallery version rather than bumping
again so the workflow can resume the missing GitHub release.
.OUTPUTS
PSSemVer representing the resolved module version.
#>
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '',
Justification = 'Parameter is used inside LogGroup script block.')]
[CmdletBinding()]
[OutputType([object])]
param(
# The latest version found in GitHub Releases.
[Parameter(Mandatory)]
[object] $GitHubVersion,
# The latest stable version found in the PowerShell Gallery.
[Parameter(Mandatory)]
[object] $PSGalleryVersion,
# The release decision for this workflow run.
[Parameter(Mandatory)]
[PSCustomObject] $Decision,
# The publish configuration object.
[Parameter(Mandatory)]
[PSCustomObject] $Configuration,
# The name of the module.
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string] $ModuleName,
# The GitHub releases list, used for prerelease numbering.
[Parameter()]
[AllowNull()]
[AllowEmptyCollection()]
[array] $Releases = @()
)
LogGroup 'Resolve module version' {
$latestVersion = Get-LatestPublishedVersion -GitHubVersion $GitHubVersion -PSGalleryVersion $PSGalleryVersion
$params = @{
LatestVersion = $latestVersion
Decision = $Decision
Configuration = $Configuration
ModuleName = $ModuleName
Releases = $Releases
}
$resolvedVersion = Get-NextModuleVersion @params
if ($Decision.CreateRelease) {
$githubParams = $params.Clone()
$githubParams.LatestVersion = $GitHubVersion
$githubCandidate = Get-NextModuleVersion @githubParams
$galleryVersionString = "$($PSGalleryVersion.Major).$($PSGalleryVersion.Minor).$($PSGalleryVersion.Patch)"
$githubCandidateString = "$($githubCandidate.Major).$($githubCandidate.Minor).$($githubCandidate.Patch)"
if ([string]::IsNullOrWhiteSpace($PSGalleryVersion.Prerelease) -and
$galleryVersionString -eq $githubCandidateString) {
Write-Host (
"PowerShell Gallery contains [$galleryVersionString], the next stable version after " +
"GitHub [$GitHubVersion]. Resuming the Gallery-only publication."
)
$resolvedVersion = $githubCandidate
}
}
$resolvedVersion
}
}
function Write-ActionOutput {
<#
.SYNOPSIS
Emits the resolved version and release type as GitHub Actions step outputs.
.EXAMPLE
Write-ActionOutput -Decision $decision -NewVersion $newVersion
#>
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '',
Justification = 'Parameter is used inside LogGroup script block.')]
[CmdletBinding()]
param(
# The release decision object.
[Parameter(Mandatory)]
[PSCustomObject] $Decision,
# The resolved next version.
[Parameter(Mandatory)]
[object] $NewVersion
)
LogGroup 'Emit outputs' {
$versionString = "$($NewVersion.Major).$($NewVersion.Minor).$($NewVersion.Patch)"
$prereleaseString = [string]$NewVersion.Prerelease
$fullVersionString = $NewVersion.ToString()
$resolvedReleaseType = if ($Decision.ShouldPublish) {
if ($Decision.CreateRelease) { 'Release' } else { 'Prerelease' }
} else {
'None'
}
Add-Content -Path $env:GITHUB_OUTPUT -Value "Version=$versionString"
Add-Content -Path $env:GITHUB_OUTPUT -Value "Prerelease=$prereleaseString"
Add-Content -Path $env:GITHUB_OUTPUT -Value "FullVersion=$fullVersionString"
Add-Content -Path $env:GITHUB_OUTPUT -Value "ReleaseType=$resolvedReleaseType"
Add-Content -Path $env:GITHUB_OUTPUT -Value "CreateRelease=$($Decision.ShouldPublish.ToString().ToLower())"
Write-Host '-------------------------------------------------'
Write-Host ([PSCustomObject]@{
Version = $versionString
Prerelease = $prereleaseString
FullVersion = $fullVersionString
ReleaseType = $resolvedReleaseType
CreateRelease = $Decision.ShouldPublish
} | Format-List | Out-String)
Write-Host '-------------------------------------------------'
}
}