diff --git a/Actions/.Modules/ReadSettings.psm1 b/Actions/.Modules/ReadSettings.psm1
index 8cb88c35f..9183c8c8d 100644
--- a/Actions/.Modules/ReadSettings.psm1
+++ b/Actions/.Modules/ReadSettings.psm1
@@ -322,6 +322,7 @@ function GetDefaultSettings
}
"pullRequestTrigger" = "pull_request"
"skipDraftPullRequests" = $false
+ "optionalPatternsForPrValidation" = @()
"bcptThresholds" = [ordered]@{
"DurationWarning" = 10
"DurationError" = 25
diff --git a/Actions/.Modules/settings.schema.json b/Actions/.Modules/settings.schema.json
index 27781556c..47c8228b3 100644
--- a/Actions/.Modules/settings.schema.json
+++ b/Actions/.Modules/settings.schema.json
@@ -3,6 +3,14 @@
"description": "Schema for AL-Go settings",
"type": "object",
"properties": {
+ "optionalPatternsForPrValidation": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "default": [],
+ "description": "Optional case-insensitive PowerShell wildcard patterns matching full job names. Only names matching 'Build * (*) / *' qualify, including custom jobs following this convention. Matching failures do not block the aggregate Pull Request Status Check; jobs outside this convention remain required. Applies to PTE and AppSource Pull Request Build workflows, including merge groups. See https://aka.ms/ALGoSettings#optionalPatternsForPrValidation"
+ },
"type": {
"type": "string",
"minLength": 1,
diff --git a/Actions/PullRequestStatusCheck/PullRequestStatusCheck.ps1 b/Actions/PullRequestStatusCheck/PullRequestStatusCheck.ps1
index 49f707fd2..72bd0df39 100644
--- a/Actions/PullRequestStatusCheck/PullRequestStatusCheck.ps1
+++ b/Actions/PullRequestStatusCheck/PullRequestStatusCheck.ps1
@@ -1,11 +1,13 @@
-$gitHubHelperPath = Join-Path $PSScriptRoot '..\Github-Helper.psm1' -Resolve
-Import-Module $gitHubHelperPath -DisableNameChecking
+. (Join-Path $PSScriptRoot '..\AL-Go-Helper.ps1' -Resolve)
<#
.SYNOPSIS
- Checks the status of all jobs in a Pull Request build run and fails if any job failed.
+ Checks a Pull Request build run and fails if any required job failed.
.DESCRIPTION
- Queries the GitHub Actions jobs API for the given run and throws if any job concluded with "failure".
+ Queries the GitHub Actions jobs API and throws for required jobs concluded with "failure".
+ Jobs named "Build * (*) / *" matching optional wildcard patterns emit warnings instead.
+ Other jobs remain required. Other conclusions retain their existing behavior.
+ Writes failedOptionalJobs as a JSON array of failed optional job names before reporting required failures.
The jobs endpoint is paginated and can return a large response for builds with many jobs (for example
a build that spans many countries). Three robustness measures are applied:
- The request is retried, because the (large) jobs endpoint intermittently returns HTTP 502.
@@ -18,36 +20,75 @@ Import-Module $gitHubHelperPath -DisableNameChecking
The repository (owner/name) that owns the run.
.PARAMETER RunId
The id of the workflow run to check.
+.PARAMETER OptionalPatterns
+ Case-insensitive PowerShell wildcard patterns matching full build job names.
.EXAMPLE
PullRequestStatusCheck -Repository "owner/repo" -RunId "123456"
#>
-function PullRequestStatusCheck()
-{
+function PullRequestStatusCheck() {
param(
[Parameter(HelpMessage = "Repository name", Mandatory = $true)]
[string] $Repository,
[Parameter(HelpMessage = "Run Id", Mandatory = $true)]
- [string] $RunId
+ [string] $RunId,
+ [string[]] $OptionalPatterns = @()
)
Write-Host "Checking PR Build status for run $RunId in repository $Repository"
+ foreach ($pattern in $OptionalPatterns) {
+ # Fail-Fast for invalid wildcard patterns. Force wildcard parsing even when the run contains no failed jobs.
+ $null = '' -like $pattern
+ }
$env:GH_HOST = ([Uri]$env:GITHUB_SERVER_URL).Host
$workflowJobs = Invoke-CommandWithRetry -RetryCount 5 -FirstDelay 5 -MaxWaitBetweenRetries 60 -ScriptBlock {
$jobsJson = gh api "/repos/$Repository/actions/runs/$RunId/jobs?per_page=50" --paginate --slurp -H "Accept: application/vnd.github+json" -H "X-GitHub-Api-Version: 2022-11-28"
if ($LASTEXITCODE) {
throw "Failed to get jobs for run $RunId in repository $Repository (gh exit code $LASTEXITCODE)."
}
- $jobsJson | ConvertFrom-Json
+ $jobsJson | ConvertFrom-Json | ForEach-Object {
+ foreach ($page in $_) {
+ $page | ConvertTo-HashTable -recurse
+ }
+ }
}
# --slurp yields an array with one entry per page; member enumeration flattens jobs across all pages.
# When a single (non-slurped) object is returned, .jobs resolves to that object's jobs.
$failedJobs = @($workflowJobs.jobs | Where-Object { $_.conclusion -eq "failure" })
- if ($failedJobs) {
- throw "PR Build failed. Failing jobs: $($failedJobs.name -join ', ')"
+ $failedOptionalJobs = @()
+ $badFailures = @(
+ foreach ($job in $failedJobs) {
+ $matchesOptionalPattern = @($OptionalPatterns | Where-Object { $job.name -like $_ }).Count -gt 0
+ if ($job.name -like 'Build * (*) / *' -and $matchesOptionalPattern) {
+ $failedOptionalJobs += $job.name
+ OutputWarning -message "Optional PR build job failed (non-blocking): $($job.name)"
+ continue
+ }
+ $job
+ }
+ )
+ $failedOptionalJobsJson = ConvertTo-Json -InputObject $failedOptionalJobs -Compress
+ Add-Content -Encoding UTF8 -Path $env:GITHUB_OUTPUT -Value "failedOptionalJobs=$failedOptionalJobsJson"
+ if ($badFailures) {
+ throw "PR Build failed. Failing jobs: $($badFailures.name -join ', ')"
}
}
-PullRequestStatusCheck -Repository $env:GITHUB_REPOSITORY -RunId $env:GITHUB_RUN_ID
+if (!$env:Settings) {
+ throw "Settings environment variable is required."
+}
+$settingsJson = $env:Settings | ConvertFrom-Json
+$rawOptionalPatterns = $settingsJson.optionalPatternsForPrValidation
+if ($rawOptionalPatterns -isnot [System.Array]) {
+ throw "Settings.optionalPatternsForPrValidation must be an array."
+}
+foreach ($pattern in $rawOptionalPatterns) {
+ if ($pattern -isnot [string]) {
+ throw "Settings.optionalPatternsForPrValidation must contain only strings."
+ }
+}
+$settings = $settingsJson | ConvertTo-HashTable -recurse
+$optionalPatterns = @($settings.optionalPatternsForPrValidation)
+PullRequestStatusCheck -Repository $env:GITHUB_REPOSITORY -RunId $env:GITHUB_RUN_ID -OptionalPatterns $optionalPatterns
Write-Host "PR Build succeeded"
diff --git a/Actions/PullRequestStatusCheck/README.md b/Actions/PullRequestStatusCheck/README.md
index cb761b2cb..9cf1da11a 100644
--- a/Actions/PullRequestStatusCheck/README.md
+++ b/Actions/PullRequestStatusCheck/README.md
@@ -1,6 +1,6 @@
# Pull Request Status Check
-Check the status of a pull request build and fail the build if any jobs have failed.
+Check the status of a pull request build and fail if any required jobs have failed. Matching optional build-matrix failures emit warnings instead. Other job conclusions retain their existing behavior.
## INPUT
@@ -16,6 +16,25 @@ Check the status of a pull request build and fail the build if any jobs have fai
| :-- | :-: | :-- | :-- |
| shell | | The shell (powershell or pwsh) in which the PowerShell script in this action should run | powershell |
+Optional build job patterns are read from `Settings.optionalPatternsForPrValidation`, which is populated by the preceding ReadSettings action. The setting is an array of case-insensitive PowerShell wildcard patterns matching full build job names.
+
+The PTE and AppSource Pull Request Build workflows read settings in the StatusCheck job after checking out the build ref. The patterns are passed as JSON from the ReadSettings action's standard `Settings` environment variable. Only jobs whose API names match `Build * (*) / *` can be optional, and they must also match a configured pattern. Custom jobs using this naming convention also qualify. Jobs outside this convention remain required even with a broad wildcard. Invalid JSON or input shapes fail explicitly.
+
+Optional jobs and the workflow run may remain failed while this aggregate status check succeeds. See [optional PR builds](../../Scenarios/settings.md#optional-pr-builds).
+
## OUTPUT
-none
+| Name | Description |
+| :-- | :-- |
+| failedOptionalJobs | JSON array of full names of failed optional build jobs, or `[]` when none qualify. Successful, skipped, cancelled, and required jobs are excluded. |
+
+After job classification, the output is written even if a required job failure causes the action to fail. API or input validation errors do not produce this output.
+
+Give the action step an `id` (for example, `statusCheck`) and read `${{ steps.statusCheck.outputs.failedOptionalJobs }}`. Use `fromJSON(steps.statusCheck.outputs.failedOptionalJobs)` to consume it as an array. To expose it to other jobs, map it to a job output and read `${{ needs.StatusCheck.outputs.failedOptionalJobs }}`:
+
+```yaml
+outputs:
+ failedOptionalJobs: ${{ steps.statusCheck.outputs.failedOptionalJobs }}
+```
+
+Consumers that must run after a required failure need an appropriate condition such as `if: always()`.
diff --git a/Actions/PullRequestStatusCheck/action.yaml b/Actions/PullRequestStatusCheck/action.yaml
index 859b0b364..fe673632d 100644
--- a/Actions/PullRequestStatusCheck/action.yaml
+++ b/Actions/PullRequestStatusCheck/action.yaml
@@ -5,11 +5,16 @@ inputs:
description: Shell in which you want to run the action (powershell or pwsh)
required: false
default: powershell
+outputs:
+ failedOptionalJobs:
+ description: JSON array of failed optional build job names
+ value: ${{ steps.pullrequeststatuscheck.outputs.failedOptionalJobs }}
runs:
using: composite
steps:
- name: run
shell: ${{ inputs.shell }}
+ id: pullrequeststatuscheck
run: |
${{ github.action_path }}/../Invoke-AlGoAction.ps1 -ActionName "PullRequestStatusCheck" -Action {
${{ github.action_path }}/PullRequestStatusCheck.ps1
diff --git a/RELEASENOTES.md b/RELEASENOTES.md
index ca179be70..0f0ee535f 100644
--- a/RELEASENOTES.md
+++ b/RELEASENOTES.md
@@ -1,3 +1,9 @@
+### Optional builds for PR validation
+
+The new `optionalPatternsForPrValidation` setting (default `[]`) lets PTE and AppSource repositories make selected build-matrix failures non-blocking for the aggregate **Pull Request Status Check**, including merge-group runs. Case-insensitive PowerShell wildcard patterns match full GitHub job names. Eligible names must also match `Build * (*) / *`; custom jobs following this convention also qualify. Optional failures emit warnings; jobs outside this convention remain required. Individual optional jobs and the workflow run can still be red, so rulesets should require the aggregate check. Update AL-Go system files for the new input wiring. See [optionalPatternsForPrValidation](Scenarios/settings.md#optionalPatternsForPrValidation).
+
+The PullRequestStatusCheck action exposes `failedOptionalJobs`, a JSON array of failed optional build job names (`[]` when none qualify), for consumption by later steps or via job outputs. The output is also written when required job failures cause the check to fail.
+
## v10.1
### Optional draft PR build skipping
diff --git a/Scenarios/settings.md b/Scenarios/settings.md
index f3b5fe762..f8d9b8156 100644
--- a/Scenarios/settings.md
+++ b/Scenarios/settings.md
@@ -163,6 +163,28 @@ The following settings are only allowed in workflow specific settings files or i
| appSourceContextSecretName | This setting specifies the name (**NOT the secret**) of a secret containing a json string with ClientID, TenantID and ClientSecret or RefreshToken. If this secret exists, AL-Go will can upload builds to AppSource validation. | AppSourceContext |
| keyVaultCertificateUrlSecretName
keyVaultCertificatePasswordSecretName
keyVaultClientIdSecretName | If you want to enable KeyVault access for your AppSource App, you need to provide 3 secrets as GitHub Secrets or in the Azure KeyVault. The names of those secrets (**NOT the secrets**) should be specified in the settings file with these 3 settings. Default is to not have KeyVault access from your AppSource App. Read [this](EnableKeyVaultForAppSourceApp.md) for more information. | |
+## Optional PR builds
+
+| Name | Description | Default value |
+| :-- | :-- | :-- |
+| optionalPatternsForPrValidation | Optional array of strings containing case-insensitive PowerShell wildcard patterns (`*`, `?`, and character sets) matching full GitHub build-matrix job names. Matching failed builds emit warnings instead of blocking **Pull Request Status Check**. Non-build jobs always remain required. Honored by the **Pull Request Build** workflows, including merge-group runs; not by CI/CD or the Current, NextMinor, and NextMajor workflows. Read in the StatusCheck job from organization, repository, workflow, and root project settings, without aggregating settings from individual matrix projects. | `[]` |
+
+For example, when a build mode is named `NextMinor`, configure:
+
+```json
+{
+ "optionalPatternsForPrValidation": ["Build * (NextMinor) / *"]
+}
+```
+
+Patterns match the full job name returned by GitHub, such as `Build MyProject (NextMinor) / MyProject (NextMinor)`, not artifact URLs or build-mode settings directly. Matching uses PowerShell `-like`, just as conditional settings do, not regular expressions. Arrays follow the existing settings merge and `overwriteSettings` rules. An empty array keeps all failures blocking.
+
+Only jobs whose full API names match `Build * (*) / *` can be optional, and they must also match a configured pattern. Custom jobs following this naming convention also qualify. Initialization, fork validation, code analysis, and other jobs outside this convention remain required even with `["*"]`. Jobs sharing the same name follow the same pattern-matching rules. A failure in any step of an eligible build job can be optional, including container setup or checkout failures. Additional-country execution inside that same job cannot be made optional separately.
+
+Individual optional jobs and the workflow run can still appear failed while the aggregate **Pull Request Status Check** succeeds. Configure branch protection/rulesets to require the aggregate check rather than the optional jobs. Optional failures are reported as workflow warnings.
+
+Only jobs with conclusion `failure` are affected. Existing cancellation/skipping behavior and dependency scheduling are unchanged: an optional failure does not rerun downstream builds that were skipped because of it. The same policy applies to merge-queue validation. Update AL-Go system files to obtain the new workflow input wiring.
+
## Conditional Settings
diff --git a/Templates/AppSource App/.github/workflows/PullRequestHandler.yaml b/Templates/AppSource App/.github/workflows/PullRequestHandler.yaml
index f910c15a7..1f10e2aa4 100644
--- a/Templates/AppSource App/.github/workflows/PullRequestHandler.yaml
+++ b/Templates/AppSource App/.github/workflows/PullRequestHandler.yaml
@@ -160,6 +160,17 @@ jobs:
runs-on: [ windows-latest ]
name: Pull Request Status Check
steps:
+ - name: Checkout
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ lfs: true
+ ref: ${{ github.event_name == 'pull_request' && github.sha || github.event_name == 'merge_group' && github.ref || format('refs/pull/{0}/merge', github.event.pull_request.number) }}
+
+ - name: Read settings
+ uses: microsoft/AL-Go-Actions/ReadSettings@main
+ with:
+ shell: powershell
+
- name: Pull Request Status Check
id: PullRequestStatusCheck
uses: microsoft/AL-Go-Actions/PullRequestStatusCheck@main
diff --git a/Templates/Per Tenant Extension/.github/workflows/PullRequestHandler.yaml b/Templates/Per Tenant Extension/.github/workflows/PullRequestHandler.yaml
index f910c15a7..1f10e2aa4 100644
--- a/Templates/Per Tenant Extension/.github/workflows/PullRequestHandler.yaml
+++ b/Templates/Per Tenant Extension/.github/workflows/PullRequestHandler.yaml
@@ -160,6 +160,17 @@ jobs:
runs-on: [ windows-latest ]
name: Pull Request Status Check
steps:
+ - name: Checkout
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ lfs: true
+ ref: ${{ github.event_name == 'pull_request' && github.sha || github.event_name == 'merge_group' && github.ref || format('refs/pull/{0}/merge', github.event.pull_request.number) }}
+
+ - name: Read settings
+ uses: microsoft/AL-Go-Actions/ReadSettings@main
+ with:
+ shell: powershell
+
- name: Pull Request Status Check
id: PullRequestStatusCheck
uses: microsoft/AL-Go-Actions/PullRequestStatusCheck@main
diff --git a/Tests/PullRequestStatusCheck.Test.ps1 b/Tests/PullRequestStatusCheck.Test.ps1
index 85a542467..6a72f8a37 100644
--- a/Tests/PullRequestStatusCheck.Test.ps1
+++ b/Tests/PullRequestStatusCheck.Test.ps1
@@ -1,4 +1,10 @@
-Get-Module TestActionsHelper | Remove-Module -Force
+[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', 'optionalJobName', Justification = 'Used by Pester test and mock scopes.')]
+[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', 'requiredJobName', Justification = 'Used by Pester test and mock scopes.')]
+[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', 'jobsJson', Justification = 'Used by Pester mocks.')]
+[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', 'Patterns', Justification = 'Used in Pester assertion scriptblocks.')]
+param()
+
+Get-Module TestActionsHelper | Remove-Module -Force
Import-Module (Join-Path $PSScriptRoot 'TestActionsHelper.psm1')
$errorActionPreference = "Stop"; $ProgressPreference = "SilentlyContinue"; Set-StrictMode -Version 2.0
@@ -19,12 +25,24 @@ Describe "PullRequestStatusCheck Action Tests" {
$originalServerUrl = $ENV:GITHUB_SERVER_URL
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', 'originalGhHost', Justification = 'False positive.')]
$originalGhHost = $ENV:GH_HOST
+ [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', 'originalGithubOutput', Justification = 'Used in AfterAll.')]
+ $originalGithubOutput = $ENV:GITHUB_OUTPUT
+ [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', 'originalSettings', Justification = 'Used in AfterAll.')]
+ $originalSettings = $ENV:Settings
$ENV:GITHUB_SERVER_URL = "https://github.com"
}
+ BeforeEach {
+ $ENV:GITHUB_OUTPUT = Join-Path $TestDrive 'github_output.txt'
+ Set-Content -Encoding UTF8 -Path $ENV:GITHUB_OUTPUT -Value $null
+ $ENV:Settings = '{"optionalPatternsForPrValidation":[]}'
+ }
+
AfterAll {
$ENV:GITHUB_SERVER_URL = $originalServerUrl
$ENV:GH_HOST = $originalGhHost
+ $ENV:GITHUB_OUTPUT = $originalGithubOutput
+ $ENV:Settings = $originalSettings
}
It 'Compile Action' {
@@ -33,6 +51,7 @@ Describe "PullRequestStatusCheck Action Tests" {
It 'Test action.yaml matches script' {
$outputs = [ordered]@{
+ "failedOptionalJobs" = "JSON array of failed optional build job names"
}
YamlTest -scriptRoot $scriptRoot -actionName $actionName -actionScript $actionScript -outputs $outputs
}
@@ -56,6 +75,7 @@ Describe "PullRequestStatusCheck Action Tests" {
Mock Write-Host {}
& $scriptPath
Assert-MockCalled Write-Host -Exactly 1 -Scope It -ParameterFilter { $Object -eq "PR Build succeeded" }
+ (Get-Content -Encoding UTF8 -Path $ENV:GITHUB_OUTPUT -Raw).Trim() | Should -Be 'failedOptionalJobs=[]'
$ENV:GH_HOST | Should -Be 'github.com'
}
@@ -67,4 +87,162 @@ Describe "PullRequestStatusCheck Action Tests" {
} | Should -Throw -ExpectedMessage '*Failed to get jobs for run*'
Assert-MockCalled gh -Exactly 5 -Scope It
}
+
+ Context 'Optional build failures' {
+ BeforeAll {
+ $optionalJobName = 'Build Alpha (NextMinor) / Alpha (NextMinor)'
+ $requiredJobName = 'Build Beta (Default) / Beta (Default)'
+ }
+
+ BeforeEach {
+ $jobsJson = ConvertTo-Json -InputObject @{ jobs = @(
+ @{ name = $optionalJobName; conclusion = 'failure' }
+ @{ name = $requiredJobName; conclusion = 'success' }
+ ) } -Depth 10
+ Mock gh { $global:LASTEXITCODE = 0; $jobsJson }
+ Mock OutputWarning {}
+ Mock Write-Host {}
+ Mock Start-Sleep -ModuleName Github-Helper {}
+ }
+
+ It 'Allows an optional failure using ' -TestCases @(
+ @{ Patterns = '["Build Alpha (NextMinor) / Alpha (NextMinor)"]' }
+ @{ Patterns = '["*NextMinor*"]' }
+ @{ Patterns = '["*nextminor*"]' }
+ @{ Patterns = '["Build Alph? (*) / *"]' }
+ @{ Patterns = '["Build [AB]*"]' }
+ @{ Patterns = '["no match","*NextMinor*"]' }
+ ) {
+ param($Patterns)
+ $ENV:Settings = "{`"optionalPatternsForPrValidation`":$Patterns}"
+ & $scriptPath
+ Assert-MockCalled OutputWarning -Exactly 1 -ParameterFilter { $message -eq "Optional PR build job failed (non-blocking): $optionalJobName" }
+ Assert-MockCalled Write-Host -Exactly 1 -ParameterFilter { $Object -eq 'PR Build succeeded' }
+ $outputJson = (Get-Content -Encoding UTF8 -Path $ENV:GITHUB_OUTPUT -Raw).Trim() -replace '^failedOptionalJobs=', ''
+ $outputJson | Should -Be (ConvertTo-Json -InputObject @($optionalJobName) -Compress)
+ }
+
+ It 'Preserves failures with ' -TestCases @(
+ @{ Patterns = '[]' }
+ @{ Patterns = '["no match"]' }
+ ) {
+ param($Patterns)
+ $ENV:Settings = "{`"optionalPatternsForPrValidation`":$Patterns}"
+ { & $scriptPath } |
+ Should -Throw -ExpectedMessage "PR Build failed. Failing jobs: $optionalJobName"
+ (Get-Content -Encoding UTF8 -Path $ENV:GITHUB_OUTPUT -Raw).Trim() | Should -Be 'failedOptionalJobs=[]'
+ }
+
+ It 'Warns about optional failures and only reports required failures across pages' {
+ $jobsJson = '[{"jobs":[{"name":"Build Alpha (NextMinor) / Alpha (NextMinor)","conclusion":"failure"}]},{"jobs":[{"name":"Build Beta (Default) / Beta (Default)","conclusion":"failure"}]}]'
+ $ENV:Settings = '{"optionalPatternsForPrValidation":["*NextMinor*"]}'
+ { & $scriptPath } |
+ Should -Throw -ExpectedMessage "PR Build failed. Failing jobs: $requiredJobName"
+ Assert-MockCalled OutputWarning -Exactly 1 -ParameterFilter { $message -like 'Optional PR build job failed*' }
+ $outputJson = (Get-Content -Encoding UTF8 -Path $ENV:GITHUB_OUTPUT -Raw).Trim() -replace '^failedOptionalJobs=', ''
+ $outputJson | Should -Be (ConvertTo-Json -InputObject @($optionalJobName) -Compress)
+ }
+
+ It 'Outputs only failed optional build names across pages and escapes JSON characters' {
+ $escapedJobName = 'Build "Custom" (NextMinor) / Custom\Path (NextMinor)'
+ $jobsJson = ConvertTo-Json -InputObject @(
+ @{ jobs = @(
+ @{ name = $optionalJobName; conclusion = 'failure' }
+ @{ name = $optionalJobName; conclusion = 'success' }
+ @{ name = 'Initialization'; conclusion = 'skipped' }
+ ) }
+ @{ jobs = @(
+ @{ name = $escapedJobName; conclusion = 'failure' }
+ @{ name = $optionalJobName; conclusion = 'cancelled' }
+ ) }
+ ) -Depth 10
+ $ENV:Settings = '{"optionalPatternsForPrValidation":["*"]}'
+ & $scriptPath
+ $outputJson = (Get-Content -Encoding UTF8 -Path $ENV:GITHUB_OUTPUT -Raw).Trim() -replace '^failedOptionalJobs=', ''
+ $outputJson | Should -Be (ConvertTo-Json -InputObject @($optionalJobName, $escapedJobName) -Compress)
+ }
+
+ It 'Keeps non-build jobs required even with a broad wildcard: ' -TestCases @(
+ @{ Name = 'Initialization' }
+ @{ Name = 'PregateCheck' }
+ @{ Name = 'Code Analysis Processing' }
+ @{ Name = 'Build Custom (NextMinor)' }
+ @{ Name = 'Custom (NextMinor) / Custom (NextMinor)' }
+ @{ Name = 'Build Custom / Custom' }
+ ) {
+ param($Name)
+ $jobsJson = ConvertTo-Json -InputObject @{ jobs = @(@{ name = $Name; conclusion = 'failure' }) } -Depth 10
+ $ENV:Settings = '{"optionalPatternsForPrValidation":["*"]}'
+ { & $scriptPath } |
+ Should -Throw -ExpectedMessage "PR Build failed. Failing jobs: $Name"
+ }
+
+ It 'Keeps infrastructure failures blocking alongside optional build failures' {
+ $jobsJson = ConvertTo-Json -InputObject @{ jobs = @(
+ @{ name = $optionalJobName; conclusion = 'failure' }
+ @{ name = 'Initialization'; conclusion = 'failure' }
+ ) } -Depth 10
+ $ENV:Settings = '{"optionalPatternsForPrValidation":["*"]}'
+ { & $scriptPath } |
+ Should -Throw -ExpectedMessage 'PR Build failed. Failing jobs: Initialization'
+ Assert-MockCalled OutputWarning -Exactly 1 -ParameterFilter { $message -like 'Optional PR build job failed*' }
+ }
+
+ It 'Allows matching build names without metadata or a matrix suffix: ' -TestCases @(
+ @{ Name = 'Build Custom (NextMinor) / Custom (NextMinor)' }
+ @{ Name = 'Build Beta (Default) / Beta (Default)' }
+ @{ Name = 'build alpha (nextminor) / alpha (nextminor)' }
+ @{ Name = 'Build Al* (NextMinor) / Al* (NextMinor)' }
+ @{ Name = 'Build Custom (NextMinor) / Setup' }
+ ) {
+ param($Name)
+ $jobsJson = ConvertTo-Json -InputObject @{ jobs = @(@{ name = $Name; conclusion = 'failure' }) } -Depth 10
+ $ENV:Settings = '{"optionalPatternsForPrValidation":["*"]}'
+ & $scriptPath
+ Assert-MockCalled OutputWarning -Exactly 1 -ParameterFilter { $message -like 'Optional PR build job failed*' }
+ }
+
+ It 'Allows optional failures with duplicate API names and conclusions' -TestCases @(
+ @{ Conclusion = 'success'; Warnings = 1 }
+ @{ Conclusion = 'failure'; Warnings = 2 }
+ ) {
+ param($Conclusion, $Warnings)
+ $jobsJson = ConvertTo-Json -InputObject @{ jobs = @(
+ @{ name = $optionalJobName; conclusion = 'failure' }
+ @{ name = $optionalJobName; conclusion = $Conclusion }
+ ) } -Depth 10
+ $ENV:Settings = '{"optionalPatternsForPrValidation":["*"]}'
+ & $scriptPath
+ Assert-MockCalled OutputWarning -Exactly $Warnings -ParameterFilter { $message -eq "Optional PR build job failed (non-blocking): $optionalJobName" }
+ Assert-MockCalled Write-Host -Exactly 1 -ParameterFilter { $Object -eq 'PR Build succeeded' }
+ }
+
+ It 'Preserves non-failure conclusions: ' -TestCases @(
+ @{ Conclusion = 'skipped' }
+ @{ Conclusion = 'cancelled' }
+ @{ Conclusion = 'timed_out' }
+ @{ Conclusion = 'success' }
+ ) {
+ param($Conclusion)
+ $jobsJson = ConvertTo-Json -InputObject @{ jobs = @(@{ name = 'Initialization'; conclusion = $Conclusion }) } -Depth 10
+ $ENV:Settings = '{"optionalPatternsForPrValidation":["*"]}'
+ & $scriptPath
+ Assert-MockCalled Write-Host -Exactly 1 -ParameterFilter { $Object -eq 'PR Build succeeded' }
+ }
+
+ It 'Rejects malformed input: ' -TestCases @(
+ @{ Patterns = '{}' }
+ @{ Patterns = 'null' }
+ @{ Patterns = '[1]' }
+ @{ Patterns = '[null]' }
+ @{ Patterns = '[[]]' }
+ @{ Patterns = '["["]' }
+ @{ Patterns = '[' }
+ ) {
+ param($Patterns)
+ $ENV:Settings = "{`"optionalPatternsForPrValidation`":$Patterns}"
+ { & $scriptPath } | Should -Throw
+ Assert-MockCalled gh -Exactly 0
+ }
+ }
}
diff --git a/Tests/ReadSettings.Action.Test.ps1 b/Tests/ReadSettings.Action.Test.ps1
index e7c0ce02c..be38639ea 100644
--- a/Tests/ReadSettings.Action.Test.ps1
+++ b/Tests/ReadSettings.Action.Test.ps1
@@ -1,237 +1,281 @@
-Get-Module TestActionsHelper | Remove-Module -Force
-Import-Module (Join-Path $PSScriptRoot 'TestActionsHelper.psm1')
-$errorActionPreference = "Stop"; $ProgressPreference = "SilentlyContinue"; Set-StrictMode -Version 2.0
-
-Describe "ReadSettings Action Tests" {
- BeforeAll {
- $actionName = "ReadSettings"
- $scriptRoot = Join-Path $PSScriptRoot "..\Actions\$actionName" -Resolve
- . (Join-Path $scriptRoot '..\AL-Go-Helper.ps1' -Resolve)
- $scriptName = "$actionName.ps1"
- [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', 'scriptPath', Justification = 'False positive.')]
- $scriptPath = Join-Path $scriptRoot $scriptName
- [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', 'actionScript', Justification = 'False positive.')]
- $actionScript = GetActionScript -scriptRoot $scriptRoot -scriptName $scriptName
- }
-
- It 'Compile Action' {
- Invoke-Expression $actionScript
- }
-
- It 'Test action.yaml matches script' {
- $outputs = [ordered]@{
- "GitHubRunnerJson" = "GitHubRunner in compressed Json format"
- "GitHubRunnerShell" = "Shell for GitHubRunner jobs"
- }
- YamlTest -scriptRoot $scriptRoot -actionName $actionName -actionScript $actionScript -outputs $outputs
- }
-
- It 'Emits skipped settings and a single balanced sources group' {
- $workspace = Join-Path ([System.IO.Path]::GetTempPath()) ([Guid]::NewGuid().ToString())
- $originalEnvironment = @{}
- foreach ($name in @('GITHUB_WORKSPACE', 'GITHUB_ENV', 'GITHUB_OUTPUT', 'GITHUB_RUN_NUMBER', 'GITHUB_RUN_ATTEMPT', 'GITHUB_EVENT_NAME', 'ALGoOrgSettings', 'ALGoRepoSettings', 'ALGoEnvSettings')) {
- $originalEnvironment[$name] = [Environment]::GetEnvironmentVariable($name)
- }
-
- try {
- New-Item -ItemType Directory -Path $workspace | Out-Null
- $env:GITHUB_WORKSPACE = $workspace
- $env:GITHUB_ENV = Join-Path $workspace 'github-env.txt'
- $env:GITHUB_OUTPUT = Join-Path $workspace 'github-output.txt'
- $env:GITHUB_RUN_NUMBER = '1'
- $env:GITHUB_RUN_ATTEMPT = '1'
- $env:GITHUB_EVENT_NAME = 'push'
- $env:ALGoOrgSettings = '{"protectedSettings":["country"],"country":"de"}'
- $env:ALGoRepoSettings = '{"country":"ch"}'
- $env:ALGoEnvSettings = ''
-
- $transcriptPath = Join-Path $workspace 'action-log.txt'
- Start-Transcript -Path $transcriptPath -Force | Out-Null
- try {
- & $scriptPath -workflowName '' -project '' | Out-Null
- }
- finally {
- Stop-Transcript | Out-Null
- }
- $output = Get-Content -Path $transcriptPath -Raw -Encoding UTF8
- $notice = 'Skipped setting country from settings ALGoRepoSettings (Variable): protected by settings ALGoOrgSettings (Variable)'
- $groupStart = [regex]::Matches($output, '(?m)(::group::Settings sources|==== Group start: Settings sources ====)')
- $groupEnd = [regex]::Matches($output, '(?m)(::endgroup::|==== Group end ====)')
-
- $output.Contains($notice) | Should -BeTrue
- ([regex]::Matches($output, [regex]::Escape($notice))).Count | Should -Be 1
- $groupStart.Count | Should -Be 1
- $groupEnd.Count | Should -Be 1
- $output.IndexOf($notice) | Should -BeLessThan $groupStart[0].Index
- $groupEnd[0].Index | Should -BeGreaterThan $groupStart[0].Index
- $sourcesGroup = $output.Substring($groupStart[0].Index, $groupEnd[0].Index - $groupStart[0].Index)
- $sourcesGroup | Should -Match '(?m)^country: settings ALGoOrgSettings \(Variable\) \(protected\)\r?$'
- $sourcesGroup | Should -Match '(?m)^shell: default, derived from runs-on\r?$'
- $sourcesGroup | Should -Match '(?m)^alDoc\.includeProjects: default\r?$'
- $sourcesGroup | Should -Match '(?m)^appBuild: default, derived from versioning strategy 0 \(runNumberOffset and GITHUB_RUN_NUMBER\)\r?$'
- $sourcesGroup | Should -Match '(?m)^appRevision: default, derived from versioning strategy 0 \(GITHUB_RUN_ATTEMPT minus 1\)\r?$'
- }
- finally {
- foreach ($name in $originalEnvironment.Keys) {
- [Environment]::SetEnvironmentVariable($name, $originalEnvironment[$name])
- }
- Remove-Item -Path $workspace -Recurse -Force -ErrorAction SilentlyContinue
- }
- }
-
- Context 'Action-level source derivations' {
- BeforeAll {
- $invokeAction = {
- $transcriptPath = Join-Path $workspace 'action-log.txt'
- $startedAt = [DateTime]::UtcNow
- Start-Transcript -Path $transcriptPath -Force | Out-Null
- try {
- & $scriptPath -workflowName '' -project '' | Out-Null
- }
- finally {
- Stop-Transcript | Out-Null
- }
- $finishedAt = [DateTime]::UtcNow
- $output = Get-Content -Path $transcriptPath -Raw -Encoding UTF8
- $groupStart = [regex]::Matches($output, '(?m)(::group::Settings sources|==== Group start: Settings sources ====)')
- $groupEnd = [regex]::Matches($output, '(?m)(::endgroup::|==== Group end ====)')
- $groupStart.Count | Should -Be 1
- $groupEnd.Count | Should -Be 1
- $groupEnd[0].Index | Should -BeGreaterThan $groupStart[0].Index
- $settingsLine = Get-Content -Path $env:GITHUB_ENV -Encoding UTF8 | Where-Object { $_.StartsWith('Settings=') } | Select-Object -Last 1
- @{
- sources = $output.Substring($groupStart[0].Index, $groupEnd[0].Index - $groupStart[0].Index)
- settings = $settingsLine.Substring('Settings='.Length) | ConvertFrom-Json | ConvertTo-HashTable -recurse
- startedAt = $startedAt
- finishedAt = $finishedAt
- }
- }
- }
-
- BeforeEach {
- $workspace = Join-Path ([System.IO.Path]::GetTempPath()) ([Guid]::NewGuid().ToString())
- $originalEnvironment = @{}
- foreach ($name in @('GITHUB_WORKSPACE', 'GITHUB_ENV', 'GITHUB_OUTPUT', 'GITHUB_RUN_NUMBER', 'GITHUB_RUN_ATTEMPT', 'GITHUB_EVENT_NAME', 'ALGoOrgSettings', 'ALGoRepoSettings', 'ALGoEnvSettings')) {
- $originalEnvironment[$name] = [Environment]::GetEnvironmentVariable($name)
- }
- New-Item -ItemType Directory -Path $workspace | Out-Null
- $env:GITHUB_WORKSPACE = $workspace
- $env:GITHUB_ENV = Join-Path $workspace 'github-env.txt'
- $env:GITHUB_OUTPUT = Join-Path $workspace 'github-output.txt'
- $env:GITHUB_RUN_NUMBER = '42'
- $env:GITHUB_RUN_ATTEMPT = '3'
- $env:GITHUB_EVENT_NAME = 'push'
- $env:ALGoOrgSettings = ''
- $env:ALGoRepoSettings = '{"runNumberOffset":100}'
- $env:ALGoEnvSettings = ''
- }
-
- AfterEach {
- foreach ($name in $originalEnvironment.Keys) {
- [Environment]::SetEnvironmentVariable($name, $originalEnvironment[$name])
- }
- Remove-Item -Path $workspace -Recurse -Force -ErrorAction SilentlyContinue
- }
-
- It 'Traces and exports versioning strategy ' -TestCases @(
- @{ strategy = 0; expectedBuild = 142; expectedRevision = 2; buildDerivation = 'runNumberOffset and GITHUB_RUN_NUMBER'; revisionDerivation = 'GITHUB_RUN_ATTEMPT minus 1' }
- @{ strategy = 16; expectedBuild = 142; expectedRevision = 2; buildDerivation = 'runNumberOffset and GITHUB_RUN_NUMBER'; revisionDerivation = 'GITHUB_RUN_ATTEMPT minus 1' }
- @{ strategy = 3; expectedBuild = -1; expectedRevision = 142; buildDerivation = 'use build from app.json'; revisionDerivation = 'runNumberOffset and GITHUB_RUN_NUMBER' }
- @{ strategy = 15; expectedBuild = [int32]::MaxValue; expectedRevision = 142; buildDerivation = 'maxValue'; revisionDerivation = 'runNumberOffset and GITHUB_RUN_NUMBER' }
- ) {
- Param($strategy, $expectedBuild, $expectedRevision, $buildDerivation, $revisionDerivation)
-
- $env:ALGoRepoSettings = @{ versioningStrategy = $strategy; runNumberOffset = 100 } | ConvertTo-Json
- $result = & $invokeAction
- $effectiveStrategy = $strategy -band 15
-
- $result.settings.versioningStrategy | Should -Be $strategy
- $result.settings.appBuild | Should -Be $expectedBuild
- $result.settings.appRevision | Should -Be $expectedRevision
- $result.sources | Should -Match ('(?m)^appBuild: ' + [regex]::Escape("default, derived from versioning strategy $effectiveStrategy ($buildDerivation)") + '\r?$')
- $result.sources | Should -Match ('(?m)^appRevision: ' + [regex]::Escape("default, derived from versioning strategy $effectiveStrategy ($revisionDerivation)") + '\r?$')
- $result.sources | Should -Match '(?m)^versioningStrategy: settings ALGoRepoSettings \(Variable\)\r?$'
- $result.settings.doNotSignApps | Should -BeFalse
- $result.sources | Should -Not -Match 'derived from GitHub pull request or merge group event'
- }
-
- It 'Traces UTC date and time for versioning strategy 2' {
- $env:ALGoRepoSettings = '{"versioningStrategy":2}'
- $result = & $invokeAction
-
- $result.settings.versioningStrategy | Should -Be 2
- @([int32]$result.startedAt.ToString('yyyyMMdd'), [int32]$result.finishedAt.ToString('yyyyMMdd')) | Should -Contain $result.settings.appBuild
- $startTime = [int32]$result.startedAt.ToString('HHmmss')
- $endTime = [int32]$result.finishedAt.ToString('HHmmss')
- if ($result.startedAt.Date -eq $result.finishedAt.Date) {
- ($result.settings.appRevision -ge $startTime -and $result.settings.appRevision -le $endTime) | Should -BeTrue
- }
- else {
- ($result.settings.appRevision -ge $startTime -or $result.settings.appRevision -le $endTime) | Should -BeTrue
- }
- $result.sources | Should -Match '(?m)^appBuild: default, derived from versioning strategy 2 \(UTC date\)\r?$'
- $result.sources | Should -Match '(?m)^appRevision: default, derived from versioning strategy 2 \(UTC time\)\r?$'
- }
-
- It 'Leaves explicit build and revision sources unchanged for versioning strategy -1' {
- $env:ALGoRepoSettings = '{"versioningStrategy":-1,"appBuild":7,"appRevision":9}'
- $result = & $invokeAction
-
- $result.settings.versioningStrategy | Should -Be -1
- $result.settings.appBuild | Should -Be 7
- $result.settings.appRevision | Should -Be 9
- $result.sources | Should -Match '(?m)^appBuild: settings ALGoRepoSettings \(Variable\)\r?$'
- $result.sources | Should -Match '(?m)^appRevision: settings ALGoRepoSettings \(Variable\)\r?$'
- }
-
- It 'Traces event-derived settings for ' -TestCases @(
- @{ eventName = 'pull_request' }
- @{ eventName = 'pull_request_target' }
- @{ eventName = 'merge_group' }
- ) {
- Param($eventName)
-
- $env:GITHUB_EVENT_NAME = $eventName
- $env:ALGoRepoSettings = '{"runNumberOffset":100,"versioningStrategy":-1,"doNotSignApps":false}'
- $result = & $invokeAction
-
- $result.settings.doNotSignApps | Should -BeTrue
- $result.settings.versioningStrategy | Should -Be 15
- $result.settings.appBuild | Should -Be ([int32]::MaxValue)
- $result.settings.appRevision | Should -Be 142
- foreach ($setting in @('doNotSignApps', 'versioningStrategy')) {
- $result.sources | Should -Match ('(?m)^' + $setting + ': settings ALGoRepoSettings \(Variable\), derived from GitHub pull request or merge group event\r?$')
- }
- $result.sources | Should -Match '(?m)^appBuild: default, derived from versioning strategy 15 \(maxValue\)\r?$'
- $result.sources | Should -Match '(?m)^appRevision: default, derived from versioning strategy 15 \(runNumberOffset and GITHUB_RUN_NUMBER\)\r?$'
- }
-
- It 'Traces strategy 15 derived from a maximum appBuild' {
- $env:ALGoRepoSettings = '{"runNumberOffset":100,"versioningStrategy":0,"appBuild":2147483647}'
- $result = & $invokeAction
-
- $result.settings.versioningStrategy | Should -Be 15
- $result.settings.appBuild | Should -Be ([int32]::MaxValue)
- $result.settings.appRevision | Should -Be 142
- $result.sources | Should -Match '(?m)^versioningStrategy: settings ALGoRepoSettings \(Variable\), derived from appBuild set to maxValue\r?$'
- $result.sources | Should -Match '(?m)^appBuild: settings ALGoRepoSettings \(Variable\), derived from versioning strategy 15 \(maxValue\)\r?$'
- $result.sources | Should -Match '(?m)^appRevision: default, derived from versioning strategy 15 \(runNumberOffset and GITHUB_RUN_NUMBER\)\r?$'
- }
-
- It 'Preserves earlier sources and protection flags when appending action derivations' {
- $env:GITHUB_EVENT_NAME = 'pull_request'
- $env:ALGoOrgSettings = '{"protectedSettings":["doNotSignApps","versioningStrategy","appBuild","appRevision"],"doNotSignApps":false,"versioningStrategy":-1,"appBuild":7,"appRevision":9}'
- $result = & $invokeAction
-
- $result.settings.doNotSignApps | Should -BeTrue
- $result.settings.versioningStrategy | Should -Be 15
- $result.settings.appBuild | Should -Be ([int32]::MaxValue)
- $result.settings.appRevision | Should -Be 142
- foreach ($setting in @('doNotSignApps', 'versioningStrategy')) {
- $result.sources | Should -Match ('(?m)^' + $setting + ': settings ALGoOrgSettings \(Variable\), derived from GitHub pull request or merge group event \(protected\)\r?$')
- }
- $result.sources | Should -Match '(?m)^appBuild: settings ALGoOrgSettings \(Variable\), derived from versioning strategy 15 \(maxValue\) \(protected\)\r?$'
- $result.sources | Should -Match '(?m)^appRevision: settings ALGoOrgSettings \(Variable\), derived from versioning strategy 15 \(runNumberOffset and GITHUB_RUN_NUMBER\) \(protected\)\r?$'
- }
- }
-}
+Get-Module TestActionsHelper | Remove-Module -Force
+Import-Module (Join-Path $PSScriptRoot 'TestActionsHelper.psm1')
+$errorActionPreference = "Stop"; $ProgressPreference = "SilentlyContinue"; Set-StrictMode -Version 2.0
+
+Describe "ReadSettings Action Tests" {
+ BeforeAll {
+ $actionName = "ReadSettings"
+ $scriptRoot = Join-Path $PSScriptRoot "..\Actions\$actionName" -Resolve
+ . (Join-Path $scriptRoot '..\AL-Go-Helper.ps1' -Resolve)
+ $scriptName = "$actionName.ps1"
+ [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', 'scriptPath', Justification = 'False positive.')]
+ $scriptPath = Join-Path $scriptRoot $scriptName
+ [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', 'actionScript', Justification = 'False positive.')]
+ $actionScript = GetActionScript -scriptRoot $scriptRoot -scriptName $scriptName
+ }
+
+ It 'Compile Action' {
+ Invoke-Expression $actionScript
+ }
+
+ It 'Test action.yaml matches script' {
+ $outputs = [ordered]@{
+ "GitHubRunnerJson" = "GitHubRunner in compressed Json format"
+ "GitHubRunnerShell" = "Shell for GitHubRunner jobs"
+ }
+ YamlTest -scriptRoot $scriptRoot -actionName $actionName -actionScript $actionScript -outputs $outputs
+ }
+
+ It 'Includes optional patterns in the Settings environment variable: ' -TestCases @(
+ @{ Patterns = '[]' }
+ @{ Patterns = '["*NextMinor*"]' }
+ @{ Patterns = '["*NextMinor*","*NextMajor*"]' }
+ @{ Patterns = '["Build * (NextMinor) / *"]' }
+ ) {
+ param($Patterns)
+ $originalEnvironment = @{}
+ foreach ($name in @('GITHUB_WORKSPACE', 'GITHUB_OUTPUT', 'GITHUB_ENV', 'GITHUB_RUN_NUMBER', 'GITHUB_RUN_ATTEMPT', 'GITHUB_EVENT_NAME', 'ALGoOrgSettings', 'ALGoRepoSettings', 'ALGoEnvSettings')) {
+ $originalEnvironment[$name] = [Environment]::GetEnvironmentVariable($name)
+ }
+ try {
+ $env:GITHUB_WORKSPACE = $TestDrive
+ $env:GITHUB_OUTPUT = Join-Path $TestDrive 'outputs.txt'
+ $env:GITHUB_ENV = Join-Path $TestDrive 'env.txt'
+ Set-Content -Path $env:GITHUB_OUTPUT -Value '' -Encoding UTF8
+ Set-Content -Path $env:GITHUB_ENV -Value '' -Encoding UTF8
+ $env:GITHUB_RUN_NUMBER = '1'
+ $env:GITHUB_RUN_ATTEMPT = '1'
+ $env:GITHUB_EVENT_NAME = 'pull_request'
+ $env:ALGoOrgSettings = ''
+ $env:ALGoEnvSettings = ''
+ $env:ALGoRepoSettings = "{`"optionalPatternsForPrValidation`":$Patterns}"
+ Mock Write-Host {}
+ & $scriptPath -workflowName '' -project ''
+ $settingsLine = Get-Content -Path $env:GITHUB_ENV -Encoding UTF8 |
+ Where-Object { $_ -like 'Settings=*' }
+ $exportedSettings = $settingsLine.Substring('Settings='.Length) | ConvertFrom-Json | ConvertTo-HashTable -recurse
+ (ConvertTo-Json -InputObject @($exportedSettings.optionalPatternsForPrValidation) -Compress) | Should -Be $Patterns
+ @(Get-Content -Path $env:GITHUB_ENV -Encoding UTF8 | Where-Object { $_ -like 'optionalPatternsForPrValidationJson=*' }).Count | Should -Be 0
+ Set-Content -Path $env:GITHUB_ENV -Value '' -Encoding UTF8
+ & $scriptPath -workflowName '' -project '' -get 'country,optionalPatternsForPrValidation'
+ $patternsArray = ($Patterns | ConvertFrom-Json)
+ Get-Content -Path $env:GITHUB_ENV -Encoding UTF8 | Should -Contain "optionalPatternsForPrValidation=$patternsArray"
+ Get-Content -Path $env:GITHUB_ENV -Encoding UTF8 | Should -Contain 'country=us'
+ @(Get-Content -Path $env:GITHUB_OUTPUT -Encoding UTF8 | Where-Object { $_ }).Count | Should -Be 4
+ }
+ finally {
+ foreach ($name in $originalEnvironment.Keys) {
+ [Environment]::SetEnvironmentVariable($name, $originalEnvironment[$name])
+ }
+ }
+ }
+
+ It 'Emits skipped settings and a single balanced sources group' {
+ $workspace = Join-Path ([System.IO.Path]::GetTempPath()) ([Guid]::NewGuid().ToString())
+ $originalEnvironment = @{}
+ foreach ($name in @('GITHUB_WORKSPACE', 'GITHUB_ENV', 'GITHUB_OUTPUT', 'GITHUB_RUN_NUMBER', 'GITHUB_RUN_ATTEMPT', 'GITHUB_EVENT_NAME', 'ALGoOrgSettings', 'ALGoRepoSettings', 'ALGoEnvSettings')) {
+ $originalEnvironment[$name] = [Environment]::GetEnvironmentVariable($name)
+ }
+
+ try {
+ New-Item -ItemType Directory -Path $workspace | Out-Null
+ $env:GITHUB_WORKSPACE = $workspace
+ $env:GITHUB_ENV = Join-Path $workspace 'github-env.txt'
+ $env:GITHUB_OUTPUT = Join-Path $workspace 'github-output.txt'
+ $env:GITHUB_RUN_NUMBER = '1'
+ $env:GITHUB_RUN_ATTEMPT = '1'
+ $env:GITHUB_EVENT_NAME = 'push'
+ $env:ALGoOrgSettings = '{"protectedSettings":["country"],"country":"de"}'
+ $env:ALGoRepoSettings = '{"country":"ch"}'
+ $env:ALGoEnvSettings = ''
+
+ $transcriptPath = Join-Path $workspace 'action-log.txt'
+ Start-Transcript -Path $transcriptPath -Force | Out-Null
+ try {
+ & $scriptPath -workflowName '' -project '' | Out-Null
+ }
+ finally {
+ Stop-Transcript | Out-Null
+ }
+ $output = Get-Content -Path $transcriptPath -Raw -Encoding UTF8
+ $notice = 'Skipped setting country from settings ALGoRepoSettings (Variable): protected by settings ALGoOrgSettings (Variable)'
+ $groupStart = [regex]::Matches($output, '(?m)(::group::Settings sources|==== Group start: Settings sources ====)')
+ $groupEnd = [regex]::Matches($output, '(?m)(::endgroup::|==== Group end ====)')
+
+ $output.Contains($notice) | Should -BeTrue
+ ([regex]::Matches($output, [regex]::Escape($notice))).Count | Should -Be 1
+ $groupStart.Count | Should -Be 1
+ $groupEnd.Count | Should -Be 1
+ $output.IndexOf($notice) | Should -BeLessThan $groupStart[0].Index
+ $groupEnd[0].Index | Should -BeGreaterThan $groupStart[0].Index
+ $sourcesGroup = $output.Substring($groupStart[0].Index, $groupEnd[0].Index - $groupStart[0].Index)
+ $sourcesGroup | Should -Match '(?m)^country: settings ALGoOrgSettings \(Variable\) \(protected\)\r?$'
+ $sourcesGroup | Should -Match '(?m)^shell: default, derived from runs-on\r?$'
+ $sourcesGroup | Should -Match '(?m)^alDoc\.includeProjects: default\r?$'
+ $sourcesGroup | Should -Match '(?m)^appBuild: default, derived from versioning strategy 0 \(runNumberOffset and GITHUB_RUN_NUMBER\)\r?$'
+ $sourcesGroup | Should -Match '(?m)^appRevision: default, derived from versioning strategy 0 \(GITHUB_RUN_ATTEMPT minus 1\)\r?$'
+ }
+ finally {
+ foreach ($name in $originalEnvironment.Keys) {
+ [Environment]::SetEnvironmentVariable($name, $originalEnvironment[$name])
+ }
+ Remove-Item -Path $workspace -Recurse -Force -ErrorAction SilentlyContinue
+ }
+ }
+
+ Context 'Action-level source derivations' {
+ BeforeAll {
+ $invokeAction = {
+ $transcriptPath = Join-Path $workspace 'action-log.txt'
+ $startedAt = [DateTime]::UtcNow
+ Start-Transcript -Path $transcriptPath -Force | Out-Null
+ try {
+ & $scriptPath -workflowName '' -project '' | Out-Null
+ }
+ finally {
+ Stop-Transcript | Out-Null
+ }
+ $finishedAt = [DateTime]::UtcNow
+ $output = Get-Content -Path $transcriptPath -Raw -Encoding UTF8
+ $groupStart = [regex]::Matches($output, '(?m)(::group::Settings sources|==== Group start: Settings sources ====)')
+ $groupEnd = [regex]::Matches($output, '(?m)(::endgroup::|==== Group end ====)')
+ $groupStart.Count | Should -Be 1
+ $groupEnd.Count | Should -Be 1
+ $groupEnd[0].Index | Should -BeGreaterThan $groupStart[0].Index
+ $settingsLine = Get-Content -Path $env:GITHUB_ENV -Encoding UTF8 | Where-Object { $_.StartsWith('Settings=') } | Select-Object -Last 1
+ @{
+ sources = $output.Substring($groupStart[0].Index, $groupEnd[0].Index - $groupStart[0].Index)
+ settings = $settingsLine.Substring('Settings='.Length) | ConvertFrom-Json | ConvertTo-HashTable -recurse
+ startedAt = $startedAt
+ finishedAt = $finishedAt
+ }
+ }
+ }
+
+ BeforeEach {
+ $workspace = Join-Path ([System.IO.Path]::GetTempPath()) ([Guid]::NewGuid().ToString())
+ $originalEnvironment = @{}
+ foreach ($name in @('GITHUB_WORKSPACE', 'GITHUB_ENV', 'GITHUB_OUTPUT', 'GITHUB_RUN_NUMBER', 'GITHUB_RUN_ATTEMPT', 'GITHUB_EVENT_NAME', 'ALGoOrgSettings', 'ALGoRepoSettings', 'ALGoEnvSettings')) {
+ $originalEnvironment[$name] = [Environment]::GetEnvironmentVariable($name)
+ }
+ New-Item -ItemType Directory -Path $workspace | Out-Null
+ $env:GITHUB_WORKSPACE = $workspace
+ $env:GITHUB_ENV = Join-Path $workspace 'github-env.txt'
+ $env:GITHUB_OUTPUT = Join-Path $workspace 'github-output.txt'
+ $env:GITHUB_RUN_NUMBER = '42'
+ $env:GITHUB_RUN_ATTEMPT = '3'
+ $env:GITHUB_EVENT_NAME = 'push'
+ $env:ALGoOrgSettings = ''
+ $env:ALGoRepoSettings = '{"runNumberOffset":100}'
+ $env:ALGoEnvSettings = ''
+ }
+
+ AfterEach {
+ foreach ($name in $originalEnvironment.Keys) {
+ [Environment]::SetEnvironmentVariable($name, $originalEnvironment[$name])
+ }
+ Remove-Item -Path $workspace -Recurse -Force -ErrorAction SilentlyContinue
+ }
+
+ It 'Traces and exports versioning strategy ' -TestCases @(
+ @{ strategy = 0; expectedBuild = 142; expectedRevision = 2; buildDerivation = 'runNumberOffset and GITHUB_RUN_NUMBER'; revisionDerivation = 'GITHUB_RUN_ATTEMPT minus 1' }
+ @{ strategy = 16; expectedBuild = 142; expectedRevision = 2; buildDerivation = 'runNumberOffset and GITHUB_RUN_NUMBER'; revisionDerivation = 'GITHUB_RUN_ATTEMPT minus 1' }
+ @{ strategy = 3; expectedBuild = -1; expectedRevision = 142; buildDerivation = 'use build from app.json'; revisionDerivation = 'runNumberOffset and GITHUB_RUN_NUMBER' }
+ @{ strategy = 15; expectedBuild = [int32]::MaxValue; expectedRevision = 142; buildDerivation = 'maxValue'; revisionDerivation = 'runNumberOffset and GITHUB_RUN_NUMBER' }
+ ) {
+ Param($strategy, $expectedBuild, $expectedRevision, $buildDerivation, $revisionDerivation)
+
+ $env:ALGoRepoSettings = @{ versioningStrategy = $strategy; runNumberOffset = 100 } | ConvertTo-Json
+ $result = & $invokeAction
+ $effectiveStrategy = $strategy -band 15
+
+ $result.settings.versioningStrategy | Should -Be $strategy
+ $result.settings.appBuild | Should -Be $expectedBuild
+ $result.settings.appRevision | Should -Be $expectedRevision
+ $result.sources | Should -Match ('(?m)^appBuild: ' + [regex]::Escape("default, derived from versioning strategy $effectiveStrategy ($buildDerivation)") + '\r?$')
+ $result.sources | Should -Match ('(?m)^appRevision: ' + [regex]::Escape("default, derived from versioning strategy $effectiveStrategy ($revisionDerivation)") + '\r?$')
+ $result.sources | Should -Match '(?m)^versioningStrategy: settings ALGoRepoSettings \(Variable\)\r?$'
+ $result.settings.doNotSignApps | Should -BeFalse
+ $result.sources | Should -Not -Match 'derived from GitHub pull request or merge group event'
+ }
+
+ It 'Traces UTC date and time for versioning strategy 2' {
+ $env:ALGoRepoSettings = '{"versioningStrategy":2}'
+ $result = & $invokeAction
+
+ $result.settings.versioningStrategy | Should -Be 2
+ @([int32]$result.startedAt.ToString('yyyyMMdd'), [int32]$result.finishedAt.ToString('yyyyMMdd')) | Should -Contain $result.settings.appBuild
+ $startTime = [int32]$result.startedAt.ToString('HHmmss')
+ $endTime = [int32]$result.finishedAt.ToString('HHmmss')
+ if ($result.startedAt.Date -eq $result.finishedAt.Date) {
+ ($result.settings.appRevision -ge $startTime -and $result.settings.appRevision -le $endTime) | Should -BeTrue
+ }
+ else {
+ ($result.settings.appRevision -ge $startTime -or $result.settings.appRevision -le $endTime) | Should -BeTrue
+ }
+ $result.sources | Should -Match '(?m)^appBuild: default, derived from versioning strategy 2 \(UTC date\)\r?$'
+ $result.sources | Should -Match '(?m)^appRevision: default, derived from versioning strategy 2 \(UTC time\)\r?$'
+ }
+
+ It 'Leaves explicit build and revision sources unchanged for versioning strategy -1' {
+ $env:ALGoRepoSettings = '{"versioningStrategy":-1,"appBuild":7,"appRevision":9}'
+ $result = & $invokeAction
+
+ $result.settings.versioningStrategy | Should -Be -1
+ $result.settings.appBuild | Should -Be 7
+ $result.settings.appRevision | Should -Be 9
+ $result.sources | Should -Match '(?m)^appBuild: settings ALGoRepoSettings \(Variable\)\r?$'
+ $result.sources | Should -Match '(?m)^appRevision: settings ALGoRepoSettings \(Variable\)\r?$'
+ }
+
+ It 'Traces event-derived settings for ' -TestCases @(
+ @{ eventName = 'pull_request' }
+ @{ eventName = 'pull_request_target' }
+ @{ eventName = 'merge_group' }
+ ) {
+ Param($eventName)
+
+ $env:GITHUB_EVENT_NAME = $eventName
+ $env:ALGoRepoSettings = '{"runNumberOffset":100,"versioningStrategy":-1,"doNotSignApps":false}'
+ $result = & $invokeAction
+
+ $result.settings.doNotSignApps | Should -BeTrue
+ $result.settings.versioningStrategy | Should -Be 15
+ $result.settings.appBuild | Should -Be ([int32]::MaxValue)
+ $result.settings.appRevision | Should -Be 142
+ foreach ($setting in @('doNotSignApps', 'versioningStrategy')) {
+ $result.sources | Should -Match ('(?m)^' + $setting + ': settings ALGoRepoSettings \(Variable\), derived from GitHub pull request or merge group event\r?$')
+ }
+ $result.sources | Should -Match '(?m)^appBuild: default, derived from versioning strategy 15 \(maxValue\)\r?$'
+ $result.sources | Should -Match '(?m)^appRevision: default, derived from versioning strategy 15 \(runNumberOffset and GITHUB_RUN_NUMBER\)\r?$'
+ }
+
+ It 'Traces strategy 15 derived from a maximum appBuild' {
+ $env:ALGoRepoSettings = '{"runNumberOffset":100,"versioningStrategy":0,"appBuild":2147483647}'
+ $result = & $invokeAction
+
+ $result.settings.versioningStrategy | Should -Be 15
+ $result.settings.appBuild | Should -Be ([int32]::MaxValue)
+ $result.settings.appRevision | Should -Be 142
+ $result.sources | Should -Match '(?m)^versioningStrategy: settings ALGoRepoSettings \(Variable\), derived from appBuild set to maxValue\r?$'
+ $result.sources | Should -Match '(?m)^appBuild: settings ALGoRepoSettings \(Variable\), derived from versioning strategy 15 \(maxValue\)\r?$'
+ $result.sources | Should -Match '(?m)^appRevision: default, derived from versioning strategy 15 \(runNumberOffset and GITHUB_RUN_NUMBER\)\r?$'
+ }
+
+ It 'Preserves earlier sources and protection flags when appending action derivations' {
+ $env:GITHUB_EVENT_NAME = 'pull_request'
+ $env:ALGoOrgSettings = '{"protectedSettings":["doNotSignApps","versioningStrategy","appBuild","appRevision"],"doNotSignApps":false,"versioningStrategy":-1,"appBuild":7,"appRevision":9}'
+ $result = & $invokeAction
+
+ $result.settings.doNotSignApps | Should -BeTrue
+ $result.settings.versioningStrategy | Should -Be 15
+ $result.settings.appBuild | Should -Be ([int32]::MaxValue)
+ $result.settings.appRevision | Should -Be 142
+ foreach ($setting in @('doNotSignApps', 'versioningStrategy')) {
+ $result.sources | Should -Match ('(?m)^' + $setting + ': settings ALGoOrgSettings \(Variable\), derived from GitHub pull request or merge group event \(protected\)\r?$')
+ }
+ $result.sources | Should -Match '(?m)^appBuild: settings ALGoOrgSettings \(Variable\), derived from versioning strategy 15 \(maxValue\) \(protected\)\r?$'
+ $result.sources | Should -Match '(?m)^appRevision: settings ALGoOrgSettings \(Variable\), derived from versioning strategy 15 \(runNumberOffset and GITHUB_RUN_NUMBER\) \(protected\)\r?$'
+ }
+ }
+}
diff --git a/Tests/ReadSettings.Test.ps1 b/Tests/ReadSettings.Test.ps1
index aba354d92..bc3716b65 100644
--- a/Tests/ReadSettings.Test.ps1
+++ b/Tests/ReadSettings.Test.ps1
@@ -27,6 +27,33 @@ InModuleScope ReadSettings { # Allows testing of private functions
$settingsSchema.properties.skipDraftPullRequests.default | Should -BeFalse
}
+ It 'Requires all PR build jobs by default and defines optional wildcard patterns as a string array' {
+ . (Join-Path $PSScriptRoot '../Actions/AL-Go-Helper.ps1')
+ $settings = GetDefaultSettings
+ $settings.optionalPatternsForPrValidation.Count | Should -Be 0
+ $settingsSchema = $schema | ConvertFrom-Json | ConvertTo-HashTable -recurse
+ $settingsSchema.properties.optionalPatternsForPrValidation.type | Should -Be 'array'
+ $settingsSchema.properties.optionalPatternsForPrValidation.items.type | Should -Be 'string'
+ $settingsSchema.properties.optionalPatternsForPrValidation.default.Count | Should -Be 0
+ }
+
+ It 'Merges optional patterns from variables and matching conditional settings' {
+ $settings = ReadSettings -baseFolder $TestDrive -repoName 'owner/repo' -project '' `
+ -workflowName 'Pull Request Build' -trigger 'pull_request' `
+ -orgSettingsVariableValue '{"optionalPatternsForPrValidation":["*NextMinor*"]}' `
+ -repoSettingsVariableValue '{"optionalPatternsForPrValidation":["*NextMajor*"],"ConditionalSettings":[{"triggers":["pull_request"],"settings":{"optionalPatternsForPrValidation":["*Preview*"]}}]}' `
+ -environmentSettingsVariableValue ''
+ $settings.optionalPatternsForPrValidation | Should -Be @('*NextMinor*', '*NextMajor*', '*Preview*')
+ }
+
+ It 'Supports overwriting optional patterns with an empty array' {
+ $settings = ReadSettings -baseFolder $TestDrive -repoName 'owner/repo' -project '' `
+ -workflowName '' -orgSettingsVariableValue '{"optionalPatternsForPrValidation":["*NextMinor*"]}' `
+ -repoSettingsVariableValue '{"overwriteSettings":["optionalPatternsForPrValidation"],"optionalPatternsForPrValidation":[]}' `
+ -environmentSettingsVariableValue ''
+ $settings.optionalPatternsForPrValidation.Count | Should -Be 0
+ }
+
It 'Reads settings from all settings locations' {
Mock Write-Host { }
Mock Out-Host { }