From 1c663006983f4d54e635af52eec2dcb4af3aa664 Mon Sep 17 00:00:00 2001 From: Maria Zhelezova <43066499+mazhelez@users.noreply.github.com> Date: Fri, 13 Nov 2026 13:55:35 +0100 Subject: [PATCH 1/6] Reference repository actions locally instead of @main Replace 'microsoft/BCApps/.github/actions/@main' with local './.github/actions/' references so the action code matches the workflow's commit. Jobs without a checkout get one; jobs that check out another branch (matrix.branch) sparse-check out the workflow's own commit into '_actions' and reference the action from there. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../RunAutomation/HowToAddAnAutomation.md | 18 +++++++++++++++--- .github/workflows/SubmitStabilityJobs.yaml | 10 ++++++++-- .github/workflows/UpdateALGoProjects.yaml | 15 +++++++++++++-- .github/workflows/UpdateBCArtifactVersion.yaml | 15 +++++++++++++-- .github/workflows/UpdatePackageVersions.yaml | 15 +++++++++++++-- .github/workflows/VerifyAppChanges.yaml | 4 ++-- 6 files changed, 64 insertions(+), 13 deletions(-) diff --git a/.github/actions/RunAutomation/HowToAddAnAutomation.md b/.github/actions/RunAutomation/HowToAddAnAutomation.md index 750dd40258f..e2986b53995 100644 --- a/.github/actions/RunAutomation/HowToAddAnAutomation.md +++ b/.github/actions/RunAutomation/HowToAddAnAutomation.md @@ -9,6 +9,7 @@ - `Files`: Files changed by the automation that will be included in the pull request. - `Message`: Message to display as an automaton result and use as commit message and pull request description. 3. Create a new workflow in `.github\workflows` to run your new automation. + - Reference the actions in this repository locally (`./...`) rather than as `microsoft/BCApps/...@main`, so the action code always matches the workflow's commit. Local actions require the repository to be checked out first. When the job checks out another branch (e.g. `${{ matrix.branch }}`), check out the workflow's own commit into `_actions` and reference the action from there. - Add a job to run the script: ```yaml AutomationJob: @@ -23,12 +24,20 @@ fail-fast: false steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@ # with: ref: ${{ matrix.branch }} + - name: Checkout actions + uses: actions/checkout@ # + with: + path: _actions + sparse-checkout: | + .github/actions + build/scripts + - name: - uses: microsoft/BCApps/.github/actions/RunAutomation@main + uses: ./_actions/.github/actions/RunAutomation with: automations: targetBranch: ${{ matrix.branch }} @@ -41,9 +50,12 @@ outputs: updateBranches: ${{ steps.getOfficialBranches.outputs.branchesJson }} steps: + - name: Checkout + uses: actions/checkout@ # + - name: Get Official Branches id: getOfficialBranches - uses: mazhelez/BCApps/.github/actions/GetGitBranches@main + uses: ./.github/actions/GetGitBranches with: include: "['main', 'releases/*']" ``` diff --git a/.github/workflows/SubmitStabilityJobs.yaml b/.github/workflows/SubmitStabilityJobs.yaml index 14239e98b74..4093493e11f 100644 --- a/.github/workflows/SubmitStabilityJobs.yaml +++ b/.github/workflows/SubmitStabilityJobs.yaml @@ -15,9 +15,12 @@ jobs: outputs: officialBranches: ${{ steps.getOfficialBranches.outputs.branchesJson }} steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - name: Get Official Branches id: getOfficialBranches - uses: microsoft/BCApps/.github/actions/GetGitBranches@main + uses: ./.github/actions/GetGitBranches with: include: "['releases/*']" @@ -38,10 +41,13 @@ jobs: app-id: ${{ vars.APP_ID }} private-key: ${{ secrets.PRIVATE_KEY }} + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - name: Submit Stability Job env: GH_TOKEN: ${{ steps.app-token.outputs.token }} - uses: microsoft/BCApps/.github/actions/RunAutomation@main + uses: ./.github/actions/RunAutomation with: automations: SubmitStabilityJob targetBranch: ${{ matrix.branch }} diff --git a/.github/workflows/UpdateALGoProjects.yaml b/.github/workflows/UpdateALGoProjects.yaml index 1fb06332fc2..4bedcbbee41 100644 --- a/.github/workflows/UpdateALGoProjects.yaml +++ b/.github/workflows/UpdateALGoProjects.yaml @@ -24,9 +24,12 @@ jobs: with: egress-policy: audit + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - name: Get Official Branches id: getOfficialBranches - uses: microsoft/BCApps/.github/actions/GetGitBranches@main + uses: ./.github/actions/GetGitBranches with: include: "['main', 'releases/*']" @@ -54,10 +57,18 @@ jobs: app-id: ${{ vars.APP_ID }} private-key: ${{ secrets.PRIVATE_KEY }} + - name: Checkout actions + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + path: _actions + sparse-checkout: | + .github/actions + build/scripts + - name: Update AL-Go Project Dependencies env: GH_TOKEN: ${{ steps.app-token.outputs.token }} - uses: microsoft/BCApps/.github/actions/RunAutomation@main + uses: ./_actions/.github/actions/RunAutomation with: automations: UpdateUseProjectDependencies targetBranch: ${{ matrix.branch }} diff --git a/.github/workflows/UpdateBCArtifactVersion.yaml b/.github/workflows/UpdateBCArtifactVersion.yaml index 2eb6339fb63..0c9ae10d549 100644 --- a/.github/workflows/UpdateBCArtifactVersion.yaml +++ b/.github/workflows/UpdateBCArtifactVersion.yaml @@ -24,9 +24,12 @@ jobs: with: egress-policy: audit + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - name: Get Official Branches id: getOfficialBranches - uses: microsoft/BCApps/.github/actions/GetGitBranches@main + uses: ./.github/actions/GetGitBranches with: include: "['main', 'releases/*']" @@ -54,10 +57,18 @@ jobs: app-id: ${{ vars.APP_ID }} private-key: ${{ secrets.PRIVATE_KEY }} + - name: Checkout actions + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + path: _actions + sparse-checkout: | + .github/actions + build/scripts + - name: Update BC Artifact Version env: GH_TOKEN: ${{ steps.app-token.outputs.token }} - uses: microsoft/BCApps/.github/actions/RunAutomation@main + uses: ./_actions/.github/actions/RunAutomation with: automations: UpdateBCArtifact diff --git a/.github/workflows/UpdatePackageVersions.yaml b/.github/workflows/UpdatePackageVersions.yaml index a9b54787f40..39045bf08c8 100644 --- a/.github/workflows/UpdatePackageVersions.yaml +++ b/.github/workflows/UpdatePackageVersions.yaml @@ -24,9 +24,12 @@ jobs: with: egress-policy: audit + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - name: Get Official Branches id: getOfficialBranches - uses: microsoft/BCApps/.github/actions/GetGitBranches@main + uses: ./.github/actions/GetGitBranches with: include: "['main', 'releases/*']" @@ -54,10 +57,18 @@ jobs: app-id: ${{ vars.APP_ID }} private-key: ${{ secrets.PRIVATE_KEY }} + - name: Checkout actions + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + path: _actions + sparse-checkout: | + .github/actions + build/scripts + - name: Update Package Versions env: GH_TOKEN: ${{ steps.app-token.outputs.token }} - uses: microsoft/BCApps/.github/actions/RunAutomation@main + uses: ./_actions/.github/actions/RunAutomation with: automations: UpdateAppBaselines,UpdateAppTranslations targetBranch: ${{ matrix.branch }} \ No newline at end of file diff --git a/.github/workflows/VerifyAppChanges.yaml b/.github/workflows/VerifyAppChanges.yaml index 213d1df218f..69ab1b320e6 100644 --- a/.github/workflows/VerifyAppChanges.yaml +++ b/.github/workflows/VerifyAppChanges.yaml @@ -22,6 +22,6 @@ jobs: ref: ${{ github.sha }} fetch-depth: 0 - - uses: microsoft/BCApps/.github/actions/TestPreprocessorSymbols@main + - uses: ./.github/actions/TestPreprocessorSymbols - - uses: microsoft/BCApps/.github/actions/TestObjectIdsAndManifests@main + - uses: ./.github/actions/TestObjectIdsAndManifests From bbcbe3f7f77fa0641d30f47af995dd323857478e Mon Sep 17 00:00:00 2001 From: Maria Zhelezova <43066499+mazhelez@users.noreply.github.com> Date: Fri, 13 Nov 2026 14:57:06 +0100 Subject: [PATCH 2/6] Sync repository actions and their script dependencies with main Make the code of all repository actions (.github/actions) identical to main so every in-support branch runs the same action versions. Actions import PowerShell modules from build/scripts, so the dependencies needed by the actions are brought in line with main as well: - Modules only consumed by actions are synced as whole files (AutomatedSubmission, AppObjectValidation, BuildOptimization, TestPreprocessorSymbols, PlatformHelper, their tests, and Miapp where VerifyMiappSync is used). - EnlistmentHelperFunctions.psm1 is shared with the build, so only the functions required by the actions are taken from main (Get-PackageLatestVersion, Get-LatestBCArtifactUrl, Update-BCArtifactVersion, Update-PackageVersion, Test-IsBranchInSupport). Build-facing functions are left unchanged. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../actions/CleanUpStalePRChecks/action.ps1 | 16 +- .github/actions/GetGitBranches/action.yaml | 2 +- .../LabelPRsAwaitingApproval/action.ps1 | 216 ++++++++ .../LabelPRsAwaitingApproval/action.yaml | 34 ++ .../RunAutomation/HowToAddAnAutomation.md | 3 + .../RunAutomation/SubmitStabilityJob/run.ps1 | 6 +- .../RunAutomation/UpdateAppBaselines/run.ps1 | 2 +- .../UpdatePlatformVersion/run.ps1 | 29 + .../UpdateSystemFilesSchedule/run.ps1 | 93 ++++ .github/actions/RunAutomation/run.ps1 | 11 +- .../TestObjectIdsAndManifests/action.ps1 | 157 +++++- .../TestObsoleteTagPreprocessors/action.ps1 | 34 ++ .../TestObsoleteTagPreprocessors/action.yaml | 13 + .../actions/UpdateUnstableTests/action.ps1 | 51 ++ .../actions/UpdateUnstableTests/action.yaml | 49 ++ .../UpdateUnstableTestsCombined/action.ps1 | 81 +++ .../UpdateUnstableTestsCombined/action.yaml | 68 +++ .../ValidateCountryProjects/action.ps1 | 6 + .../ValidateCountryProjects/action.yaml | 13 + .github/actions/VerifyMiappSync/action.ps1 | 5 + .github/actions/VerifyMiappSync/action.yaml | 13 + build/scripts/AppObjectValidation.psm1 | 267 +++++++++- build/scripts/AutomatedSubmission.psm1 | 9 +- build/scripts/BuildOptimization.psm1 | 503 ++++++++++++++++++ build/scripts/EnlistmentHelperFunctions.psm1 | 47 +- build/scripts/PlatformHelper.psm1 | 179 +++++++ .../tests/AppObjectValidation.Test.ps1 | 284 ++++++++++ build/scripts/tests/PlatformHelper.Test.ps1 | 138 +++++ 28 files changed, 2281 insertions(+), 48 deletions(-) create mode 100644 .github/actions/LabelPRsAwaitingApproval/action.ps1 create mode 100644 .github/actions/LabelPRsAwaitingApproval/action.yaml create mode 100644 .github/actions/RunAutomation/UpdatePlatformVersion/run.ps1 create mode 100644 .github/actions/RunAutomation/UpdateSystemFilesSchedule/run.ps1 create mode 100644 .github/actions/TestObsoleteTagPreprocessors/action.ps1 create mode 100644 .github/actions/TestObsoleteTagPreprocessors/action.yaml create mode 100644 .github/actions/UpdateUnstableTests/action.ps1 create mode 100644 .github/actions/UpdateUnstableTests/action.yaml create mode 100644 .github/actions/UpdateUnstableTestsCombined/action.ps1 create mode 100644 .github/actions/UpdateUnstableTestsCombined/action.yaml create mode 100644 .github/actions/ValidateCountryProjects/action.ps1 create mode 100644 .github/actions/ValidateCountryProjects/action.yaml create mode 100644 .github/actions/VerifyMiappSync/action.ps1 create mode 100644 .github/actions/VerifyMiappSync/action.yaml create mode 100644 build/scripts/BuildOptimization.psm1 create mode 100644 build/scripts/PlatformHelper.psm1 create mode 100644 build/scripts/tests/AppObjectValidation.Test.ps1 create mode 100644 build/scripts/tests/PlatformHelper.Test.ps1 diff --git a/.github/actions/CleanUpStalePRChecks/action.ps1 b/.github/actions/CleanUpStalePRChecks/action.ps1 index 32787096001..b830dfc93c3 100644 --- a/.github/actions/CleanUpStalePRChecks/action.ps1 +++ b/.github/actions/CleanUpStalePRChecks/action.ps1 @@ -21,7 +21,7 @@ if ($WhatIf) { Write-Host "Fetching open pull requests..." # Get all open pull requests with mergeable state -$prs = gh pr list --state open --json number,title,url,mergeable --limit 1000 | ConvertFrom-Json +$prs = @(gh pr list --state open --json number,title,url,mergeable --limit 1000 | ConvertFrom-Json) Write-Host "Found $($prs.Count) open pull requests" @@ -32,15 +32,18 @@ if ($prs.Count -eq 0) { $now = [DateTime]::UtcNow $restarted = 0 +$skipped = 0 $failed = 0 foreach ($pr in $prs) { Write-Host "" Write-Host "Checking PR #$($pr.number): $($pr.title)" - # Check if PR is mergeable - if ($pr.mergeable -ne "MERGEABLE") { - Write-Host " PR is not in MERGEABLE state (current: $($pr.mergeable)), skipping" + # Skip PRs with merge conflicts - they need manual resolution first + # Process PRs in MERGEABLE and UNKNOWN states (UNKNOWN means GitHub hasn't computed mergeability yet) + if ($pr.mergeable -eq "CONFLICTING") { + Write-Host " PR has merge conflicts (state: CONFLICTING), skipping" + $skipped++ continue } @@ -62,6 +65,7 @@ foreach ($pr in $prs) { if (-not $statusCheck) { Write-Host " No 'Pull Request Status Check' found for this PR" + $skipped++ continue } @@ -70,6 +74,7 @@ foreach ($pr in $prs) { # Check if the check is completed and successful if ($statusCheck.state -ne "SUCCESS") { Write-Host " Check state is '$($statusCheck.state)', not 'SUCCESS', skipping" + $skipped++ continue } @@ -154,6 +159,7 @@ This will automatically trigger a new **Pull Request Build** workflow run. Write-Host "" Write-Host "Summary:" Write-Host " ✓ Successfully processed: $restarted PR(s)" +Write-Host " ↷ Skipped: $skipped PR(s)" Write-Host " ✗ Failed to process: $failed PR(s)" # Add GitHub Actions job summary @@ -169,6 +175,7 @@ if ($env:GITHUB_STEP_SUMMARY) { else { Add-Content -Path $env:GITHUB_STEP_SUMMARY -Value "- ✓ Successfully processed: **$restarted** PR(s) (deleted stale workflow runs and added comments)" } + Add-Content -Path $env:GITHUB_STEP_SUMMARY -Value "- ↷ Skipped: **$skipped** PR(s) (non-mergeable, no status check, or check not successful)" Add-Content -Path $env:GITHUB_STEP_SUMMARY -Value "- ✗ Failed to process: **$failed** PR(s)" } @@ -177,3 +184,4 @@ if ($failed -gt 0 -and -not $WhatIf) { Write-Host "::error::Failed to process $failed PR(s)" exit 1 } +exit 0 diff --git a/.github/actions/GetGitBranches/action.yaml b/.github/actions/GetGitBranches/action.yaml index e5476da0c40..36c520c58eb 100644 --- a/.github/actions/GetGitBranches/action.yaml +++ b/.github/actions/GetGitBranches/action.yaml @@ -18,7 +18,7 @@ runs: using: composite steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - name: run shell: pwsh diff --git a/.github/actions/LabelPRsAwaitingApproval/action.ps1 b/.github/actions/LabelPRsAwaitingApproval/action.ps1 new file mode 100644 index 00000000000..d6e7ef94ae6 --- /dev/null +++ b/.github/actions/LabelPRsAwaitingApproval/action.ps1 @@ -0,0 +1,216 @@ +param ( + [Parameter(Mandatory = $false, HelpMessage = "Label to manage on PRs awaiting workflow approval")] + [string] $Label = 'needs-approval', + [Parameter(Mandatory = $false, HelpMessage = "Dry-run mode - log changes without applying them")] + [switch] $WhatIf +) + +$ErrorActionPreference = "Stop" +$ProgressPreference = "SilentlyContinue" +Set-StrictMode -Version 2.0 + +$repo = $env:GITHUB_REPOSITORY +if (-not $repo) { + throw "GITHUB_REPOSITORY environment variable is not set" +} + +if ($WhatIf) { + Write-Host "::notice::Running in WhatIf mode - no label changes will be applied" +} + +function Invoke-GhApi { + param ( + [Parameter(Mandatory = $true)] [string[]] $Arguments, + [int] $MaxRetries = 3 + ) + for ($attempt = 1; $attempt -le $MaxRetries; $attempt++) { + $stderrFile = [System.IO.Path]::GetTempFileName() + try { + # Redirect stderr to a temp file so deprecation notices / warnings + # don't get prepended to stdout and break ConvertFrom-Json. + $stdout = & gh api @Arguments 2>$stderrFile + if ($LASTEXITCODE -eq 0) { + $stderrText = Get-Content -Path $stderrFile -Raw -ErrorAction SilentlyContinue + if ($stderrText -and $stderrText.Trim()) { + Write-Host " gh api stderr: $($stderrText.Trim())" + } + return $stdout + } + $stderrText = Get-Content -Path $stderrFile -Raw -ErrorAction SilentlyContinue + throw "gh api failed (exit $LASTEXITCODE): $stderrText" + } + catch { + if ($attempt -eq $MaxRetries) { throw } + Start-Sleep -Seconds ([Math]::Pow(2, $attempt)) + } + finally { + Remove-Item -Path $stderrFile -ErrorAction SilentlyContinue + } + } +} + +function Ensure-Label { + param ([string] $Name) + $stderrFile = [System.IO.Path]::GetTempFileName() + try { + & gh api "repos/$repo/labels/$([Uri]::EscapeDataString($Name))" 2>$stderrFile | Out-Null + if ($LASTEXITCODE -eq 0) { + Write-Host "Label '$Name' exists" + return + } + $errText = Get-Content -Path $stderrFile -Raw -ErrorAction SilentlyContinue + # Only treat genuine "not found" responses as a signal to create the + # label. Other failures (rate limiting, 5xx, network) should bubble + # up so they're not masked as a missing-label condition. + if ($errText -notmatch 'HTTP 404|Not Found') { + throw "Unexpected error checking label '$Name' (exit $LASTEXITCODE): $errText" + } + Write-Host "Label '$Name' not found - creating it" + if ($WhatIf) { + Write-Host " [WhatIf] Would create label '$Name'" + return + } + & gh label create $Name --repo $repo --color 'FBCA04' --description 'Workflow runs require maintainer approval to start' 2>&1 | Out-Null + if ($LASTEXITCODE -ne 0) { + throw "Failed to create label '$Name'" + } + } + finally { + Remove-Item -Path $stderrFile -ErrorAction SilentlyContinue + } +} + +function Get-AwaitingApprovalPRs { + Write-Host "" + Write-Host "Fetching open PRs in $repo (for head-SHA mapping)..." + # With --paginate, gh runs the --jq filter against each page and emits the + # results concatenated. We use a filter that emits one JSON object per + # line, and parse them individually below (NDJSON style) - this avoids + # the "multiple JSON arrays concatenated" problem that breaks + # ConvertFrom-Json. + $prsJson = Invoke-GhApi -Arguments @('--paginate', "repos/$repo/pulls?state=open&per_page=100", '--jq', '.[] | {number: .number, sha: .head.sha}') + $openPRs = @($prsJson | Where-Object { $_ -and $_.ToString().Trim() } | ForEach-Object { $_ | ConvertFrom-Json }) + Write-Host "Found $($openPRs.Count) open PR(s)" + + # Map of current PR head SHA -> list of PR numbers. We match action_required + # runs against the *current* head only, so PRs with stale action_required + # runs from older commits (whose newer commits have been approved) are not + # falsely flagged. A list (rather than a single PR) handles the edge case + # where multiple open PRs share the same head SHA (e.g. one PR per base + # branch from a single commit). + $headShaToPRs = @{} + foreach ($pr in $openPRs) { + if ($pr.sha) { + if (-not $headShaToPRs.ContainsKey($pr.sha)) { + $headShaToPRs[$pr.sha] = [System.Collections.Generic.List[int]]::new() + } + $headShaToPRs[$pr.sha].Add([int]$pr.number) + } + } + + Write-Host "" + Write-Host "Fetching workflow runs with status=action_required..." + $runsJson = Invoke-GhApi -Arguments @('--paginate', "repos/$repo/actions/runs?status=action_required&per_page=100", '--jq', '.workflow_runs[]') + $runs = @($runsJson | Where-Object { $_ -and $_.ToString().Trim() } | ForEach-Object { $_ | ConvertFrom-Json }) + Write-Host "Found $($runs.Count) action_required workflow run(s)" + + $awaiting = [System.Collections.Generic.HashSet[int]]::new() + foreach ($run in $runs) { + if (($run.PSObject.Properties.Name -contains 'head_sha') -and $run.head_sha -and $headShaToPRs.ContainsKey($run.head_sha)) { + foreach ($prNum in $headShaToPRs[$run.head_sha]) { + [void]$awaiting.Add($prNum) + } + } + } + + # Comma prevents PowerShell from unrolling the HashSet (which would + # turn an empty set into $null at the call site). + return ,$awaiting +} + +function Get-LabeledPRs { + param ([string] $LabelName) + Write-Host "" + Write-Host "Fetching open PRs currently labelled '$LabelName'..." + $encoded = [Uri]::EscapeDataString($LabelName) + $json = Invoke-GhApi -Arguments @('--paginate', "repos/$repo/issues?state=open&labels=$encoded&per_page=100", '--jq', '.[] | select(.pull_request) | .number') + $set = [System.Collections.Generic.HashSet[int]]::new() + foreach ($n in @($json | Where-Object { $_ -and $_.ToString().Trim() -match '^\d+$' })) { + [void]$set.Add([int]$n) + } + Write-Host "Found $($set.Count) PR(s) with label '$LabelName'" + return ,$set +} + +# --- Main --- + +Ensure-Label -Name $Label +$awaitingPRs = Get-AwaitingApprovalPRs +$labeledPRs = Get-LabeledPRs -LabelName $Label + +if ($awaitingPRs.Count -gt 0) { + Write-Host "" + Write-Host "PRs awaiting approval:" + $awaitingPRs | Sort-Object | ForEach-Object { Write-Host " - #$_" } +} + +$toAdd = @($awaitingPRs | Where-Object { -not $labeledPRs.Contains($_) } | Sort-Object) +$toRemove = @($labeledPRs | Where-Object { -not $awaitingPRs.Contains($_) } | Sort-Object) + +Write-Host "" +Write-Host "Plan: add '$Label' to $($toAdd.Count) PR(s), remove from $($toRemove.Count) PR(s)" + +$added = 0; $removed = 0; $failed = 0 + +foreach ($pr in $toAdd) { + Write-Host " + Add '$Label' to PR #$pr" + if ($WhatIf) { $added++; continue } + try { + & gh pr edit $pr --repo $repo --add-label $Label 2>&1 | Out-Null + if ($LASTEXITCODE -ne 0) { throw "gh pr edit exited with $LASTEXITCODE" } + $added++ + } + catch { + Write-Host " ::warning::Failed to add label to PR #${pr}: $_" + $failed++ + } +} + +foreach ($pr in $toRemove) { + Write-Host " - Remove '$Label' from PR #$pr" + if ($WhatIf) { $removed++; continue } + try { + & gh pr edit $pr --repo $repo --remove-label $Label 2>&1 | Out-Null + if ($LASTEXITCODE -ne 0) { throw "gh pr edit exited with $LASTEXITCODE" } + $removed++ + } + catch { + Write-Host " ::warning::Failed to remove label from PR #${pr}: $_" + $failed++ + } +} + +Write-Host "" +Write-Host "Summary:" +Write-Host " PRs awaiting approval: $($awaitingPRs.Count)" +Write-Host " Labels added: $added" +Write-Host " Labels removed: $removed" +Write-Host " Failures: $failed" + +if ($env:GITHUB_STEP_SUMMARY) { + $title = if ($WhatIf) { "## PRs Awaiting Approval - Label Sync (WhatIf)" } else { "## PRs Awaiting Approval - Label Sync" } + Add-Content -Path $env:GITHUB_STEP_SUMMARY -Value $title + Add-Content -Path $env:GITHUB_STEP_SUMMARY -Value "" + Add-Content -Path $env:GITHUB_STEP_SUMMARY -Value "- Label: ``$Label``" + Add-Content -Path $env:GITHUB_STEP_SUMMARY -Value "- PRs awaiting approval: **$($awaitingPRs.Count)**" + Add-Content -Path $env:GITHUB_STEP_SUMMARY -Value "- Labels added: **$added**" + Add-Content -Path $env:GITHUB_STEP_SUMMARY -Value "- Labels removed: **$removed**" + if ($failed -gt 0) { + Add-Content -Path $env:GITHUB_STEP_SUMMARY -Value "- Failures: **$failed**" + } +} + +if ($failed -gt 0 -and -not $WhatIf) { + Write-Host "::error::Encountered $failed label operation failure(s)" + exit 1 +} diff --git a/.github/actions/LabelPRsAwaitingApproval/action.yaml b/.github/actions/LabelPRsAwaitingApproval/action.yaml new file mode 100644 index 00000000000..0489b3becb5 --- /dev/null +++ b/.github/actions/LabelPRsAwaitingApproval/action.yaml @@ -0,0 +1,34 @@ +name: Label PRs Awaiting Workflow Approval +author: Microsoft Corporation +description: Adds or removes a label on open PRs based on whether they have workflow runs in the 'action_required' state (waiting for maintainer approval). +inputs: + token: + description: The GitHub token running the action + required: false + default: ${{ github.token }} + label: + description: The label to add to PRs that have workflow runs awaiting approval + required: false + default: 'needs-approval' + whatIf: + description: If 'true', logs intended changes without applying them + required: false + default: 'false' +runs: + using: composite + steps: + - name: Sync 'needs-approval' label + shell: pwsh + env: + GH_TOKEN: ${{ inputs.token }} + GITHUB_REPOSITORY: ${{ github.repository }} + ACTION_LABEL: ${{ inputs.label }} + ACTION_WHATIF: ${{ inputs.whatIf }} + ACTION_PATH: ${{ github.action_path }} + run: | + $whatIfSwitch = @{} + if ($env:ACTION_WHATIF -eq 'true') { $whatIfSwitch['WhatIf'] = $true } + & "$env:ACTION_PATH/action.ps1" -Label $env:ACTION_LABEL @whatIfSwitch +branding: + icon: tag + color: yellow diff --git a/.github/actions/RunAutomation/HowToAddAnAutomation.md b/.github/actions/RunAutomation/HowToAddAnAutomation.md index e2986b53995..48a00fdcead 100644 --- a/.github/actions/RunAutomation/HowToAddAnAutomation.md +++ b/.github/actions/RunAutomation/HowToAddAnAutomation.md @@ -1,5 +1,8 @@ # How to add a new automation +> [!NOTE] +> Automations run through `RunAutomation` are automatically skipped on branches that are out of support (branches with the "Branch is out of support" ruleset). No pull request is created for those branches, so you don't need to handle this in your automation. + 1. Create a folder in `.github\actions\RunAutomations`. The name of the folder is the name of the automation, e.g. "_UpdateAppBaselines_". 2. Create a `run.ps1` file in the new folder. It should contain the script with the automation's logic. - The script can accept the following parameters: diff --git a/.github/actions/RunAutomation/SubmitStabilityJob/run.ps1 b/.github/actions/RunAutomation/SubmitStabilityJob/run.ps1 index 63d999dd75f..76022e2e8b1 100644 --- a/.github/actions/RunAutomation/SubmitStabilityJob/run.ps1 +++ b/.github/actions/RunAutomation/SubmitStabilityJob/run.ps1 @@ -5,11 +5,11 @@ param ( $repository = $runParameters.Repository $targetBranch = $runParameters.TargetBranch -$workflowName = " CI/CD" +$workflowName = "CICD.yaml" $workflowRunTime = Get-Date -AsUTC Write-Host "Running the workflow '$workflowName' on branch $targetBranch" -gh workflow run --repo $repository --ref $targetBranch $workflowName +gh workflow run --repo $repository --ref $targetBranch $workflowName | Out-Null # Get the workflow run URL to display in the message @@ -32,4 +32,4 @@ if ($workflowRun.createdAt -gt $workflowRunTime) { $result.Message = "'$workflowName' workflow started: $($workflowRun.url)" } -return $result \ No newline at end of file +return $result diff --git a/.github/actions/RunAutomation/UpdateAppBaselines/run.ps1 b/.github/actions/RunAutomation/UpdateAppBaselines/run.ps1 index 39e3c49bd6b..14880646dfa 100644 --- a/.github/actions/RunAutomation/UpdateAppBaselines/run.ps1 +++ b/.github/actions/RunAutomation/UpdateAppBaselines/run.ps1 @@ -9,7 +9,7 @@ Install-Module -Name BcContainerHelper -AllowPrerelease -Force Import-Module BcContainerHelper -DisableNameChecking Import-Module $PSScriptRoot\..\..\..\..\build\scripts\EnlistmentHelperFunctions.psm1 -$newVersion = Update-PackageVersion -PackageName "AppBaselines-BCArtifacts" +$newVersion = Update-PackageVersion -PackageName "AppBaselines-BCArtifacts" -Branch $runParameters.TargetBranch $result = @{ 'Files' = @() diff --git a/.github/actions/RunAutomation/UpdatePlatformVersion/run.ps1 b/.github/actions/RunAutomation/UpdatePlatformVersion/run.ps1 new file mode 100644 index 00000000000..ea45b3e8bb3 --- /dev/null +++ b/.github/actions/RunAutomation/UpdatePlatformVersion/run.ps1 @@ -0,0 +1,29 @@ +[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', 'runParameters', Justification = 'The parameter is always passed to the script')] +param ( + [Parameter(Mandatory=$true)] + $runParameters +) + +Import-Module $PSScriptRoot\..\..\..\..\build\scripts\EnlistmentHelperFunctions.psm1 + +$result = @{ + 'Files' = @() + 'Message' = "No update available" +} + +# Defensively check whether the BCPlatform package is tracked in the Packages config. +# Some (older) release branches do not track the BCPlatform package, in which case there is nothing to update. +$platformPackage = Get-ConfigValue -Key "BCPlatform" -ConfigType Packages +if (-not $platformPackage) { + Write-Host "BCPlatform package is not present in the Packages config. Skipping update." + return $result +} + +$newVersion = Update-PackageVersion -PackageName "BCPlatform" + +if ($newVersion) { + $result.Files = @(Get-PackagesFilePath -Relative) + $result.Message = "Update platform version. New value: $newVersion" +} + +return $result diff --git a/.github/actions/RunAutomation/UpdateSystemFilesSchedule/run.ps1 b/.github/actions/RunAutomation/UpdateSystemFilesSchedule/run.ps1 new file mode 100644 index 00000000000..32e716eeac8 --- /dev/null +++ b/.github/actions/RunAutomation/UpdateSystemFilesSchedule/run.ps1 @@ -0,0 +1,93 @@ +<# +.Synopsis + Updates the branch list of the "Update AL-Go System Files" scheduled run so it only targets supported branches. +.Description + The "Update AL-Go System Files" workflow (UpdateGitHubGoSystemFiles.yaml) is an AL-Go system file and + picks the branches to run on from the 'workflowSchedule.includeBranches' setting in + '.github/Update AL-Go System Files.settings.json'. Unlike the other BCApps automations, it does not use + the GetGitBranches action and therefore has no knowledge of the "Branch is out of support" ruleset. + + This automation rewrites 'workflowSchedule.includeBranches' with the explicit list of every official + branch (main and releases/*) that is currently in support. The list contains no wildcards and is + recomputed on every run, so out-of-support branches are dropped and newly created branches are added. +.Parameter runParameters + A hashtable with the parameters passed by the RunAutomation action (Repository and TargetBranch). +#> +param ( + [Parameter(Mandatory = $true)] + $runParameters +) + +Import-Module $PSScriptRoot\..\..\..\..\build\scripts\EnlistmentHelperFunctions.psm1 -DisableNameChecking + +$repository = $runParameters.Repository + +$result = @{ + 'Files' = @() + 'Message' = "No update available" +} + +$settingsRelativePath = ".github/Update AL-Go System Files.settings.json" +$settingsPath = Join-Path (Get-BaseFolder) $settingsRelativePath + +if (-not (Test-Path $settingsPath)) { + Write-Host "Settings file '$settingsRelativePath' not found. Nothing to update." + return $result +} + +$settings = Get-Content -Path $settingsPath -Raw | ConvertFrom-Json + +if (-not $settings.workflowSchedule) { + Write-Host "No 'workflowSchedule' configured in '$settingsRelativePath'. Nothing to update." + return $result +} + +$currentBranches = @($settings.workflowSchedule.includeBranches) +Write-Host "Configured branches: $($currentBranches -join ', ')" + +# The official branches, matching the definition used by the GetGitBranches action. +$officialBranchPatterns = @('main', 'releases/*') + +# Fetch all remote branches so the official branches can be listed explicitly. +RunAndCheck git fetch --quiet origin "+refs/heads/*:refs/remotes/origin/*" +$allBranches = @(RunAndCheck git for-each-ref --format="%(refname:short)" refs/remotes/origin/) | Where-Object { $_ -ne 'origin' } | ForEach-Object { $_ -replace '^origin/', '' } + +# Keep only the official branches (main and releases/*) that are in support. +$supportedBranches = @( + $allBranches | Where-Object { + $branch = $_ + ($officialBranchPatterns | Where-Object { $branch -like $_ }) -and (Test-IsBranchInSupport -BranchName $branch -Repository $repository) + } +) + +# Order deterministically ('main' first, then release branches in natural numeric order) to keep diffs clean. +function Get-BranchSortKey { + param([string] $Branch) + if ($Branch -eq 'main') { + return '0' + } + # Zero-pad numeric segments so e.g. releases/26.2 sorts before releases/26.10. + $padded = [regex]::Replace($Branch, '\d+', { param($m) $m.Value.PadLeft(10, '0') }) + return "1$padded" +} +$supportedBranches = @($supportedBranches | Select-Object -Unique | Sort-Object { Get-BranchSortKey $_ }) + +if ($supportedBranches.Count -eq 0) { + Write-Host "::Warning::No supported official branches found; leaving the schedule unchanged." + return $result +} + +if (($currentBranches -join ',') -eq ($supportedBranches -join ',')) { + Write-Host "Scheduled branches already match the supported official branches. Nothing to update." + return $result +} + +Write-Host "Updated branches: $($supportedBranches -join ', ')" + +$settings.workflowSchedule.includeBranches = @($supportedBranches) +$settings | ConvertTo-Json -Depth 100 | Set-ContentLF -Path $settingsPath + +$result.Files = @($settingsRelativePath) +$result.Message = "Update Update AL-Go System Files schedule to only include supported branches" + +return $result diff --git a/.github/actions/RunAutomation/run.ps1 b/.github/actions/RunAutomation/run.ps1 index 3211e6a070f..38040d600fc 100644 --- a/.github/actions/RunAutomation/run.ps1 +++ b/.github/actions/RunAutomation/run.ps1 @@ -29,6 +29,15 @@ param( $ErrorActionPreference = "Stop"; $ProgressPreference = "SilentlyContinue"; Set-StrictMode -Version 2.0 +Import-Module $PSScriptRoot\..\..\..\build\scripts\EnlistmentHelperFunctions.psm1 -DisableNameChecking + +# Do not run automations on branches that are out of support (branches with the "Branch is out of support" ruleset). +# This is a safety net that also covers manual (workflow_dispatch) runs, which bypass the GetGitBranches filtering. +if (-not (Test-IsBranchInSupport -BranchName $TargetBranch -Repository $Repository)) { + Write-Host "::Notice::Skipping automations because branch '$TargetBranch' is out of support." + return +} + function RunAutomation { param( [Parameter(Mandatory=$true)] @@ -122,7 +131,7 @@ function OpenPR { git push -u origin $branch | Out-Null - $prDescription += "`n`nAB#539394" # Add link to a work item + $prDescription += "`n`nAB#640900" # Add link to a work item return New-GitHubPullRequest -Repository $Repository -BranchName $branch -TargetBranch $TargetBranch -Title $prTitle -Description $prDescription } diff --git a/.github/actions/TestObjectIdsAndManifests/action.ps1 b/.github/actions/TestObjectIdsAndManifests/action.ps1 index 0c09ed336e7..24d21db153e 100644 --- a/.github/actions/TestObjectIdsAndManifests/action.ps1 +++ b/.github/actions/TestObjectIdsAndManifests/action.ps1 @@ -1,29 +1,146 @@ Import-Module "$PSScriptRoot\..\..\..\build\scripts\AppObjectValidation.psm1" -Force +Import-Module "$PSScriptRoot\..\..\..\build\scripts\BuildOptimization.psm1" -Force Import-Module "$PSScriptRoot\..\..\..\build\scripts\EnlistmentHelperFunctions.psm1" -DisableNameChecking $sourceCodeFolder = Join-Path (Get-BaseFolder) "src" -Resolve -# Test that all test object IDs are within the valid range -Test-ObjectIDsAreValid -SourceCodePaths $sourceCodeFolder - -# Test that all application IDs are unique -Test-ApplicationIds -SourceCodePaths $sourceCodeFolder - -# That that test objects are categorized correctly -$allowedUncategorizedTests = @( - 139504, # Data Archive Tests - 133502,139624,139628, # E-Document Core Tests" - 148191, # E-Document Connector - Avalara Tests - 139621,139622, # Error Messages with Recommendations Tests - 139600, # Essential Business Headlines Test - 139876,139877,139878,139879,139880,139881,139875, # PowerBI Reports Tests - 139636,139568,139695,139608,139609,139611,139648,139567,139546,139551, # Shopify Connector Test - 139686,139687,139688,139689,139690,139691,139692,139693,148155,148152,139912,139913,139914,139915,139916,148160,148156,139884,139885,148157,139887,139888,139889,148158,148153,148159,139694,139895,148154, # Subscription Billing - 139610 # Send remittance advice by email Tests +# Base folders (everything except Apps and Layers) +$baseFolders = @(Get-ChildItem -Path $sourceCodeFolder -Directory -Exclude "Apps", "Layers" | Select-Object -ExpandProperty FullName) +# W1 Folders (For Apps and Layers) +$w1Apps = @(Join-Path $sourceCodeFolder "Apps\W1") +$w1Layers = @(Join-Path $sourceCodeFolder "Layers\W1") +# All Folders (For Apps) +$allApps = @(Join-Path $sourceCodeFolder "Apps") +# The 'Layers' folder only exists on main and not on release branches. Guard the +# Get-ChildItem call so it does not fail when the folder is missing. +$layersFolder = Join-Path $sourceCodeFolder 'Layers' +$allBaseApps = @( + if (Test-Path -Path $layersFolder) { + Get-ChildItem -Path $layersFolder -Directory | + ForEach-Object { Join-Path $_.FullName 'BaseApp' } | + Where-Object { Test-Path -Path $_ } + } ) -Test-ApplicationTestTypes -SourceCodePaths $sourceCodeFolder -Exceptions $allowedUncategorizedTests + +# Build path sets for different validations +# Some folders (e.g. Layers) only exist on main and not on release branches, so filter out +# any paths that do not exist to avoid Get-ChildItem failing on missing directories. +[string[]] $w1OnlyPaths = @($baseFolders + $w1Apps + $w1Layers | Where-Object { Test-Path -Path $_ }) +[string[]] $allPaths = @($baseFolders + $allApps + $w1Layers | Where-Object { Test-Path -Path $_ }) +[string[]] $objectIdValidationPaths = @( + $allBaseApps + (Join-Path $sourceCodeFolder 'Business Foundation\App') + (Join-Path $sourceCodeFolder 'System Application\App') + $allApps +) | Where-Object { Test-Path -Path $_ } + +# Define exceptions +$AllowedDuplicateObjects = @( + "table 230", # Source Code + "table 231", # Reason Code + "table 242", # Source Code Setup + "table 308", # No. Series + "table 309", # No. Series Line + "table 310", # No. Series Relationship + "table 1263", # No. Series Tenant + "table 6635", # Return Reason + "table 12145", # No. Series Line Sales + "table 12146" # No. Series Line Purchase +) + +# Test that all application IDs are unique (Base Folders + All Apps and W1 Layer) +$duplicateApplicationIds = @( + "bd16d8dd-8faf-45d3-b733-3ddc6b9cfabf", # Bug 592283 + "f3e4e6f8-2ba7-4202-834d-141ed9b89192" +) + +# Exception - Out of range test object IDs +$outOfRangeTestObjects = @( + 13918,13922,13923,13924,13925,13926, # E-Document for Germany Tests + 10505, # Intrastat GB Tests + 18649, # Fixed Asset Depreciation Tests + 18078,18427,18428,18429,18460,18488, # GST Base Tests + 18271,18272,18273, # GST On Payments Tests + 18125,18126,18127,18128,18131,18132, # GST Purchase Automation + 18133,18134,18135,18136,18137,18138,18139, # GST Purchase Automation (cont.) + 18191,18192,18193,18194,18196,18197,18198, # GST Sales Automation + 18479, # GST Subcontracting Automation + 18345,18346,18480,18481, # India GST Tests + 18044,18045,18046,18047, # India Reports Tests + 18990,18991, # India Charge Group Tests + 18628,18629,18630, # India Gate Entry Tests + 18996,18998,18999, # India Voucher Interface Tests + 18912, # TCS Base Test Automation + 18925,18927,18928, # TCS On Receipt Automation + 18914,18916,18917,18918,18919, # TCS on Sales Test Automation + 18921, # TCS Return and Settlement Automation + 18800, # TDS Base Tests + 18682,18683, # TDS On Customer Tests + 18790,18802,18803,18804,18805,18806, # TDS on Payments Tests + 18791,18792,18793,18794, # TDS on Purchase Tests + 18797 # TDS Return and Settlement Tests +) + +# Test that object IDs don't clash and test objects are in valid range (W1 only) +Test-ObjectIDsAreValid -SourceCodePaths $w1OnlyPaths -AllowedDuplicateObjects $AllowedDuplicateObjects + +# Test that all test object IDs are within the valid range (all apps - country test objects excepted) +Test-ObjectIDsAreValid -SourceCodePaths $allPaths -AllowedOutOfRangeTestObjects $outOfRangeTestObjects -SkipDuplicateCheck + +# Test that all application IDs are unique (all paths) +Test-ApplicationIds -SourceCodePaths $allPaths -Exceptions $duplicateApplicationIds # Test that all manifests are valid $currentMajorMinor = Get-ConfigValue -Key "repoVersion" -ConfigType AL-Go -$expectedPlatformVersion = "$($currentMajorMinor).0.0" # This can be hardcoded to a specific platform version if needed during version updates -Test-ApplicationManifests -Path $sourceCodeFolder -ExpectedAppVersion "$($currentMajorMinor).0.0" -ExpectedPlatformVersion $expectedPlatformVersion +$currentMajor = [int]($currentMajorMinor -split '\.')[0] +$expectedPlatformVersionCurrent = "$currentMajor.0.0.0" +$expectedPlatformVersionPrevious = "$($currentMajor - 1).0.0.0" +Test-ApplicationManifests -Path $allPaths -ExpectedAppVersion "$($currentMajorMinor).0.0" -ExpectedPlatformVersions @($expectedPlatformVersionCurrent, $expectedPlatformVersionPrevious) + +# Test that we are not adding new uncategorized tests (W1 only) - Disabled for now +# Test-ApplicationTestTypes -SourceCodePaths $w1OnlyPaths -Exceptions $allowedUncategorizedTests + +# Test object IDs declared in newly added production AL files. +$AllowedObjectIdRanges = @( + [PSCustomObject]@{ From = 1; To = 49999 }, + [PSCustomObject]@{ From = 2000000; To = 2000059 }, + [PSCustomObject]@{ From = 3005000; To = 3011499 }, + [PSCustomObject]@{ From = 5000000; To = 5000099 }, + [PSCustomObject]@{ From = 5000250; To = 5055999 }, + [PSCustomObject]@{ From = 5001900; To = 5001999 }, + [PSCustomObject]@{ From = 5005100; To = 5005399 }, + [PSCustomObject]@{ From = 7000000; To = 7000099 }, + [PSCustomObject]@{ From = 11000000; To = 11000499 }, + [PSCustomObject]@{ From = 15000000; To = 15000499 }, + [PSCustomObject]@{ From = 31000000; To = 31000099 }, + [PSCustomObject]@{ From = 32000000; To = 32000199 }, + [PSCustomObject]@{ From = 99000750; To = 99001048 } +) + +# '@($null)' has a Count of 1, so filter empties to make the guard below work. +$addedFiles = @(Get-ChangedFilesForCI -DiffFilter 'A' -CompareFromMergeBase -RequireChangeDetection | Where-Object { -not [string]::IsNullOrWhiteSpace($_) }) +if ($addedFiles.Count -eq 0) { + Write-Host "No newly added files were found; skipping the production object ID range validation." +} +else { + $repositoryRoot = (Resolve-Path -Path (Get-BaseFolder)).Path + $addedFilePaths = @($addedFiles | ForEach-Object { Join-Path -Path $repositoryRoot -ChildPath $_ }) + + # 'build\projects.json' is absent on some branches; pass it only when present. + $projectsJsonPath = Join-Path -Path $repositoryRoot -ChildPath 'build\projects.json' + $getALGoTestFoldersParams = @{ + ProjectsPath = Join-Path -Path $repositoryRoot -ChildPath 'build\projects' + RepositoryRoot = $repositoryRoot + } + if (Test-Path -LiteralPath $projectsJsonPath) { + $getALGoTestFoldersParams['ProjectsJsonPath'] = $projectsJsonPath + } + else { + Write-Host "No 'build\projects.json' found at '$projectsJsonPath'; deriving test folders from project settings only." + } + $testFolderPaths = Get-ALGoTestFolders @getALGoTestFoldersParams + $allowedRangesText = ($AllowedObjectIdRanges | ForEach-Object { "$($_.From)..$($_.To)" }) -join ', ' + Write-Host "Validating object IDs in newly added production AL files (allowed ranges: $allowedRangesText)." + + Test-ObjectIDsInAddedALFilesAreInAllowedRange -FilePaths $addedFilePaths -SourceCodePaths $objectIdValidationPaths -TestFolderPaths $testFolderPaths -AllowedRanges $AllowedObjectIdRanges +} diff --git a/.github/actions/TestObsoleteTagPreprocessors/action.ps1 b/.github/actions/TestObsoleteTagPreprocessors/action.ps1 new file mode 100644 index 00000000000..456c87e3e74 --- /dev/null +++ b/.github/actions/TestObsoleteTagPreprocessors/action.ps1 @@ -0,0 +1,34 @@ +# Current path is .github/actions/TestObsoleteTagPreprocessors + +Import-Module "$PSScriptRoot\..\..\..\build\scripts\TestObsoleteTagPreprocessors.psm1" -Force + +# Exception list for testing files (files that are used in testing and should be ignored). +# These are test libraries/fixtures that legitimately contain ObsoleteTag properties +# outside of preprocessor blocks. +$exceptionList = @( + "src\Layers\W1\Tests\TestLibraries\MergeDuplicateObsolete.Table.al", + "src\Layers\W1\Tests\TestLibraries\ObsoleteRemovedTable.Table.al", + "src\Layers\W1\Tests\TestLibraries\TableWithRemovedField.Table.al", + "src\Layers\W1\Tests\Upgrade\DataSetup\TableStateObsoleteRemoved.Table.al" +) + +Write-Host "Checking ObsoleteTag preprocessor compliance in .al files..." +Write-Host "Using $($exceptionList.Count) predefined exception(s) for test files" + +# Initialize array to store any invalid ObsoleteTag issues +$obsoleteTagIssues = @() + +$alfiles = (Get-ChildItem -Filter '*.al' -Recurse) | Select-Object -ExpandProperty FullName +foreach ($file in $alfiles) { + # Call the Test-ObsoleteTagPreprocessors function with the file path and exception list + $result = Test-ObsoleteTagPreprocessors -filePath $file -ExceptionList $exceptionList + if ($null -ne $result) { + $obsoleteTagIssues += $result.Issues + } +} + +if ($obsoleteTagIssues.Count -gt 0) { + throw "ObsoleteTag properties found outside preprocessor blocks:`n$($obsoleteTagIssues -join "`n")" +} + +Write-Host "All ObsoleteTag properties are properly surrounded by preprocessor symbols." diff --git a/.github/actions/TestObsoleteTagPreprocessors/action.yaml b/.github/actions/TestObsoleteTagPreprocessors/action.yaml new file mode 100644 index 00000000000..f07d9353ec5 --- /dev/null +++ b/.github/actions/TestObsoleteTagPreprocessors/action.yaml @@ -0,0 +1,13 @@ +name: Test Obsolete Tag Preprocessors +author: Microsoft Corporation +description: Verifies that ObsoleteTag properties on .al files are surrounded by preprocessor symbols +runs: + using: composite + steps: + - name: Test Obsolete Tag Preprocessors + shell: pwsh + run: | + ${{ github.action_path }}/action.ps1 +branding: + icon: terminal + color: blue diff --git a/.github/actions/UpdateUnstableTests/action.ps1 b/.github/actions/UpdateUnstableTests/action.ps1 new file mode 100644 index 00000000000..5ffc8ce7804 --- /dev/null +++ b/.github/actions/UpdateUnstableTests/action.ps1 @@ -0,0 +1,51 @@ +<# +.Synopsis + Entry point for the Update Unstable Tests action. +.Description + Reads the failing tests from the supplied CI/CD (or PR Build) runs and invokes the shared updater + script, which builds the per-branch unstable-tests list and exposes the artifact name for upload. + + By default the list is recomputed from the supplied runs. When -additive is set, the failing tests + are merged into the existing artifact instead (every existing entry is preserved). + + The set of runs to read is computed by the calling workflow and passed in as a comma-separated list. + + Parameters are passed explicitly by the action.yaml run block. +#> +[CmdletBinding()] +param( + [Parameter(Mandatory = $true)] + [string] $branch, + + [string] $runId = '', + + [switch] $additive +) + +$ErrorActionPreference = 'Stop' +$ProgressPreference = 'SilentlyContinue' +Set-StrictMode -Version 2.0 + +$scriptsRoot = Join-Path $PSScriptRoot '..' '..' '..' 'build' 'scripts' 'TestTolerance' +Import-Module (Join-Path $scriptsRoot 'TestTolerance.psm1') -Force + +# Parse the comma-separated run ids. +$runIds = @($runId.Split(',') | ForEach-Object { $_.Trim() } | Where-Object { $_ }) +if ($runIds.Count -eq 0) { + throw "No valid run IDs were provided in 'run-id' (value: '$runId'). Provide at least one CI/CD (or PR Build) run ID." +} + +$outputPath = Join-Path '.unstable-tests' 'unstable-tests.json' + +& (Join-Path $scriptsRoot 'UpdateUnstableTestsArtifact.ps1') ` + -Branch $branch ` + -RunIds $runIds ` + -OutputPath $outputPath ` + -Additive:$additive + +# Expose the artifact name so the action's upload step can publish it. Only emit it when the artifact +# was actually produced, so the upload step can be skipped otherwise. +if ($env:GITHUB_OUTPUT -and (Test-Path $outputPath)) { + $artifactName = Get-UnstableTestsArtifactName -Branch $branch + Add-Content -Encoding UTF8 -Path $env:GITHUB_OUTPUT -Value "artifactName=$artifactName" +} diff --git a/.github/actions/UpdateUnstableTests/action.yaml b/.github/actions/UpdateUnstableTests/action.yaml new file mode 100644 index 00000000000..3512d5c1021 --- /dev/null +++ b/.github/actions/UpdateUnstableTests/action.yaml @@ -0,0 +1,49 @@ +name: Update Unstable Tests +author: Microsoft Corporation +description: > + Updates the per-branch unstable-tests artifact from a set of CI/CD runs. By default the list is + recomputed from the supplied runs; when additive is set, their failing tests are merged into the + existing artifact instead. The runs to read are computed by the calling workflow. +inputs: + branch: + description: Target branch (e.g. 'main', 'releases/26.0') + required: true + run-id: + description: Comma-separated CI/CD (or PR Build) run IDs to read failing tests from. + required: true + additive: + description: > + When 'true', merge the runs' failing tests into the existing per-branch artifact (preserving + every existing entry) instead of recomputing the list from scratch. + required: false + default: 'false' +runs: + using: composite + steps: + - name: Update Unstable Tests + id: update + shell: pwsh + env: + GH_TOKEN: ${{ github.token }} + _branch: ${{ inputs.branch }} + _runId: ${{ inputs.run-id }} + _additive: ${{ inputs.additive }} + run: | + ${{ github.action_path }}/action.ps1 ` + -branch $env:_branch ` + -runId $env:_runId ` + -additive:($env:_additive -eq 'true') + + - name: Upload unstable tests artifact + if: steps.update.outputs.artifactName != '' + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + env: + ACTIONS_RUNNER_DISABLE_NODE_MAGLEV: 1 + with: + name: ${{ steps.update.outputs.artifactName }} + path: .unstable-tests/unstable-tests.json + if-no-files-found: warn + retention-days: 30 +branding: + icon: terminal + color: blue diff --git a/.github/actions/UpdateUnstableTestsCombined/action.ps1 b/.github/actions/UpdateUnstableTestsCombined/action.ps1 new file mode 100644 index 00000000000..04f11b4645d --- /dev/null +++ b/.github/actions/UpdateUnstableTestsCombined/action.ps1 @@ -0,0 +1,81 @@ +<# +.Synopsis + Entry point for the Update Unstable Tests (Combined) action. +.Description + Invokes the combined updater script, which maintains the per-branch unstable-tests artifact from both + detection signals in a single run: the CI/CD sliding-window recompute (Path A) and the additive + cross-PR PR-build detector (Path B). It then exposes the artifact name so the action's upload step can + publish it, only when the artifact was actually produced. + + Parameters are passed explicitly by the action.yaml run block, which sources the numeric tuning + values (RunLimit / WindowHours / MinDistinctPrs) from its own input defaults so they live in a + single place rather than being duplicated as PowerShell parameter defaults. + +.Parameter Branch + Supported branch (main or releases/*) whose unstable-tests artifact should be updated. +.Parameter RunLimit + Path A: number of recent completed CI/CD runs to recompute the base list from. +.Parameter FilterPush + Path A: include CI/CD runs triggered by 'push' when discovering the window. +.Parameter FilterWorkflowDispatch + Path A: include CI/CD runs triggered by 'workflow_dispatch' when discovering the window. +.Parameter WindowHours + Path B: how many hours of recent PR builds (by completion time) to examine. +.Parameter MinDistinctPrs + Path B: minimum number of distinct PRs a test must fail on to be marked unstable. +#> +[CmdletBinding()] +param( + [Parameter(Mandatory = $true)] + [string] $Branch, + + [Parameter(Mandatory = $true)] + [int] $RunLimit, + + [switch] $FilterPush, + + [switch] $FilterWorkflowDispatch, + + [Parameter(Mandatory = $true)] + [int] $WindowHours, + + [Parameter(Mandatory = $true)] + [int] $MinDistinctPrs +) + +$ErrorActionPreference = 'Stop' +$ProgressPreference = 'SilentlyContinue' +Set-StrictMode -Version 2.0 + +$scriptsRoot = Join-Path -Path $PSScriptRoot -ChildPath '..' -AdditionalChildPath '..', '..', 'build', 'scripts', 'TestTolerance' +Import-Module (Join-Path -Path $scriptsRoot -ChildPath 'TestTolerance.psm1') -Force + +$outputPath = Join-Path -Path '.unstable-tests' -ChildPath 'unstable-tests.json' + +try { + & (Join-Path -Path $scriptsRoot -ChildPath 'UpdateUnstableTestsCombined.ps1') ` + -Branch $Branch ` + -RunLimit $RunLimit ` + -FilterPush:$FilterPush ` + -FilterWorkflowDispatch:$FilterWorkflowDispatch ` + -WindowHours $WindowHours ` + -MinDistinctPrs $MinDistinctPrs ` + -OutputPath $outputPath + + # Expose the artifact name so the action's upload step can publish it. Only emit it when the artifact + # was actually produced, so the upload step can be skipped otherwise. + if ($env:GITHUB_OUTPUT -and (Test-Path $outputPath)) { + $artifactName = Get-UnstableTestsArtifactName -Branch $Branch + Add-Content -Encoding UTF8 -Path $env:GITHUB_OUTPUT -Value "artifactName=$artifactName" + } +} +catch { + Write-Host "::error::Failed to update unstable tests for '$Branch': $($_.Exception.Message)" + exit 1 +} + +# The driver runs best-effort 'gh' commands (e.g. downloading results from still-running PR builds that may +# not have uploaded any artifacts yet), which can leave $LASTEXITCODE non-zero even though the update itself +# succeeded. GitHub's pwsh wrapper ends with 'exit $LASTEXITCODE', so normalize the exit code on success to +# avoid failing the step on a benign, already-tolerated 'gh' error. +exit 0 diff --git a/.github/actions/UpdateUnstableTestsCombined/action.yaml b/.github/actions/UpdateUnstableTestsCombined/action.yaml new file mode 100644 index 00000000000..b154081733b --- /dev/null +++ b/.github/actions/UpdateUnstableTestsCombined/action.yaml @@ -0,0 +1,68 @@ +name: Update Unstable Tests (Combined) +author: Microsoft Corporation +description: > + Maintains the per-branch unstable-tests artifact from both detection signals in a single run: the CI/CD + sliding-window recompute (Path A) and the additive cross-PR PR-build detector (Path B). Publishes the + updated per-branch artifact, and only uploads when an artifact was actually produced. +inputs: + branch: + description: Target branch (e.g. 'main', 'releases/26.0') + required: true + run-limit: + description: 'Path A: number of recent completed CI/CD runs to examine.' + required: false + default: '3' + filter-push: + description: "Path A: include CI/CD runs triggered by push ('true'/'false')." + required: false + default: 'false' + filter-workflow-dispatch: + description: "Path A: include CI/CD runs triggered by workflow_dispatch ('true'/'false')." + required: false + default: 'true' + window-hours: + description: 'Path B: how many hours of recent PR builds to examine.' + required: false + default: '6' + min-distinct-prs: + description: 'Path B: minimum number of distinct PRs a test must fail on to be marked unstable.' + required: false + default: '3' +runs: + using: composite + steps: + - name: Update unstable tests + id: update + shell: pwsh + env: + GH_TOKEN: ${{ github.token }} + _branch: ${{ inputs.branch }} + _runLimit: ${{ inputs.run-limit }} + _filterPush: ${{ inputs.filter-push }} + _filterWorkflowDispatch: ${{ inputs.filter-workflow-dispatch }} + _windowHours: ${{ inputs.window-hours }} + _minDistinctPrs: ${{ inputs.min-distinct-prs }} + run: | + ${{ github.action_path }}/action.ps1 ` + -Branch $env:_branch ` + -RunLimit ([int]$env:_runLimit) ` + -FilterPush:($env:_filterPush -eq 'true') ` + -FilterWorkflowDispatch:($env:_filterWorkflowDispatch -eq 'true') ` + -WindowHours ([int]$env:_windowHours) ` + -MinDistinctPrs ([int]$env:_minDistinctPrs) + + - name: Upload unstable tests artifact + if: steps.update.outputs.artifactName != '' + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + env: + ACTIONS_RUNNER_DISABLE_NODE_MAGLEV: 1 + with: + name: ${{ steps.update.outputs.artifactName }} + path: .unstable-tests/unstable-tests.json + if-no-files-found: warn + # A fresh artifact is produced on every hourly run and PR builds only ever consume the latest, so + # a long retention just multiplies storage. 7 days still buffers a multi-day scheduler outage. + retention-days: 7 +branding: + icon: terminal + color: blue diff --git a/.github/actions/ValidateCountryProjects/action.ps1 b/.github/actions/ValidateCountryProjects/action.ps1 new file mode 100644 index 00000000000..904b6ef7c35 --- /dev/null +++ b/.github/actions/ValidateCountryProjects/action.ps1 @@ -0,0 +1,6 @@ +$repoRoot = & git rev-parse --show-toplevel +$result = & "$repoRoot/build/scripts/Update-CountryProjectSettings.ps1" -Validate +if ($result -eq $false) { + Write-Host "::error::Country project settings are out of date. Run 'build/scripts/Update-CountryProjectSettings.ps1' and commit the changes." + exit 1 +} diff --git a/.github/actions/ValidateCountryProjects/action.yaml b/.github/actions/ValidateCountryProjects/action.yaml new file mode 100644 index 00000000000..56e23ab9b8d --- /dev/null +++ b/.github/actions/ValidateCountryProjects/action.yaml @@ -0,0 +1,13 @@ +name: Validate Country Projects +author: Microsoft Corporation +description: Validates that country project settings.json files have correct W1 app dependencies. +runs: + using: composite + steps: + - name: Validate Country Projects + shell: pwsh + run: | + ${{ github.action_path }}/action.ps1 +branding: + icon: terminal + color: blue diff --git a/.github/actions/VerifyMiappSync/action.ps1 b/.github/actions/VerifyMiappSync/action.ps1 new file mode 100644 index 00000000000..b6b30e0be18 --- /dev/null +++ b/.github/actions/VerifyMiappSync/action.ps1 @@ -0,0 +1,5 @@ +# Current path is .github/actions/VerifyMiappSync + +Import-Module "$PSScriptRoot\..\..\..\build\scripts\Miapp\MicroSnapApp.psm1" -Force +$env:RepoBranchName = $env:GITHUB_BASE_REF +Invoke-MiSnapApp diff --git a/.github/actions/VerifyMiappSync/action.yaml b/.github/actions/VerifyMiappSync/action.yaml new file mode 100644 index 00000000000..aa5905dc00f --- /dev/null +++ b/.github/actions/VerifyMiappSync/action.yaml @@ -0,0 +1,13 @@ +name: Verify Miapp Sync +author: Microsoft Corporation +description: Verifies that all Miapp-dependent files are synchronized using Invoke-MiSnapApp. +runs: + using: composite + steps: + - name: Verify Miapp sync + shell: pwsh + run: | + ${{ github.action_path }}/action.ps1 +branding: + icon: terminal + color: blue diff --git a/build/scripts/AppObjectValidation.psm1 b/build/scripts/AppObjectValidation.psm1 index f120cf4e4a8..5afdde3122b 100644 --- a/build/scripts/AppObjectValidation.psm1 +++ b/build/scripts/AppObjectValidation.psm1 @@ -10,27 +10,39 @@ An array of paths to the source code directories to be scanned for AL files. .PARAMETER AllowedDuplicateObjects An array of object signatures (in the format " ") that are allowed to have duplicates. + .PARAMETER AllowedOutOfRangeTestObjects + An array of test object IDs that are allowed to be outside the valid range (e.g. country-specific test objects). .PARAMETER MinTestObjectId The minimum valid object ID for test objects. Default is 130000. .PARAMETER MaxTestObjectId The maximum valid object ID for test objects. Default is 149999. + .PARAMETER SkipDuplicateCheck + If specified, the duplicate object ID check is skipped. #> function Test-ObjectIDsAreValid { param( [string[]] $SourceCodePaths = @(), [string[]] $AllowedDuplicateObjects = @(), + [int[]] $AllowedOutOfRangeTestObjects = @(), [int] $MinTestObjectId = 130000, - [int] $MaxTestObjectId = 149999 + [int] $MaxTestObjectId = 149999, + [switch] $SkipDuplicateCheck ) $ApplicationObjects = Get-FilesCollection -SourceCodePaths $SourceCodePaths - $IntroducedDuplicates = @($ApplicationObjects.DuplicateObjects | Where-Object { -not ($AllowedDuplicateObjects -contains $_) }) + + $IntroducedDuplicates = @() + if (-not $SkipDuplicateCheck) { + $IntroducedDuplicates = @($ApplicationObjects.DuplicateObjects | Where-Object { -not ($AllowedDuplicateObjects -contains $_) }) + } $offendingObjects = @() foreach ($TestObject in $ApplicationObjects.TestObjects) { $ObjectID = GetObjectId $TestObject if (($ObjectID -lt $MinTestObjectId) -or ($ObjectID -gt $MaxTestObjectId)) { - $offendingObjects += $ObjectID + if (-not ($AllowedOutOfRangeTestObjects -contains $ObjectID)) { + $offendingObjects += $ObjectID + } } } @@ -135,6 +147,9 @@ function Test-ApplicationTestTypes { - DuplicateObjects: An array of object signatures that are found to be duplicates across the scanned files. .PARAMETER SourceCodePaths An array of paths to the source code directories to be scanned for AL files. + .PARAMETER ObjectTypePattern + A regular expression alternation of the AL object types to recognize. Defaults to the primary six + ID-bearing types so that existing callers (the duplicate and test object checks) are unaffected. .OUTPUTS A custom object with the following properties: - ObjectSignatures: A hash map of unique object signatures and their names. @@ -143,9 +158,11 @@ function Test-ApplicationTestTypes { #> function Get-FilesCollection ( - [string[]] $SourceCodePaths + [string[]] $SourceCodePaths, + [string] $ObjectTypePattern = 'codeunit|page|table|query|report|xmlport' ) { $SourceFiles = @{} + $ObjectDetails = @{} $TestObjectSignatures = @() $DuplicateObjectSignatures = @() @@ -156,7 +173,7 @@ function Get-FilesCollection } $filesInPath = Get-ChildItem -Path $Path -File -Recurse -Filter '*.al' foreach ($file in $filesInPath) { - $objectInfo = GetALObjectInformation -FilePath $file.FullName + $objectInfo = GetALObjectInformation -FilePath $file.FullName -ObjectTypePattern $ObjectTypePattern if ($null -eq $objectInfo) { continue } @@ -166,6 +183,13 @@ function Get-FilesCollection $TestObjectSignatures += $objectInfo.Signature } $SourceFiles.Add($objectInfo.Signature, $objectInfo.ObjectName) + $ObjectDetails.Add($objectInfo.Signature, [PSCustomObject] @{ + ObjectType = $objectInfo.ObjectType + ObjectId = $objectInfo.ObjectId + ObjectName = $objectInfo.ObjectName + Signature = $objectInfo.Signature + Path = $file.FullName + }) } else { $DuplicateObjectSignatures += $objectInfo.Signature @@ -176,6 +200,7 @@ function Get-FilesCollection return [PSCustomObject] @{ ObjectSignatures = $SourceFiles + ObjectDetails = $ObjectDetails TestObjects = $TestObjectSignatures DuplicateObjects = $DuplicateObjectSignatures } @@ -183,12 +208,13 @@ function Get-FilesCollection function GetALObjectInformation ( - [string] $FilePath + [string] $FilePath, + [string] $ObjectTypePattern = 'codeunit|page|table|query|report|xmlport' ) { # (? function Test-ApplicationManifests { param( - [string] $Path, + [string[]] $Path, [string] $ExpectedAppVersion, - [string] $ExpectedPlatformVersion + [string[]] $ExpectedPlatformVersions ) $appManifests = Get-ChildItem -Path $Path -File -Recurse -Filter 'app.json' $errors = @() @@ -241,8 +267,8 @@ function Test-ApplicationManifests { } # Check Platform Version - if ($ExpectedPlatformVersion -and ($appManifest.platform -ne $ExpectedPlatformVersion)) { - $errors += "ERROR: Wrong platform version in manifest $appManifestFile. Expected: $ExpectedPlatformVersion. Actual: $($appManifest.platform)" + if ($ExpectedPlatformVersions -and ($appManifest.platform -notin $ExpectedPlatformVersions)) { + $errors += "ERROR: Wrong platform version in manifest $appManifestFile. Expected one of: $($ExpectedPlatformVersions -join ', '). Actual: $($appManifest.platform)" } # Check Dependency Versions @@ -311,8 +337,223 @@ function GetObjectId return $ObjectId -as [int] } +<# + .SYNOPSIS + Determines whether an object ID falls within any of the provided allowed ranges. + .DESCRIPTION + Returns $true if the given numeric object ID is contained (inclusively) in at least one of the + allowed ranges, otherwise $false. + .PARAMETER ObjectId + The numeric object ID to validate. + .PARAMETER AllowedRanges + An array of range objects, each exposing integer 'From' and 'To' properties (inclusive bounds). +#> +function Test-IsObjectIdInAllowedRange { + param( + [Parameter(Mandatory = $true)] [int64] $ObjectId, + [Parameter(Mandatory = $true)] [object[]] $AllowedRanges + ) + + foreach ($range in $AllowedRanges) { + if (($ObjectId -ge [int64]$range.From) -and ($ObjectId -le [int64]$range.To)) { + return $true + } + } + + return $false +} + +<# + .SYNOPSIS + Returns the test application folders configured by AL-Go and the build metadata. + .DESCRIPTION + Reads every build project settings.json and resolves its testFolders entries to absolute paths. It also + includes projects marked isTest in projects.json, which covers test utilities listed as AL-Go appFolders. + A trailing wildcard is treated as the containing test folder because every application below it is a test app. + .PARAMETER ProjectsPath + The directory containing the AL-Go build projects. + .PARAMETER ProjectsJsonPath + The build projects.json file containing canonical isTest metadata. + .PARAMETER RepositoryRoot + The standalone BCApps repository root used to remap build-system paths. +#> +function Get-ALGoTestFolders { + param( + [Parameter(Mandatory = $true)] [string] $ProjectsPath, + [string] $ProjectsJsonPath, + [string] $RepositoryRoot + ) + + $testFolders = @() + $settingsFiles = Get-ChildItem -Path $ProjectsPath -File -Recurse -Filter 'settings.json' | + Where-Object { $_.Directory.Name -eq '.AL-Go' } + foreach ($settingsFile in $settingsFiles) { + $settings = Get-Content -Path $settingsFile.FullName -Raw | ConvertFrom-Json + foreach ($testFolder in @($settings.testFolders)) { + $testFolderWithoutWildcard = $testFolder -replace '[\\/]\*$', '' + $projectFolder = $settingsFile.Directory.Parent.FullName + $testFolders += [System.IO.Path]::GetFullPath((Join-Path -Path $projectFolder -ChildPath $testFolderWithoutWildcard)) + } + } + + if (-not [string]::IsNullOrWhiteSpace($ProjectsJsonPath)) { + if ([string]::IsNullOrWhiteSpace($RepositoryRoot)) { + throw 'RepositoryRoot is required when ProjectsJsonPath is provided.' + } + + $projects = (Get-Content -LiteralPath $ProjectsJsonPath -Raw | ConvertFrom-Json).projects + foreach ($project in $projects.PSObject.Properties) { + if ($project.Value.isTest -ne $true) { + continue + } + + foreach ($buildPath in @($project.Value.appJsonPath, $project.Value.projectPath)) { + if ([string]::IsNullOrWhiteSpace($buildPath)) { + continue + } + + $normalizedBuildPath = $buildPath -replace '/', '\' + $relativePath = $null + $bcAppsPrefix = '$env:INETROOT\App\BCApps\' + $appsPrefix = '$env:INETROOT\App\Apps\' + $layersPrefix = '$env:INETROOT\App\Layers\' + if ($normalizedBuildPath.StartsWith($bcAppsPrefix, [System.StringComparison]::OrdinalIgnoreCase)) { + $relativePath = $normalizedBuildPath.Substring($bcAppsPrefix.Length) + } + elseif ($normalizedBuildPath.StartsWith($appsPrefix, [System.StringComparison]::OrdinalIgnoreCase)) { + $relativePath = Join-Path 'src\Apps' $normalizedBuildPath.Substring($appsPrefix.Length) + } + elseif ($normalizedBuildPath.StartsWith($layersPrefix, [System.StringComparison]::OrdinalIgnoreCase)) { + $relativePath = Join-Path 'src\Layers' $normalizedBuildPath.Substring($layersPrefix.Length) + } + + if ([string]::IsNullOrWhiteSpace($relativePath)) { + continue + } + + $candidatePath = Join-Path $RepositoryRoot ($relativePath -replace '\$CountryCode', '*') + foreach ($resolvedPath in @(Get-Item -Path $candidatePath -ErrorAction SilentlyContinue)) { + if (-not $resolvedPath.PSIsContainer) { + $resolvedPath = $resolvedPath.Directory + } + $testFolders += $resolvedPath.FullName + } + } + } + } + + return @($testFolders | Sort-Object -Unique) +} + +function Test-IsPathUnderAnyFolder { + param( + [Parameter(Mandatory = $true)] [string] $Path, + [Parameter(Mandatory = $true)] [string[]] $Folders + ) + + $fullPath = [System.IO.Path]::GetFullPath($Path) + foreach ($folder in $Folders) { + $folderPrefix = [System.IO.Path]::GetFullPath($folder).TrimEnd('\', '/') + [System.IO.Path]::DirectorySeparatorChar + if ($fullPath.StartsWith($folderPrefix, [System.StringComparison]::OrdinalIgnoreCase)) { + return $true + } + } + + return $false +} + +function Test-IsFileInTestApplication { + param( + [Parameter(Mandatory = $true)] [string] $FilePath, + [Parameter(Mandatory = $true)] [string[]] $TestFolderPaths + ) + + if (Test-IsPathUnderAnyFolder -Path $FilePath -Folders $TestFolderPaths) { + return $true + } + if (IsTestObject -FilePath $FilePath) { + return $true + } + + $directory = [System.IO.DirectoryInfo](Split-Path -Path $FilePath -Parent) + while ($null -ne $directory) { + $manifestPath = Join-Path -Path $directory.FullName -ChildPath 'app.json' + if (Test-Path -LiteralPath $manifestPath -PathType Leaf) { + $manifest = Get-Content -LiteralPath $manifestPath -Raw | ConvertFrom-Json + return $manifest.name -match '(?i)\btests?\b|\btest[\s-]*librar(?:y|ies)\b|\btest[\s-]*toolkit\b' + } + $directory = $directory.Parent + } + + return $false +} + +<# + .SYNOPSIS + Tests object IDs declared in newly added production AL files. + .DESCRIPTION + Validates only files supplied by the caller that are under an allowed source root and not under an AL-Go + test folder. This avoids scanning existing objects and correctly excludes non-codeunit objects in test apps. + .PARAMETER FilePaths + Absolute paths to files added by the current change. + .PARAMETER SourceCodePaths + Source roots in which production AL files are eligible for validation. + .PARAMETER TestFolderPaths + AL-Go test application folders that must not be checked against production ranges. + .PARAMETER AllowedRanges + An array of range objects, each exposing integer 'From' and 'To' properties (inclusive bounds). + .PARAMETER ObjectTypePattern + A regular expression alternation of the AL object types to recognize. +#> +function Test-ObjectIDsInAddedALFilesAreInAllowedRange { + param( + [Parameter(Mandatory = $true)] [string[]] $FilePaths, + [Parameter(Mandatory = $true)] [string[]] $SourceCodePaths, + [Parameter(Mandatory = $true)] [string[]] $TestFolderPaths, + [Parameter(Mandatory = $true)] [object[]] $AllowedRanges, + [string] $ObjectTypePattern = 'tableextension|pageextension|reportextension|enumextension|permissionsetextension|permissionset|codeunit|page|table|report|xmlport|query|enum' + ) + + $offendingObjects = @() + foreach ($filePath in $FilePaths) { + if ([System.IO.Path]::GetExtension($filePath) -ne '.al') { + continue + } + if (-not (Test-IsPathUnderAnyFolder -Path $filePath -Folders $SourceCodePaths)) { + continue + } + if (Test-IsFileInTestApplication -FilePath $filePath -TestFolderPaths $TestFolderPaths) { + continue + } + if (-not (Test-Path -LiteralPath $filePath -PathType Leaf)) { + throw "Added AL file '$filePath' does not exist." + } + + $objectInfo = GetALObjectInformation -FilePath $filePath -ObjectTypePattern $ObjectTypePattern + if (($null -ne $objectInfo) -and (-not (Test-IsObjectIdInAllowedRange -ObjectId ([int64]$objectInfo.ObjectId) -AllowedRanges $AllowedRanges))) { + $offendingObjects += [PSCustomObject]@{ + ObjectType = $objectInfo.ObjectType + ObjectId = $objectInfo.ObjectId + ObjectName = $objectInfo.ObjectName + Path = $filePath + } + } + } + + if ($offendingObjects.Count -gt 0) { + $rangeText = (($AllowedRanges | ForEach-Object { "$($_.From)..$($_.To)" }) -join ', ') + foreach ($offendingObject in ($offendingObjects | Sort-Object { [int64]$_.ObjectId })) { + Write-Host "##[error]Object '$($offendingObject.ObjectType) $($offendingObject.ObjectId) $($offendingObject.ObjectName)' in newly added file '$($offendingObject.Path)' has an ID outside the allowed range(s): $rangeText" + } + throw "Object ID validation failed. $($offendingObjects.Count) object(s) in newly added AL file(s) have IDs outside the allowed range(s) ($rangeText)." + } +} + Export-ModuleMember -Function Test-ObjectIDsAreValid Export-ModuleMember -Function Test-ApplicationIds Export-ModuleMember -Function Test-ApplicationTestTypes Export-ModuleMember -Function Test-ApplicationManifests -Export-ModuleMember -Function Get-FilesCollection \ No newline at end of file +Export-ModuleMember -Function Get-FilesCollection +Export-ModuleMember -Function Test-IsObjectIdInAllowedRange +Export-ModuleMember -Function Get-ALGoTestFolders +Export-ModuleMember -Function Test-ObjectIDsInAddedALFilesAreInAllowedRange diff --git a/build/scripts/AutomatedSubmission.psm1 b/build/scripts/AutomatedSubmission.psm1 index c63a70db8ff..4d6cbcfc2c1 100644 --- a/build/scripts/AutomatedSubmission.psm1 +++ b/build/scripts/AutomatedSubmission.psm1 @@ -152,7 +152,14 @@ function New-GitHubPullRequest Write-Host "gh pr create $parameters" $prLink = Invoke-Expression "gh pr create $parameters" - gh pr merge --auto --squash --delete-branch | Out-Null + + # Enabling auto-merge can fail due repository configuration or transient GitHub API issues. + # A PR has already been created at this point, so the automation should continue. + $mergeOutput = @(gh pr merge --auto --squash 2>&1) + if ($LASTEXITCODE -ne 0) { + Write-Host "::Warning::Failed to enable auto-merge for PR '$prLink'. Continuing without auto-merge. Details: $($mergeOutput -join ' ')" + $global:LASTEXITCODE = 0 + } return $prLink } diff --git a/build/scripts/BuildOptimization.psm1 b/build/scripts/BuildOptimization.psm1 new file mode 100644 index 00000000000..2c5d5a53037 --- /dev/null +++ b/build/scripts/BuildOptimization.psm1 @@ -0,0 +1,503 @@ +<# +.SYNOPSIS + Test-skip logic for CI/CD build optimization. +.DESCRIPTION + Determines whether a test app should be skipped based on which files changed + and the app dependency graph. Called from RunTestsInBcContainer.ps1. +#> + +$ErrorActionPreference = "Stop" + + +<# +.SYNOPSIS + Builds a dependency graph from all app.json files under the given base folder. +.PARAMETER BaseFolder + Root of the repository. +.OUTPUTS + Hashtable keyed by lowercase app ID. Each value is a PSCustomObject with + Id, Name, AppFolder, Dependencies (string[]), Dependents (List[string]). +#> +function Get-AppDependencyGraph { + [CmdletBinding()] + [OutputType([hashtable])] + param( + [Parameter(Mandatory)] + [string] $BaseFolder + ) + + $graph = @{} + $appJsonFiles = Get-ChildItem -Path $BaseFolder -Recurse -Filter 'app.json' -File | + Where-Object { $_.FullName -notmatch '[\\/]\.buildartifacts[\\/]' } + + foreach ($file in $appJsonFiles) { + $json = Get-Content -Path $file.FullName -Raw | ConvertFrom-Json + if (-not $json.id) { continue } + + $appId = $json.id.ToLowerInvariant() + $depIds = @() + if ($json.dependencies) { + $depIds = @($json.dependencies | ForEach-Object { $_.id.ToLowerInvariant() }) + } + + $graph[$appId] = [PSCustomObject]@{ + Id = $appId + Name = $json.name + AppFolder = $file.DirectoryName + Dependencies = $depIds + Dependents = [System.Collections.Generic.List[string]]::new() + } + } + + foreach ($node in $graph.Values) { + foreach ($depId in $node.Dependencies) { + if ($graph.ContainsKey($depId)) { + $graph[$depId].Dependents.Add($node.Id) + } + } + } + + return $graph +} + +<# +.SYNOPSIS + Determines which app (if any) a file belongs to by walking up to the nearest app.json. +.PARAMETER FilePath + Path to the changed file (absolute or relative to BaseFolder). +.PARAMETER BaseFolder + Root of the repository. +.OUTPUTS + The app ID (lowercase GUID) or $null if the file is not inside any app folder. +#> +function Get-AppForFile { + [CmdletBinding()] + [OutputType([string])] + param( + [Parameter(Mandatory)] + [string] $FilePath, + [Parameter(Mandatory)] + [string] $BaseFolder + ) + + if (-not [System.IO.Path]::IsPathRooted($FilePath)) { + $FilePath = Join-Path $BaseFolder $FilePath + } + $FilePath = [System.IO.Path]::GetFullPath($FilePath) + + $dir = [System.IO.Path]::GetDirectoryName($FilePath) + $baseFolderNorm = [System.IO.Path]::GetFullPath($BaseFolder).TrimEnd([System.IO.Path]::DirectorySeparatorChar, [System.IO.Path]::AltDirectorySeparatorChar) + + while ($dir -and $dir.Length -ge $baseFolderNorm.Length) { + $candidate = Join-Path $dir 'app.json' + if (Test-Path $candidate) { + $json = Get-Content -Path $candidate -Raw | ConvertFrom-Json + if ($json.id) { return $json.id.ToLowerInvariant() } + } + $parent = [System.IO.Path]::GetDirectoryName($dir) + if ($parent -eq $dir) { break } + $dir = $parent + } + + return $null +} + +<# +.SYNOPSIS + Given changed files, computes the set of affected app IDs via downstream BFS. +.DESCRIPTION + Maps each changed file to its app, then walks dependents (BFS) to find all + apps that transitively depend on a changed app. Files under src/ that can't + be mapped to an app trigger a full build (returns all app IDs). +.PARAMETER ChangedFiles + Array of changed file paths (relative to BaseFolder or absolute). +.PARAMETER BaseFolder + Root of the repository. +.PARAMETER Graph + Pre-built dependency graph. If not provided, one is built from BaseFolder. +.OUTPUTS + String array of affected app IDs (lowercase GUIDs). +#> +function Get-AffectedApps { + [CmdletBinding()] + [OutputType([string[]])] + param( + [Parameter(Mandatory)] + [string[]] $ChangedFiles, + [Parameter(Mandatory)] + [string] $BaseFolder, + [Parameter()] + [hashtable] $Graph + ) + + if (-not $Graph) { + $Graph = Get-AppDependencyGraph -BaseFolder $BaseFolder + } + + # Map changed files to apps + $directlyChanged = [System.Collections.Generic.HashSet[string]]::new() + foreach ($file in $ChangedFiles) { + $appId = Get-AppForFile -FilePath $file -BaseFolder $BaseFolder + if ($appId) { + [void]$directlyChanged.Add($appId) + } elseif ($file.Replace('\', '/') -match '(^|/)src/') { + # Unmapped file under src/ — safety fallback to full build + return [string[]]@($Graph.Keys) + } + } + + if ($directlyChanged.Count -eq 0) { return [string[]]@() } + + # BFS downstream: changed apps + everything that depends on them + $affected = [System.Collections.Generic.HashSet[string]]::new() + $queue = [System.Collections.Generic.Queue[string]]::new() + foreach ($appId in $directlyChanged) { + if ($Graph.ContainsKey($appId)) { $queue.Enqueue($appId) } + } + + while ($queue.Count -gt 0) { + $current = $queue.Dequeue() + if ($affected.Contains($current)) { continue } + [void]$affected.Add($current) + if ($Graph.ContainsKey($current)) { + foreach ($dep in $Graph[$current].Dependents) { + if (-not $affected.Contains($dep)) { $queue.Enqueue($dep) } + } + } + } + + return [string[]]@($affected) +} + +<# +.SYNOPSIS + Resolves the merge base between two commits. +.DESCRIPTION + Tries 'git merge-base' directly, and - should the merge base not be reachable + because one side's commit has not been fetched yet - fetches both endpoints + and tries once more. The workflows that rely on change detection check out the + full history (fetch-depth: 0), so no history deepening is required here. +.PARAMETER BaseSha + The base commit SHA. +.PARAMETER HeadSha + The head commit SHA. +.OUTPUTS + The merge-base commit SHA, or an empty string when it cannot be determined. +#> +function Resolve-MergeBaseForCI { + [CmdletBinding()] + [OutputType([string])] + param( + [Parameter(Mandatory = $true)] [string] $BaseSha, + [Parameter(Mandatory = $true)] [string] $HeadSha + ) + + $mergeBase = (& git merge-base $BaseSha $HeadSha 2>$null) + if (-not [string]::IsNullOrWhiteSpace($mergeBase)) { + return $mergeBase + } + + # Fetch both endpoints in case one side's commit is missing, then retry. + & git fetch --no-tags origin $BaseSha $HeadSha 2>$null + return (& git merge-base $BaseSha $HeadSha 2>$null) +} + +<# +.SYNOPSIS + Detects changed files from the GitHub Actions CI environment. +.DESCRIPTION + Reads the GitHub event payload ($GITHUB_EVENT_PATH) to extract base/head commit + SHAs, then uses git diff with those SHAs. This approach works reliably with + shallow clones (unlike three-dot diffs that need the merge base). + Supports pull_request, merge_group, and push events. + Returns $null when changed files cannot be determined (local, workflow_dispatch, git failure). + .PARAMETER DiffFilter + Optional git diff-filter value, for example 'A' to return only newly added files. + .PARAMETER CompareFromMergeBase + Compare the head against the merge base instead of the current base-branch tip. + .PARAMETER RequireChangeDetection + Throw instead of returning null when the change set cannot be determined. +.OUTPUTS + String array of changed file paths relative to repo root, or $null. +#> +function Get-ChangedFilesForCI { + [CmdletBinding()] + [OutputType([string[]])] + param( + [string] $DiffFilter, + [switch] $CompareFromMergeBase, + [switch] $RequireChangeDetection + ) + + if (-not $env:GITHUB_ACTIONS) { + if ($RequireChangeDetection) { + throw "Change detection requires a GitHub Actions environment." + } + Write-Host "BUILD OPTIMIZATION: Change detection skipped - not running in GitHub Actions" + return $null + } + + if ($env:GITHUB_EVENT_NAME -eq 'workflow_dispatch') { + if ($RequireChangeDetection) { + throw "Change detection is not supported for workflow_dispatch events." + } + Write-Host "BUILD OPTIMIZATION: Change detection skipped - workflow_dispatch event" + return $null + } + + # Read GitHub event payload for base/head commit SHAs (works with shallow clones) + if (-not $env:GITHUB_EVENT_PATH -or -not (Test-Path $env:GITHUB_EVENT_PATH)) { + if ($RequireChangeDetection) { + throw "GitHub event payload not found at '$($env:GITHUB_EVENT_PATH)'." + } + Write-Host "BUILD OPTIMIZATION: GitHub event payload not found at '$($env:GITHUB_EVENT_PATH)'" + return $null + } + + $eventPayload = Get-Content $env:GITHUB_EVENT_PATH -Raw | ConvertFrom-Json + + $baseSha = $null + $headSha = $null + + if ($env:GITHUB_EVENT_NAME -match 'pull_request') { + $baseSha = $eventPayload.pull_request.base.sha + $headSha = $eventPayload.pull_request.head.sha + } + elseif ($env:GITHUB_EVENT_NAME -eq 'merge_group') { + $baseSha = $eventPayload.merge_group.base_sha + $headSha = $eventPayload.merge_group.head_sha + } + elseif ($env:GITHUB_EVENT_NAME -eq 'push') { + $baseSha = $eventPayload.before + $headSha = $eventPayload.after + } + + if (-not $baseSha -or -not $headSha) { + if ($RequireChangeDetection) { + throw "Could not extract commit SHAs from the GitHub event payload (event=$($env:GITHUB_EVENT_NAME))." + } + Write-Host "BUILD OPTIMIZATION: Could not extract commit SHAs from event payload (event=$($env:GITHUB_EVENT_NAME))" + return $null + } + + Write-Host "BUILD OPTIMIZATION: Comparing $($baseSha.Substring(0, 8))...$($headSha.Substring(0, 8))" + + $prevErrorAction = $ErrorActionPreference + $ErrorActionPreference = 'Continue' + try { + # Fetch only when the event's base commit is not already available locally. + & git cat-file -e "$baseSha^{commit}" 2>$null + if ($LASTEXITCODE -ne 0) { + if ($CompareFromMergeBase) { + & git fetch origin $baseSha 2>$null + } + else { + & git fetch origin $baseSha --depth=1 2>$null + } + } + + $diffBase = $baseSha + if ($CompareFromMergeBase) { + $diffBase = Resolve-MergeBaseForCI -BaseSha $baseSha -HeadSha $headSha + if ([string]::IsNullOrWhiteSpace($diffBase)) { + if ($RequireChangeDetection) { + throw "Could not determine the merge base between '$baseSha' and '$headSha'." + } + Write-Host "BUILD OPTIMIZATION: Could not determine merge base" + return $null + } + } + + $diffArguments = @('-c', 'core.quotePath=false', 'diff', '--name-only') + if (-not [string]::IsNullOrWhiteSpace($DiffFilter)) { + $diffArguments += "--diff-filter=$DiffFilter" + } + $diffArguments += @($diffBase, $headSha, '--') + + $files = @(& git @diffArguments 2>$null) + if ($LASTEXITCODE -ne 0) { + if ($RequireChangeDetection) { + throw "Git diff failed with exit code $LASTEXITCODE." + } + Write-Host "BUILD OPTIMIZATION: git diff failed (exitCode=$LASTEXITCODE)" + return $null + } + + if ($files.Count -eq 0) { + Write-Host "BUILD OPTIMIZATION: No changed files detected" + return $null + } + + return [string[]]$files + } + finally { + $ErrorActionPreference = $prevErrorAction + } +} + +<# +.SYNOPSIS + Checks whether any changed files match the fullBuildPatterns from AL-Go settings. +.DESCRIPTION + Reads the fullBuildPatterns array from .github/AL-Go-Settings.json and tests + each changed file path against each pattern using -like. When AL-Go detects + matching files it forces a full compile, so the test side must also force a + full test run (i.e., skip nothing). +.PARAMETER ChangedFiles + Array of changed file paths (relative to repo root, forward-slash separated). +.PARAMETER BaseFolder + Root of the repository (used to locate .github/AL-Go-Settings.json). +.OUTPUTS + $true if any changed file matches a fullBuildPattern, $false otherwise. +#> +function Test-FullBuildPatternsMatch { + [CmdletBinding()] + [OutputType([bool])] + param( + [Parameter(Mandatory)] + [string[]] $ChangedFiles, + [Parameter(Mandatory)] + [string] $BaseFolder + ) + + $settingsPath = Join-Path $BaseFolder '.github/AL-Go-Settings.json' + if (-not (Test-Path $settingsPath)) { return $false } + + $settings = Get-Content -Path $settingsPath -Raw | ConvertFrom-Json + $patterns = $settings.fullBuildPatterns + if (-not $patterns -or $patterns.Count -eq 0) { return $false } + + foreach ($file in $ChangedFiles) { + $normalized = $file.Replace('\', '/') + foreach ($pattern in $patterns) { + if ($normalized -like $pattern) { + Write-Host "BUILD OPTIMIZATION: File '$normalized' matches fullBuildPattern '$pattern' - forcing full test run" + return $true + } + } + } + + return $false +} + +<# +.SYNOPSIS + Computes the set of app names affected by changed files. +.DESCRIPTION + Pure computation — no caching or side effects. Returns a PSCustomObject with + two properties: RunAll (bool) and AppNames (string[]). The caller is responsible + for persisting/reading the result to avoid recomputing across process invocations. +.PARAMETER BaseFolder + Root of the repository. +.OUTPUTS + PSCustomObject with RunAll (bool) and AppNames (string[]). +#> +function Get-AffectedAppNames { + [CmdletBinding()] + [OutputType([PSCustomObject])] + param( + [Parameter(Mandatory)] + [string] $BaseFolder + ) + + $runAll = @{ RunAll = $true; AppNames = @() } + + if ($env:BUILD_OPTIMIZATION_DISABLED -eq 'true') { + Write-Host "BUILD OPTIMIZATION: Disabled via BUILD_OPTIMIZATION_DISABLED=true" + return [PSCustomObject]$runAll + } + if (-not $env:GITHUB_ACTIONS) { + return [PSCustomObject]$runAll + } + if ($env:GITHUB_EVENT_NAME -eq 'workflow_dispatch') { + return [PSCustomObject]$runAll + } + + $changedFiles = Get-ChangedFilesForCI + if (-not $changedFiles) { + Write-Host "BUILD OPTIMIZATION: Running all tests - could not determine changed files" + return [PSCustomObject]$runAll + } + + Write-Host "BUILD OPTIMIZATION: Changed files ($($changedFiles.Count)):" + foreach ($f in $changedFiles) { Write-Host " - $f" } + + # If any changed file matches fullBuildPatterns, AL-Go compiles everything. + # We must run all tests to match — skip nothing. + if (Test-FullBuildPatternsMatch -ChangedFiles $changedFiles -BaseFolder $BaseFolder) { + Write-Host "BUILD OPTIMIZATION: fullBuildPatterns matched, full test run required" + return [PSCustomObject]$runAll + } + + $graph = Get-AppDependencyGraph -BaseFolder $BaseFolder + $affectedIds = Get-AffectedApps -ChangedFiles $changedFiles -BaseFolder $BaseFolder -Graph $graph + + # Full build triggered (unmapped src file or all apps affected) + if ($affectedIds.Count -ge $graph.Count) { + Write-Host "BUILD OPTIMIZATION: Full build triggered ($($affectedIds.Count) apps affected)" + return [PSCustomObject]$runAll + } + + $affectedNames = @() + foreach ($id in $affectedIds) { + if ($graph.ContainsKey($id)) { $affectedNames += $graph[$id].Name } + } + + $sortedNames = $affectedNames | Sort-Object + Write-Host "BUILD OPTIMIZATION: Affected apps ($($affectedNames.Count)):" + foreach ($name in $sortedNames) { Write-Host " - $name" } + + return [PSCustomObject]@{ RunAll = $false; AppNames = $affectedNames } +} + +<# +.SYNOPSIS + Determines whether tests for a given app should be skipped. +.DESCRIPTION + Reads the cached affected-apps JSON file written by a prior call in the same + CI job. If the file doesn't exist, computes the result and writes the cache. + Returns $true to skip, $false to run. +.PARAMETER AppName + The display name of the test app (from $parameters["appName"]). +.PARAMETER BaseFolder + Root of the repository. +.PARAMETER CacheFile + Path to the JSON cache file. Defaults to $TEMP/BuildOptimization_AffectedApps.json. +.OUTPUTS + $true if the test app should be skipped, $false if it should run. +#> +function Test-ShouldSkipTestApp { + [CmdletBinding()] + [OutputType([bool])] + param( + [Parameter(Mandatory)] + [string] $AppName, + [Parameter(Mandatory)] + [string] $BaseFolder, + [string] $CacheFile = (Join-Path ([System.IO.Path]::GetTempPath()) 'BuildOptimization_AffectedApps.json') + ) + + # Read or compute affected apps + if (Test-Path $CacheFile) { + Write-Host "BUILD OPTIMIZATION: Reading cached result from $CacheFile" + $result = Get-Content $CacheFile -Raw | ConvertFrom-Json + } else { + $result = Get-AffectedAppNames -BaseFolder $BaseFolder + $result | ConvertTo-Json -Compress | Set-Content -Path $CacheFile -Force + Write-Host "BUILD OPTIMIZATION: Cache written to $CacheFile" + } + + if ($result.RunAll) { + Write-Host "BUILD OPTIMIZATION: RUNNING tests for '$AppName'" + return $false + } + + if ($result.AppNames -notcontains $AppName) { + Write-Host "BUILD OPTIMIZATION: SKIPPING tests for '$AppName' - not in affected set" + return $true + } + Write-Host "BUILD OPTIMIZATION: RUNNING tests for '$AppName'" + return $false +} + +Export-ModuleMember -Function Get-AppDependencyGraph, Get-AppForFile, Get-AffectedApps, Get-ChangedFilesForCI, Test-FullBuildPatternsMatch, Get-AffectedAppNames, Test-ShouldSkipTestApp diff --git a/build/scripts/EnlistmentHelperFunctions.psm1 b/build/scripts/EnlistmentHelperFunctions.psm1 index 6b5edb1bcb7..bd4aebe37a6 100644 --- a/build/scripts/EnlistmentHelperFunctions.psm1 +++ b/build/scripts/EnlistmentHelperFunctions.psm1 @@ -204,13 +204,19 @@ function Set-ConfigValue() { For example, if the repo version is 1.2, the function will look for the latest version of the package that has major.minor = 1.2. .Parameter PackageName The name of the package +.Parameter Branch + The branch the package version is being updated for (e.g. "main" or "releases/28.0"). + Used to decide which storage account to use for BCArtifacts baselines. When not provided, + it falls back to Get-CurrentBranch. .Returns The latest version of the package #> function Get-PackageLatestVersion() { param( [Parameter(Mandatory=$true)] - [string] $PackageName + [string] $PackageName, + [Parameter(Mandatory=$false)] + [string] $Branch ) $package = Get-ConfigValue -Key $PackageName -ConfigType Packages @@ -243,7 +249,15 @@ function Get-PackageLatestVersion() { } } - $currentBranch = Get-CurrentBranch + # Determine the branch this update is running for. The automation is triggered from a + # single workflow (running on 'main') that updates every release branch via a matrix, so + # Get-CurrentBranch (which returns $GITHUB_REF_NAME) reports 'main' for every job and + # cannot be used to pick the storage account. Prefer the explicit target branch passed in + # by the automation and only fall back to Get-CurrentBranch when it is not available. + $currentBranch = $Branch + if (-not $currentBranch) { + $currentBranch = Get-CurrentBranch + } Write-Host "Current branch: $currentBranch" $storageAccountOrder = @("bcartifacts", "bcinsider") if($currentBranch -eq "main") { @@ -261,6 +275,20 @@ function Get-PackageLatestVersion() { return $latestVersion } + 'BCPlatform' { + Import-Module $PSScriptRoot\PlatformHelper.psm1 -DisableNameChecking + + # Use the major.minor of the currently configured platform version, not repoVersion + [System.Version] $currentPlatformVersion = $package.Version + $majorMinor = "$($currentPlatformVersion.Major).$($currentPlatformVersion.Minor)" + $latestVersion = Get-LatestPlatformVersion -MajorMinor $majorMinor + + if (-not $latestVersion) { + throw "Could not find platform version (for major.minor: $majorMinor)" + } + + return $latestVersion + } default { throw "Unknown package source: $($package.Source)" } @@ -380,13 +408,18 @@ function Update-BCArtifactVersion { Updates the version of a package in the Packages config file to the latest version available. .Parameter PackageName The name of the package to update +.Parameter Branch + The branch the package version is being updated for (e.g. "main" or "releases/28.0"). + Forwarded to Get-PackageLatestVersion to select the correct BCArtifacts baseline storage account. .Returns The new version of the package, if it was updated #> function Update-PackageVersion ( [Parameter(Mandatory=$true)] - [string] $PackageName + [string] $PackageName, + [Parameter(Mandatory=$false)] + [string] $Branch ) { $currentPackage = Get-ConfigValue -Key $PackageName -ConfigType Packages @@ -398,7 +431,13 @@ function Update-PackageVersion $currentVersion = $currentPackage.Version Write-Host "Current $PackageName version: $currentVersion" - $latestVersion = Get-PackageLatestVersion -PackageName $PackageName + # If the current version is a major.minor pattern (e.g. "28.0"), it is intentionally pinned and should not be overwritten with a full version + if ($currentVersion.Split('.').Count -eq 2) { + Write-Host "$PackageName is pinned to the major.minor pattern '$currentVersion'. Skipping update." + return $null + } + + $latestVersion = Get-PackageLatestVersion -PackageName $PackageName -Branch $Branch Write-Host "Latest $PackageName version found: $latestVersion" $result = $null diff --git a/build/scripts/PlatformHelper.psm1 b/build/scripts/PlatformHelper.psm1 new file mode 100644 index 00000000000..64bdc2b6ba4 --- /dev/null +++ b/build/scripts/PlatformHelper.psm1 @@ -0,0 +1,179 @@ +$script:PlatformCdnUrl = 'https://bcinsider-fvh2ekdjecfjd6gk.b02.azurefd.net' +$script:PlatformIndexUrl = "$script:PlatformCdnUrl/platform/indexes/platform.json" +$script:PlatformVersionsCache = $null + +<# +.SYNOPSIS + Downloads and caches the platform version index. +.DESCRIPTION + Fetches the platform.json index file from the CDN and caches it + for subsequent calls within the same session. +.PARAMETER Force + When specified, forces a refresh of the cached version index. +.OUTPUTS + Array of version strings available in the platform index. +#> +function Get-PlatformVersions { + [CmdletBinding()] + param( + [Parameter(Mandatory = $false)] + [switch] $Force + ) + + if ($null -eq $script:PlatformVersionsCache -or $Force) { + try { + Write-Host "Fetching platform version index from $script:PlatformIndexUrl" + $response = Invoke-WebRequest -Uri $script:PlatformIndexUrl -ErrorAction Stop + $index = @($response.Content | ConvertFrom-Json) + if ($index.Count -gt 0 -and $index[0].PSObject.Properties['Version']) { + $script:PlatformVersionsCache = @($index | ForEach-Object { $_.Version }) + } else { + $script:PlatformVersionsCache = $index + } + } + catch { + throw "Failed to fetch platform version index from '$script:PlatformIndexUrl': $($_.Exception.Message)" + } + } + + return $script:PlatformVersionsCache +} + +<# +.SYNOPSIS + Gets the full CDN URL for a specific platform version. +.DESCRIPTION + Constructs and returns the full CDN URL for downloading a specific platform version. + Validates that the version exists in the platform index. +.PARAMETER Version + The full platform version string (e.g., '29.0.49913.0'). +.OUTPUTS + The full CDN URL for the specified platform version. +.EXAMPLE + Get-PlatformVersionUrl -Version '29.0.49913.0' + Returns: https://bcinsider-fvh2ekdjecfjd6gk.b02.azurefd.net/platform/29.0.49913.0 +#> +function Get-PlatformVersionUrl { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string] $Version + ) + + $availableVersions = Get-PlatformVersions + if ($availableVersions -notcontains $Version) { + throw "Platform version '$Version' is not available. Use Get-PlatformVersions to see available versions." + } + + return "$script:PlatformCdnUrl/platform/$Version" +} + +<# +.SYNOPSIS + Finds the latest platform version matching a major.minor pattern. +.DESCRIPTION + Searches the platform version index for versions matching the specified + major and minor version numbers, and returns the latest (highest) matching version. +.PARAMETER MajorMinor + The major.minor version pattern to match (e.g., '29.0'). +.OUTPUTS + The latest version string matching the major.minor pattern, or $null if no match found. +.EXAMPLE + Get-LatestPlatformVersion -MajorMinor '29.0' + Returns: '29.0.49913.0' (or whatever the latest 29.0.x.x version is) +#> +function Get-LatestPlatformVersion { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string] $MajorMinor + ) + + $availableVersions = Get-PlatformVersions + + # Parse the major.minor input + $parts = $MajorMinor.Split('.') + if ($parts.Count -lt 2) { + throw "Invalid MajorMinor format '$MajorMinor'. Expected format: 'major.minor' (e.g., '29.0')." + } + + $major = [int]$parts[0] + $minor = [int]$parts[1] + + # Filter versions matching major.minor and sort to find the latest + $matchingVersions = @($availableVersions | Where-Object { + try { + $ver = [System.Version]$_ + $ver.Major -eq $major -and $ver.Minor -eq $minor + } + catch { + $false + } + } | Sort-Object { [System.Version]$_ }) + + if ($matchingVersions.Count -eq 0) { + return $null + } + + return $matchingVersions[$matchingVersions.Count - 1] +} + +<# +.SYNOPSIS + Resolves a platform version setting to a full platform version. +.DESCRIPTION + Accepts either a full platform version (e.g. '29.0.49913.0') or a + major.minor pattern (e.g. '29.0'). When a major.minor pattern is given, + the highest available version matching that pattern is returned. +.PARAMETER Version + The platform version setting to resolve. Either a full version or a + major.minor pattern. +.OUTPUTS + The resolved full platform version string. +.EXAMPLE + Resolve-PlatformVersion -Version '29.0' + Returns: '29.0.49913.0' (the highest available 29.0.x.x version) +.EXAMPLE + Resolve-PlatformVersion -Version '29.0.49913.0' + Returns: '29.0.49913.0' +#> +function Resolve-PlatformVersion { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string] $Version + ) + + # A full version has 4 parts (major.minor.build.revision); a pattern has only major.minor + if ($Version.Split('.').Count -eq 2) { + $resolvedVersion = Get-LatestPlatformVersion -MajorMinor $Version + if ($null -eq $resolvedVersion) { + throw "No platform version found matching major.minor '$Version'." + } + return $resolvedVersion + } + + return $Version +} + +<# +.SYNOPSIS + Clears the cached platform version index. +.DESCRIPTION + Clears the in-memory cache of the platform version index, forcing a + fresh download on the next call to Get-PlatformVersions. +#> +function Clear-PlatformVersionCache { + [CmdletBinding()] + param() + + $script:PlatformVersionsCache = $null +} + +Export-ModuleMember -Function @( + 'Get-PlatformVersions', + 'Get-PlatformVersionUrl', + 'Get-LatestPlatformVersion', + 'Resolve-PlatformVersion', + 'Clear-PlatformVersionCache' +) diff --git a/build/scripts/tests/AppObjectValidation.Test.ps1 b/build/scripts/tests/AppObjectValidation.Test.ps1 new file mode 100644 index 00000000000..da4290b9ebc --- /dev/null +++ b/build/scripts/tests/AppObjectValidation.Test.ps1 @@ -0,0 +1,284 @@ +Describe "AppObjectValidation" { + BeforeAll { + Import-Module "$PSScriptRoot\..\AppObjectValidation.psm1" -Force + + $script:AllowedRanges = @( + [PSCustomObject]@{ From = 1; To = 49999 }, + [PSCustomObject]@{ From = 99000750; To = 99001048 } + ) + + function New-TestAlFile { + param( + [Parameter(Mandatory = $true)] [string] $Path, + [Parameter(Mandatory = $true)] [string] $Declaration + ) + + $directory = Split-Path -Path $Path -Parent + New-Item -ItemType Directory -Path $directory -Force | Out-Null + "$Declaration`r`n{`r`n}`r`n" | Set-Content -Path $Path -Encoding UTF8 + return $Path + } + + function New-ValidationLayout { + $root = Join-Path $TestDrive ([System.Guid]::NewGuid().ToString('N')) + $source = Join-Path $root 'src' + $projects = Join-Path $root 'build\projects\Apps W1\.AL-Go' + $production = Join-Path $source 'Apps\W1\Example\App' + $countryProduction = Join-Path $source 'Apps\GB\Example\App' + $testApp = Join-Path $source 'Apps\W1\Example\Test' + $baseApp = Join-Path $source 'Layers\W1\BaseApp' + $countryBaseApp = Join-Path $source 'Layers\GB\BaseApp' + $businessFoundationApp = Join-Path $source 'Business Foundation\App' + $systemApplicationApp = Join-Path $source 'System Application\App' + + New-Item -ItemType Directory -Path $production, $countryProduction, $testApp, $baseApp, $countryBaseApp, $businessFoundationApp, $systemApplicationApp, $projects -Force | Out-Null + @{ + testFolders = @('../../../src/Apps/W1/Example/Test') + } | ConvertTo-Json | Set-Content -Path (Join-Path $projects 'settings.json') -Encoding UTF8 + @{ projects = @{} } | ConvertTo-Json | Set-Content -Path (Join-Path $root 'build\projects.json') -Encoding UTF8 + + return [PSCustomObject]@{ + Root = $root + Source = $source + Production = $production + CountryProduction = $countryProduction + TestApp = $testApp + BaseApp = $baseApp + CountryBaseApp = $countryBaseApp + BusinessFoundationApp = $businessFoundationApp + SystemApplicationApp = $systemApplicationApp + Projects = (Join-Path $root 'build\projects') + ProjectsJson = (Join-Path $root 'build\projects.json') + ValidationRoots = @($baseApp, $countryBaseApp, $businessFoundationApp, $systemApplicationApp, (Join-Path $source 'Apps')) + } + } + + function Invoke-AddedFileValidation { + param( + [Parameter(Mandatory = $true)] [object] $Layout, + [Parameter(Mandatory = $true)] [string[]] $FilePaths + ) + + $testFolders = Get-ALGoTestFolders -ProjectsPath $Layout.Projects -ProjectsJsonPath $Layout.ProjectsJson -RepositoryRoot $Layout.Root + Test-ObjectIDsInAddedALFilesAreInAllowedRange -FilePaths $FilePaths -SourceCodePaths $Layout.ValidationRoots -TestFolderPaths $testFolders -AllowedRanges $script:AllowedRanges + } + } + + Context "Test-IsObjectIdInAllowedRange" { + It "accepts both boundaries of each allowed range" { + Test-IsObjectIdInAllowedRange -ObjectId 1 -AllowedRanges $script:AllowedRanges | Should -BeTrue + Test-IsObjectIdInAllowedRange -ObjectId 49999 -AllowedRanges $script:AllowedRanges | Should -BeTrue + Test-IsObjectIdInAllowedRange -ObjectId 99000750 -AllowedRanges $script:AllowedRanges | Should -BeTrue + Test-IsObjectIdInAllowedRange -ObjectId 99001048 -AllowedRanges $script:AllowedRanges | Should -BeTrue + } + + It "rejects IDs outside the allowed ranges" { + Test-IsObjectIdInAllowedRange -ObjectId 50000 -AllowedRanges $script:AllowedRanges | Should -BeFalse + Test-IsObjectIdInAllowedRange -ObjectId 70000000 -AllowedRanges $script:AllowedRanges | Should -BeFalse + Test-IsObjectIdInAllowedRange -ObjectId 99001049 -AllowedRanges $script:AllowedRanges | Should -BeFalse + } + } + + Context "Get-FilesCollection" { + It "keeps the existing default object type behavior" { + $layout = New-ValidationLayout + New-TestAlFile -Path (Join-Path $layout.Production 'Table.al') -Declaration 'table 30000 "Table"' + New-TestAlFile -Path (Join-Path $layout.Production 'Extension.al') -Declaration 'tableextension 30001 "Extension" extends "Table"' + + $objects = Get-FilesCollection -SourceCodePaths $layout.Production + + $objects.ObjectSignatures.ContainsKey('table 30000') | Should -BeTrue + $objects.ObjectSignatures.ContainsKey('tableextension 30001') | Should -BeFalse + } + } + + Context "Get-ALGoTestFolders" { + It "resolves configured test folders to absolute paths" { + $layout = New-ValidationLayout + + $testFolders = Get-ALGoTestFolders -ProjectsPath $layout.Projects + + $testFolders | Should -Contain ([System.IO.Path]::GetFullPath($layout.TestApp)) + } + + It "treats a trailing wildcard as the containing test folder" { + $layout = New-ValidationLayout + $settingsPath = Join-Path $layout.Projects 'System\.AL-Go' + New-Item -ItemType Directory -Path $settingsPath -Force | Out-Null + @{ + testFolders = @('../../../src/System Application/Test/*') + } | ConvertTo-Json | Set-Content -Path (Join-Path $settingsPath 'settings.json') -Encoding UTF8 + + $testFolders = Get-ALGoTestFolders -ProjectsPath $layout.Projects + + $expected = Join-Path $layout.Source 'System Application\Test' + $testFolders | Should -Contain ([System.IO.Path]::GetFullPath($expected)) + } + + It "includes projects canonically marked as tests even when they are AL-Go app folders" { + $layout = New-ValidationLayout + $testUtility = Join-Path $layout.Source 'Apps\W1\LibraryNoTransactions\app' + New-Item -ItemType Directory -Path $testUtility -Force | Out-Null + @{ + projects = @{ + 'Library-NoTransactions' = @{ + projectPath = '$env:INETROOT\App\Apps\W1\LibraryNoTransactions\app' + isTest = $true + } + } + } | ConvertTo-Json -Depth 5 | Set-Content -Path $layout.ProjectsJson -Encoding UTF8 + + $testFolders = Get-ALGoTestFolders -ProjectsPath $layout.Projects -ProjectsJsonPath $layout.ProjectsJson -RepositoryRoot $layout.Root + + $testFolders | Should -Contain ([System.IO.Path]::GetFullPath($testUtility)) + } + + It "resolves test layer sources from canonical appJsonPath metadata" { + $layout = New-ValidationLayout + $layerTest = Join-Path $layout.Source 'Layers\W1\Tests\Bank' + New-Item -ItemType Directory -Path $layerTest -Force | Out-Null + '{}' | Set-Content -Path (Join-Path $layerTest 'app.json') -Encoding UTF8 + @{ + projects = @{ + 'Tests-Bank' = @{ + projectPath = '$env:INETROOT\App\Views\$CountryCode\Tests\Bank' + appJsonPath = '$env:INETROOT\App\Layers\W1\Tests\Bank\app.json' + isTest = $true + } + } + } | ConvertTo-Json -Depth 5 | Set-Content -Path $layout.ProjectsJson -Encoding UTF8 + + $testFolders = Get-ALGoTestFolders -ProjectsPath $layout.Projects -ProjectsJsonPath $layout.ProjectsJson -RepositoryRoot $layout.Root + + $testFolders | Should -Contain ([System.IO.Path]::GetFullPath($layerTest)) + } + } + + Context "Test-ObjectIDsInAddedALFilesAreInAllowedRange" { + It "accepts objects in newly added W1 and country files when their IDs are allowed" { + $layout = New-ValidationLayout + $w1File = New-TestAlFile -Path (Join-Path $layout.Production 'W1.al') -Declaration 'table 49999 "W1"' + $countryFile = New-TestAlFile -Path (Join-Path $layout.CountryProduction 'GB.al') -Declaration 'pageextension 99000750 "GB" extends "Customer Card"' + + { Invoke-AddedFileValidation -Layout $layout -FilePaths @($w1File, $countryFile) } | Should -Not -Throw + } + + It "rejects an out-of-range object in a newly added W1 file" { + $layout = New-ValidationLayout + $file = New-TestAlFile -Path (Join-Path $layout.Production 'Invalid.al') -Declaration 'table 50000 "Invalid"' + + { Invoke-AddedFileValidation -Layout $layout -FilePaths @($file) } | Should -Throw + } + + It "rejects an out-of-range object in a newly added country file" { + $layout = New-ValidationLayout + $file = New-TestAlFile -Path (Join-Path $layout.CountryProduction 'Invalid.al') -Declaration 'pageextension 50000 "Invalid GB" extends "Customer Card"' + + { Invoke-AddedFileValidation -Layout $layout -FilePaths @($file) } | Should -Throw + } + + It "checks newly added objects in all country BaseApps, Business Foundation, and System Application" { + $layout = New-ValidationLayout + $baseAppFile = New-TestAlFile -Path (Join-Path $layout.BaseApp 'Invalid.al') -Declaration 'table 50000 "Invalid BaseApp"' + $countryBaseAppFile = New-TestAlFile -Path (Join-Path $layout.CountryBaseApp 'Invalid.al') -Declaration 'tableextension 50001 "Invalid GB BaseApp" extends "Customer"' + $businessFoundationFile = New-TestAlFile -Path (Join-Path $layout.BusinessFoundationApp 'Invalid.al') -Declaration 'page 50001 "Invalid Business Foundation"' + $systemApplicationFile = New-TestAlFile -Path (Join-Path $layout.SystemApplicationApp 'Invalid.al') -Declaration 'codeunit 50002 "Invalid System Application"' + + $errorRecord = $null + try { + Invoke-AddedFileValidation -Layout $layout -FilePaths @($baseAppFile, $countryBaseAppFile, $businessFoundationFile, $systemApplicationFile) + } + catch { + $errorRecord = $_ + } + + $errorRecord | Should -Not -BeNullOrEmpty + $errorRecord.Exception.Message | Should -Match '4 object\(s\)' + } + + It "excludes a table in a test app without relying on Subtype Test" { + $layout = New-ValidationLayout + $file = New-TestAlFile -Path (Join-Path $layout.TestApp 'TestTable.al') -Declaration 'table 139560 "Test Table"' + + { Invoke-AddedFileValidation -Layout $layout -FilePaths @($file) } | Should -Not -Throw + } + + It "excludes an extension in a test app without relying on Subtype Test" { + $layout = New-ValidationLayout + $file = New-TestAlFile -Path (Join-Path $layout.TestApp 'TestPageExt.al') -Declaration 'pageextension 139561 "Test Extension" extends "Customer Card"' + + { Invoke-AddedFileValidation -Layout $layout -FilePaths @($file) } | Should -Not -Throw + } + + It "excludes a non-codeunit object when its owning manifest identifies a test app" { + $layout = New-ValidationLayout + $unconfiguredTestApp = Join-Path $layout.Source 'Apps\W1\Example\Unconfigured' + New-Item -ItemType Directory -Path $unconfiguredTestApp -Force | Out-Null + @{ + id = [System.Guid]::NewGuid() + name = 'Example Test Library' + publisher = 'Microsoft' + version = '1.0.0.0' + } | ConvertTo-Json | Set-Content -Path (Join-Path $unconfiguredTestApp 'app.json') -Encoding UTF8 + $file = New-TestAlFile -Path (Join-Path $unconfiguredTestApp 'TestTable.al') -Declaration 'table 139560 "Test Table"' + + { Invoke-AddedFileValidation -Layout $layout -FilePaths @($file) } | Should -Not -Throw + } + + It "excludes a test utility whose manifest name does not contain test" { + $layout = New-ValidationLayout + $testUtility = Join-Path $layout.Source 'Apps\W1\LibraryNoTransactions\app' + New-Item -ItemType Directory -Path $testUtility -Force | Out-Null + @{ + projects = @{ + 'Library-NoTransactions' = @{ + projectPath = '$env:INETROOT\App\Apps\W1\LibraryNoTransactions\app' + isTest = $true + } + } + } | ConvertTo-Json -Depth 5 | Set-Content -Path $layout.ProjectsJson -Encoding UTF8 + $file = New-TestAlFile -Path (Join-Path $testUtility 'NoTransactionsSubscriber.Codeunit.al') -Declaration 'codeunit 130630 "No Transactions Subscriber"' + + { Invoke-AddedFileValidation -Layout $layout -FilePaths @($file) } | Should -Not -Throw + } + + It "ignores added files outside the configured source roots" { + $layout = New-ValidationLayout + $files = @( + (New-TestAlFile -Path (Join-Path $layout.Source 'Layers\W1\DemoTool\Invalid.al') -Declaration 'table 50000 "Demo Tool"') + (New-TestAlFile -Path (Join-Path $layout.Source 'Business Foundation\Test\Invalid.al') -Declaration 'table 50001 "Business Foundation Test"') + (New-TestAlFile -Path (Join-Path $layout.Source 'System Application\Test Library\Invalid.al') -Declaration 'table 50002 "System Application Test Library"') + (New-TestAlFile -Path (Join-Path $layout.Source 'Tools\Invalid.al') -Declaration 'table 50003 "Tool"') + (New-TestAlFile -Path (Join-Path $layout.Source 'GDL\Invalid.al') -Declaration 'table 50004 "GDL"') + (New-TestAlFile -Path (Join-Path $layout.Source 'DisabledTests\Invalid.al') -Declaration 'table 50005 "Disabled Test"') + ) + + { Invoke-AddedFileValidation -Layout $layout -FilePaths $files } | Should -Not -Throw + } + + It "ignores non-AL files" { + $layout = New-ValidationLayout + $file = Join-Path $layout.Production 'README.md' + 'table 50000 "Documentation example"' | Set-Content -Path $file -Encoding UTF8 + + { Invoke-AddedFileValidation -Layout $layout -FilePaths @($file) } | Should -Not -Throw + } + + It "reports every offending object before throwing" { + $layout = New-ValidationLayout + $first = New-TestAlFile -Path (Join-Path $layout.Production 'First.al') -Declaration 'table 50000 "First"' + $second = New-TestAlFile -Path (Join-Path $layout.CountryProduction 'Second.al') -Declaration 'page 60000 "Second"' + + $errorRecord = $null + try { + Invoke-AddedFileValidation -Layout $layout -FilePaths @($first, $second) + } + catch { + $errorRecord = $_ + } + + $errorRecord | Should -Not -BeNullOrEmpty + $errorRecord.Exception.Message | Should -Match '2 object\(s\)' + } + } +} diff --git a/build/scripts/tests/PlatformHelper.Test.ps1 b/build/scripts/tests/PlatformHelper.Test.ps1 new file mode 100644 index 00000000000..adbca55fef4 --- /dev/null +++ b/build/scripts/tests/PlatformHelper.Test.ps1 @@ -0,0 +1,138 @@ +$errorActionPreference = "Stop"; $ProgressPreference = "SilentlyContinue"; Set-StrictMode -Version 2.0 + +Import-Module (Join-Path $PSScriptRoot '../PlatformHelper.psm1') -Force + +Describe "PlatformHelper" { + BeforeAll { + $script:testVersions = @( + '28.0.12345.0', + '28.0.12346.0', + '28.1.54321.0', + '29.0.49913.0', + '29.0.49914.0', + '29.1.11111.0', + '30.0.10000.0' + ) + } + + BeforeEach { + Clear-PlatformVersionCache + } + + Describe "Get-PlatformVersions" { + It "Should fetch and return platform versions" { + Mock -ModuleName PlatformHelper -CommandName Invoke-WebRequest -MockWith { + return @{ + Content = $script:testVersions | ConvertTo-Json + } + } + + $versions = Get-PlatformVersions + $versions | Should -Not -BeNullOrEmpty + $versions.Count | Should -Be 7 + } + + It "Should cache versions on subsequent calls" { + Mock -ModuleName PlatformHelper -CommandName Invoke-WebRequest -MockWith { + return @{ + Content = $script:testVersions | ConvertTo-Json + } + } + + Get-PlatformVersions | Out-Null + Get-PlatformVersions | Out-Null + + Should -Invoke -ModuleName PlatformHelper -CommandName Invoke-WebRequest -Times 1 -Exactly + } + + It "Should refresh cache when Force is specified" { + Mock -ModuleName PlatformHelper -CommandName Invoke-WebRequest -MockWith { + return @{ + Content = $script:testVersions | ConvertTo-Json + } + } + + Get-PlatformVersions | Out-Null + Get-PlatformVersions -Force | Out-Null + + Should -Invoke -ModuleName PlatformHelper -CommandName Invoke-WebRequest -Times 2 -Exactly + } + + It "Should throw on network error" { + Mock -ModuleName PlatformHelper -CommandName Invoke-WebRequest -MockWith { + throw "Network error" + } + + { Get-PlatformVersions } | Should -Throw "*Failed to fetch platform version index*" + } + } + + Describe "Get-PlatformVersionUrl" { + BeforeEach { + Mock -ModuleName PlatformHelper -CommandName Invoke-WebRequest -MockWith { + return @{ + Content = $script:testVersions | ConvertTo-Json + } + } + } + + It "Should return correct URL for valid version" { + $url = Get-PlatformVersionUrl -Version '29.0.49913.0' + $url | Should -Be 'https://bcinsider-fvh2ekdjecfjd6gk.b02.azurefd.net/platform/29.0.49913.0' + } + + It "Should throw for invalid version" { + { Get-PlatformVersionUrl -Version '99.0.00000.0' } | Should -Throw "*is not available*" + } + } + + Describe "Get-LatestPlatformVersion" { + BeforeEach { + Mock -ModuleName PlatformHelper -CommandName Invoke-WebRequest -MockWith { + return @{ + Content = $script:testVersions | ConvertTo-Json + } + } + } + + It "Should return latest version for major.minor '29.0'" { + $version = Get-LatestPlatformVersion -MajorMinor '29.0' + $version | Should -Be '29.0.49914.0' + } + + It "Should return latest version for major.minor '28.0'" { + $version = Get-LatestPlatformVersion -MajorMinor '28.0' + $version | Should -Be '28.0.12346.0' + } + + It "Should return latest version for major.minor '28.1'" { + $version = Get-LatestPlatformVersion -MajorMinor '28.1' + $version | Should -Be '28.1.54321.0' + } + + It "Should return null for non-existent major.minor" { + $version = Get-LatestPlatformVersion -MajorMinor '99.0' + $version | Should -BeNullOrEmpty + } + + It "Should throw for invalid MajorMinor format" { + { Get-LatestPlatformVersion -MajorMinor '29' } | Should -Throw "*Invalid MajorMinor format*" + } + } + + Describe "Clear-PlatformVersionCache" { + It "Should clear the cache and force re-fetch" { + Mock -ModuleName PlatformHelper -CommandName Invoke-WebRequest -MockWith { + return @{ + Content = $script:testVersions | ConvertTo-Json + } + } + + Get-PlatformVersions | Out-Null + Clear-PlatformVersionCache + Get-PlatformVersions | Out-Null + + Should -Invoke -ModuleName PlatformHelper -CommandName Invoke-WebRequest -Times 2 -Exactly + } + } +} From 4a2b8c0f46e2cb15ed2769514ed5b09b1f3cc101 Mon Sep 17 00:00:00 2001 From: Maria Zhelezova <43066499+mazhelez@users.noreply.github.com> Date: Mon, 16 Nov 2026 11:45:10 +0100 Subject: [PATCH 3/6] Use the real pinned checkout SHA in HowToAddAnAutomation examples Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/actions/RunAutomation/HowToAddAnAutomation.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/actions/RunAutomation/HowToAddAnAutomation.md b/.github/actions/RunAutomation/HowToAddAnAutomation.md index 48a00fdcead..1528b1be805 100644 --- a/.github/actions/RunAutomation/HowToAddAnAutomation.md +++ b/.github/actions/RunAutomation/HowToAddAnAutomation.md @@ -27,12 +27,12 @@ fail-fast: false steps: - name: Checkout - uses: actions/checkout@ # + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: ref: ${{ matrix.branch }} - name: Checkout actions - uses: actions/checkout@ # + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: path: _actions sparse-checkout: | @@ -54,7 +54,7 @@ updateBranches: ${{ steps.getOfficialBranches.outputs.branchesJson }} steps: - name: Checkout - uses: actions/checkout@ # + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Get Official Branches id: getOfficialBranches From 7c93ee3066c00330f06487ff82f1d5d628907ca7 Mon Sep 17 00:00:00 2001 From: Maria Zhelezova <43066499+mazhelez@users.noreply.github.com> Date: Wed, 18 Nov 2026 08:11:44 +0100 Subject: [PATCH 4/6] Trim synced actions to those used on release branches Workflows that only run on schedule/workflow_dispatch execute from main, so the copies of their actions and build scripts are not needed here. Keep only the actions used by workflows that run on this branch (identical to main) and revert the rest to the base branch. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../actions/CleanUpStalePRChecks/action.ps1 | 16 +- .github/actions/GetGitBranches/action.yaml | 2 +- .../LabelPRsAwaitingApproval/action.ps1 | 216 ------------------ .../LabelPRsAwaitingApproval/action.yaml | 34 --- .../RunAutomation/HowToAddAnAutomation.md | 21 +- .../RunAutomation/SubmitStabilityJob/run.ps1 | 6 +- .../RunAutomation/UpdateAppBaselines/run.ps1 | 2 +- .../UpdatePlatformVersion/run.ps1 | 29 --- .../UpdateSystemFilesSchedule/run.ps1 | 93 -------- .github/actions/RunAutomation/run.ps1 | 11 +- .../TestObsoleteTagPreprocessors/action.ps1 | 34 --- .../TestObsoleteTagPreprocessors/action.yaml | 13 -- .../actions/UpdateUnstableTests/action.ps1 | 51 ----- .../actions/UpdateUnstableTests/action.yaml | 49 ---- .../UpdateUnstableTestsCombined/action.ps1 | 81 ------- .../UpdateUnstableTestsCombined/action.yaml | 68 ------ .../ValidateCountryProjects/action.ps1 | 6 - .../ValidateCountryProjects/action.yaml | 13 -- .github/actions/VerifyMiappSync/action.ps1 | 5 - .github/actions/VerifyMiappSync/action.yaml | 13 -- build/scripts/AutomatedSubmission.psm1 | 9 +- build/scripts/EnlistmentHelperFunctions.psm1 | 47 +--- build/scripts/PlatformHelper.psm1 | 179 --------------- build/scripts/tests/PlatformHelper.Test.ps1 | 138 ----------- 24 files changed, 18 insertions(+), 1118 deletions(-) delete mode 100644 .github/actions/LabelPRsAwaitingApproval/action.ps1 delete mode 100644 .github/actions/LabelPRsAwaitingApproval/action.yaml delete mode 100644 .github/actions/RunAutomation/UpdatePlatformVersion/run.ps1 delete mode 100644 .github/actions/RunAutomation/UpdateSystemFilesSchedule/run.ps1 delete mode 100644 .github/actions/TestObsoleteTagPreprocessors/action.ps1 delete mode 100644 .github/actions/TestObsoleteTagPreprocessors/action.yaml delete mode 100644 .github/actions/UpdateUnstableTests/action.ps1 delete mode 100644 .github/actions/UpdateUnstableTests/action.yaml delete mode 100644 .github/actions/UpdateUnstableTestsCombined/action.ps1 delete mode 100644 .github/actions/UpdateUnstableTestsCombined/action.yaml delete mode 100644 .github/actions/ValidateCountryProjects/action.ps1 delete mode 100644 .github/actions/ValidateCountryProjects/action.yaml delete mode 100644 .github/actions/VerifyMiappSync/action.ps1 delete mode 100644 .github/actions/VerifyMiappSync/action.yaml delete mode 100644 build/scripts/PlatformHelper.psm1 delete mode 100644 build/scripts/tests/PlatformHelper.Test.ps1 diff --git a/.github/actions/CleanUpStalePRChecks/action.ps1 b/.github/actions/CleanUpStalePRChecks/action.ps1 index b830dfc93c3..32787096001 100644 --- a/.github/actions/CleanUpStalePRChecks/action.ps1 +++ b/.github/actions/CleanUpStalePRChecks/action.ps1 @@ -21,7 +21,7 @@ if ($WhatIf) { Write-Host "Fetching open pull requests..." # Get all open pull requests with mergeable state -$prs = @(gh pr list --state open --json number,title,url,mergeable --limit 1000 | ConvertFrom-Json) +$prs = gh pr list --state open --json number,title,url,mergeable --limit 1000 | ConvertFrom-Json Write-Host "Found $($prs.Count) open pull requests" @@ -32,18 +32,15 @@ if ($prs.Count -eq 0) { $now = [DateTime]::UtcNow $restarted = 0 -$skipped = 0 $failed = 0 foreach ($pr in $prs) { Write-Host "" Write-Host "Checking PR #$($pr.number): $($pr.title)" - # Skip PRs with merge conflicts - they need manual resolution first - # Process PRs in MERGEABLE and UNKNOWN states (UNKNOWN means GitHub hasn't computed mergeability yet) - if ($pr.mergeable -eq "CONFLICTING") { - Write-Host " PR has merge conflicts (state: CONFLICTING), skipping" - $skipped++ + # Check if PR is mergeable + if ($pr.mergeable -ne "MERGEABLE") { + Write-Host " PR is not in MERGEABLE state (current: $($pr.mergeable)), skipping" continue } @@ -65,7 +62,6 @@ foreach ($pr in $prs) { if (-not $statusCheck) { Write-Host " No 'Pull Request Status Check' found for this PR" - $skipped++ continue } @@ -74,7 +70,6 @@ foreach ($pr in $prs) { # Check if the check is completed and successful if ($statusCheck.state -ne "SUCCESS") { Write-Host " Check state is '$($statusCheck.state)', not 'SUCCESS', skipping" - $skipped++ continue } @@ -159,7 +154,6 @@ This will automatically trigger a new **Pull Request Build** workflow run. Write-Host "" Write-Host "Summary:" Write-Host " ✓ Successfully processed: $restarted PR(s)" -Write-Host " ↷ Skipped: $skipped PR(s)" Write-Host " ✗ Failed to process: $failed PR(s)" # Add GitHub Actions job summary @@ -175,7 +169,6 @@ if ($env:GITHUB_STEP_SUMMARY) { else { Add-Content -Path $env:GITHUB_STEP_SUMMARY -Value "- ✓ Successfully processed: **$restarted** PR(s) (deleted stale workflow runs and added comments)" } - Add-Content -Path $env:GITHUB_STEP_SUMMARY -Value "- ↷ Skipped: **$skipped** PR(s) (non-mergeable, no status check, or check not successful)" Add-Content -Path $env:GITHUB_STEP_SUMMARY -Value "- ✗ Failed to process: **$failed** PR(s)" } @@ -184,4 +177,3 @@ if ($failed -gt 0 -and -not $WhatIf) { Write-Host "::error::Failed to process $failed PR(s)" exit 1 } -exit 0 diff --git a/.github/actions/GetGitBranches/action.yaml b/.github/actions/GetGitBranches/action.yaml index 36c520c58eb..e5476da0c40 100644 --- a/.github/actions/GetGitBranches/action.yaml +++ b/.github/actions/GetGitBranches/action.yaml @@ -18,7 +18,7 @@ runs: using: composite steps: - name: Checkout - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + uses: actions/checkout@v4 - name: run shell: pwsh diff --git a/.github/actions/LabelPRsAwaitingApproval/action.ps1 b/.github/actions/LabelPRsAwaitingApproval/action.ps1 deleted file mode 100644 index d6e7ef94ae6..00000000000 --- a/.github/actions/LabelPRsAwaitingApproval/action.ps1 +++ /dev/null @@ -1,216 +0,0 @@ -param ( - [Parameter(Mandatory = $false, HelpMessage = "Label to manage on PRs awaiting workflow approval")] - [string] $Label = 'needs-approval', - [Parameter(Mandatory = $false, HelpMessage = "Dry-run mode - log changes without applying them")] - [switch] $WhatIf -) - -$ErrorActionPreference = "Stop" -$ProgressPreference = "SilentlyContinue" -Set-StrictMode -Version 2.0 - -$repo = $env:GITHUB_REPOSITORY -if (-not $repo) { - throw "GITHUB_REPOSITORY environment variable is not set" -} - -if ($WhatIf) { - Write-Host "::notice::Running in WhatIf mode - no label changes will be applied" -} - -function Invoke-GhApi { - param ( - [Parameter(Mandatory = $true)] [string[]] $Arguments, - [int] $MaxRetries = 3 - ) - for ($attempt = 1; $attempt -le $MaxRetries; $attempt++) { - $stderrFile = [System.IO.Path]::GetTempFileName() - try { - # Redirect stderr to a temp file so deprecation notices / warnings - # don't get prepended to stdout and break ConvertFrom-Json. - $stdout = & gh api @Arguments 2>$stderrFile - if ($LASTEXITCODE -eq 0) { - $stderrText = Get-Content -Path $stderrFile -Raw -ErrorAction SilentlyContinue - if ($stderrText -and $stderrText.Trim()) { - Write-Host " gh api stderr: $($stderrText.Trim())" - } - return $stdout - } - $stderrText = Get-Content -Path $stderrFile -Raw -ErrorAction SilentlyContinue - throw "gh api failed (exit $LASTEXITCODE): $stderrText" - } - catch { - if ($attempt -eq $MaxRetries) { throw } - Start-Sleep -Seconds ([Math]::Pow(2, $attempt)) - } - finally { - Remove-Item -Path $stderrFile -ErrorAction SilentlyContinue - } - } -} - -function Ensure-Label { - param ([string] $Name) - $stderrFile = [System.IO.Path]::GetTempFileName() - try { - & gh api "repos/$repo/labels/$([Uri]::EscapeDataString($Name))" 2>$stderrFile | Out-Null - if ($LASTEXITCODE -eq 0) { - Write-Host "Label '$Name' exists" - return - } - $errText = Get-Content -Path $stderrFile -Raw -ErrorAction SilentlyContinue - # Only treat genuine "not found" responses as a signal to create the - # label. Other failures (rate limiting, 5xx, network) should bubble - # up so they're not masked as a missing-label condition. - if ($errText -notmatch 'HTTP 404|Not Found') { - throw "Unexpected error checking label '$Name' (exit $LASTEXITCODE): $errText" - } - Write-Host "Label '$Name' not found - creating it" - if ($WhatIf) { - Write-Host " [WhatIf] Would create label '$Name'" - return - } - & gh label create $Name --repo $repo --color 'FBCA04' --description 'Workflow runs require maintainer approval to start' 2>&1 | Out-Null - if ($LASTEXITCODE -ne 0) { - throw "Failed to create label '$Name'" - } - } - finally { - Remove-Item -Path $stderrFile -ErrorAction SilentlyContinue - } -} - -function Get-AwaitingApprovalPRs { - Write-Host "" - Write-Host "Fetching open PRs in $repo (for head-SHA mapping)..." - # With --paginate, gh runs the --jq filter against each page and emits the - # results concatenated. We use a filter that emits one JSON object per - # line, and parse them individually below (NDJSON style) - this avoids - # the "multiple JSON arrays concatenated" problem that breaks - # ConvertFrom-Json. - $prsJson = Invoke-GhApi -Arguments @('--paginate', "repos/$repo/pulls?state=open&per_page=100", '--jq', '.[] | {number: .number, sha: .head.sha}') - $openPRs = @($prsJson | Where-Object { $_ -and $_.ToString().Trim() } | ForEach-Object { $_ | ConvertFrom-Json }) - Write-Host "Found $($openPRs.Count) open PR(s)" - - # Map of current PR head SHA -> list of PR numbers. We match action_required - # runs against the *current* head only, so PRs with stale action_required - # runs from older commits (whose newer commits have been approved) are not - # falsely flagged. A list (rather than a single PR) handles the edge case - # where multiple open PRs share the same head SHA (e.g. one PR per base - # branch from a single commit). - $headShaToPRs = @{} - foreach ($pr in $openPRs) { - if ($pr.sha) { - if (-not $headShaToPRs.ContainsKey($pr.sha)) { - $headShaToPRs[$pr.sha] = [System.Collections.Generic.List[int]]::new() - } - $headShaToPRs[$pr.sha].Add([int]$pr.number) - } - } - - Write-Host "" - Write-Host "Fetching workflow runs with status=action_required..." - $runsJson = Invoke-GhApi -Arguments @('--paginate', "repos/$repo/actions/runs?status=action_required&per_page=100", '--jq', '.workflow_runs[]') - $runs = @($runsJson | Where-Object { $_ -and $_.ToString().Trim() } | ForEach-Object { $_ | ConvertFrom-Json }) - Write-Host "Found $($runs.Count) action_required workflow run(s)" - - $awaiting = [System.Collections.Generic.HashSet[int]]::new() - foreach ($run in $runs) { - if (($run.PSObject.Properties.Name -contains 'head_sha') -and $run.head_sha -and $headShaToPRs.ContainsKey($run.head_sha)) { - foreach ($prNum in $headShaToPRs[$run.head_sha]) { - [void]$awaiting.Add($prNum) - } - } - } - - # Comma prevents PowerShell from unrolling the HashSet (which would - # turn an empty set into $null at the call site). - return ,$awaiting -} - -function Get-LabeledPRs { - param ([string] $LabelName) - Write-Host "" - Write-Host "Fetching open PRs currently labelled '$LabelName'..." - $encoded = [Uri]::EscapeDataString($LabelName) - $json = Invoke-GhApi -Arguments @('--paginate', "repos/$repo/issues?state=open&labels=$encoded&per_page=100", '--jq', '.[] | select(.pull_request) | .number') - $set = [System.Collections.Generic.HashSet[int]]::new() - foreach ($n in @($json | Where-Object { $_ -and $_.ToString().Trim() -match '^\d+$' })) { - [void]$set.Add([int]$n) - } - Write-Host "Found $($set.Count) PR(s) with label '$LabelName'" - return ,$set -} - -# --- Main --- - -Ensure-Label -Name $Label -$awaitingPRs = Get-AwaitingApprovalPRs -$labeledPRs = Get-LabeledPRs -LabelName $Label - -if ($awaitingPRs.Count -gt 0) { - Write-Host "" - Write-Host "PRs awaiting approval:" - $awaitingPRs | Sort-Object | ForEach-Object { Write-Host " - #$_" } -} - -$toAdd = @($awaitingPRs | Where-Object { -not $labeledPRs.Contains($_) } | Sort-Object) -$toRemove = @($labeledPRs | Where-Object { -not $awaitingPRs.Contains($_) } | Sort-Object) - -Write-Host "" -Write-Host "Plan: add '$Label' to $($toAdd.Count) PR(s), remove from $($toRemove.Count) PR(s)" - -$added = 0; $removed = 0; $failed = 0 - -foreach ($pr in $toAdd) { - Write-Host " + Add '$Label' to PR #$pr" - if ($WhatIf) { $added++; continue } - try { - & gh pr edit $pr --repo $repo --add-label $Label 2>&1 | Out-Null - if ($LASTEXITCODE -ne 0) { throw "gh pr edit exited with $LASTEXITCODE" } - $added++ - } - catch { - Write-Host " ::warning::Failed to add label to PR #${pr}: $_" - $failed++ - } -} - -foreach ($pr in $toRemove) { - Write-Host " - Remove '$Label' from PR #$pr" - if ($WhatIf) { $removed++; continue } - try { - & gh pr edit $pr --repo $repo --remove-label $Label 2>&1 | Out-Null - if ($LASTEXITCODE -ne 0) { throw "gh pr edit exited with $LASTEXITCODE" } - $removed++ - } - catch { - Write-Host " ::warning::Failed to remove label from PR #${pr}: $_" - $failed++ - } -} - -Write-Host "" -Write-Host "Summary:" -Write-Host " PRs awaiting approval: $($awaitingPRs.Count)" -Write-Host " Labels added: $added" -Write-Host " Labels removed: $removed" -Write-Host " Failures: $failed" - -if ($env:GITHUB_STEP_SUMMARY) { - $title = if ($WhatIf) { "## PRs Awaiting Approval - Label Sync (WhatIf)" } else { "## PRs Awaiting Approval - Label Sync" } - Add-Content -Path $env:GITHUB_STEP_SUMMARY -Value $title - Add-Content -Path $env:GITHUB_STEP_SUMMARY -Value "" - Add-Content -Path $env:GITHUB_STEP_SUMMARY -Value "- Label: ``$Label``" - Add-Content -Path $env:GITHUB_STEP_SUMMARY -Value "- PRs awaiting approval: **$($awaitingPRs.Count)**" - Add-Content -Path $env:GITHUB_STEP_SUMMARY -Value "- Labels added: **$added**" - Add-Content -Path $env:GITHUB_STEP_SUMMARY -Value "- Labels removed: **$removed**" - if ($failed -gt 0) { - Add-Content -Path $env:GITHUB_STEP_SUMMARY -Value "- Failures: **$failed**" - } -} - -if ($failed -gt 0 -and -not $WhatIf) { - Write-Host "::error::Encountered $failed label operation failure(s)" - exit 1 -} diff --git a/.github/actions/LabelPRsAwaitingApproval/action.yaml b/.github/actions/LabelPRsAwaitingApproval/action.yaml deleted file mode 100644 index 0489b3becb5..00000000000 --- a/.github/actions/LabelPRsAwaitingApproval/action.yaml +++ /dev/null @@ -1,34 +0,0 @@ -name: Label PRs Awaiting Workflow Approval -author: Microsoft Corporation -description: Adds or removes a label on open PRs based on whether they have workflow runs in the 'action_required' state (waiting for maintainer approval). -inputs: - token: - description: The GitHub token running the action - required: false - default: ${{ github.token }} - label: - description: The label to add to PRs that have workflow runs awaiting approval - required: false - default: 'needs-approval' - whatIf: - description: If 'true', logs intended changes without applying them - required: false - default: 'false' -runs: - using: composite - steps: - - name: Sync 'needs-approval' label - shell: pwsh - env: - GH_TOKEN: ${{ inputs.token }} - GITHUB_REPOSITORY: ${{ github.repository }} - ACTION_LABEL: ${{ inputs.label }} - ACTION_WHATIF: ${{ inputs.whatIf }} - ACTION_PATH: ${{ github.action_path }} - run: | - $whatIfSwitch = @{} - if ($env:ACTION_WHATIF -eq 'true') { $whatIfSwitch['WhatIf'] = $true } - & "$env:ACTION_PATH/action.ps1" -Label $env:ACTION_LABEL @whatIfSwitch -branding: - icon: tag - color: yellow diff --git a/.github/actions/RunAutomation/HowToAddAnAutomation.md b/.github/actions/RunAutomation/HowToAddAnAutomation.md index 1528b1be805..750dd40258f 100644 --- a/.github/actions/RunAutomation/HowToAddAnAutomation.md +++ b/.github/actions/RunAutomation/HowToAddAnAutomation.md @@ -1,8 +1,5 @@ # How to add a new automation -> [!NOTE] -> Automations run through `RunAutomation` are automatically skipped on branches that are out of support (branches with the "Branch is out of support" ruleset). No pull request is created for those branches, so you don't need to handle this in your automation. - 1. Create a folder in `.github\actions\RunAutomations`. The name of the folder is the name of the automation, e.g. "_UpdateAppBaselines_". 2. Create a `run.ps1` file in the new folder. It should contain the script with the automation's logic. - The script can accept the following parameters: @@ -12,7 +9,6 @@ - `Files`: Files changed by the automation that will be included in the pull request. - `Message`: Message to display as an automaton result and use as commit message and pull request description. 3. Create a new workflow in `.github\workflows` to run your new automation. - - Reference the actions in this repository locally (`./...`) rather than as `microsoft/BCApps/...@main`, so the action code always matches the workflow's commit. Local actions require the repository to be checked out first. When the job checks out another branch (e.g. `${{ matrix.branch }}`), check out the workflow's own commit into `_actions` and reference the action from there. - Add a job to run the script: ```yaml AutomationJob: @@ -27,20 +23,12 @@ fail-fast: false steps: - name: Checkout - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + uses: actions/checkout@v4 with: ref: ${{ matrix.branch }} - - name: Checkout actions - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - path: _actions - sparse-checkout: | - .github/actions - build/scripts - - name: - uses: ./_actions/.github/actions/RunAutomation + uses: microsoft/BCApps/.github/actions/RunAutomation@main with: automations: targetBranch: ${{ matrix.branch }} @@ -53,12 +41,9 @@ outputs: updateBranches: ${{ steps.getOfficialBranches.outputs.branchesJson }} steps: - - name: Checkout - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - name: Get Official Branches id: getOfficialBranches - uses: ./.github/actions/GetGitBranches + uses: mazhelez/BCApps/.github/actions/GetGitBranches@main with: include: "['main', 'releases/*']" ``` diff --git a/.github/actions/RunAutomation/SubmitStabilityJob/run.ps1 b/.github/actions/RunAutomation/SubmitStabilityJob/run.ps1 index 76022e2e8b1..63d999dd75f 100644 --- a/.github/actions/RunAutomation/SubmitStabilityJob/run.ps1 +++ b/.github/actions/RunAutomation/SubmitStabilityJob/run.ps1 @@ -5,11 +5,11 @@ param ( $repository = $runParameters.Repository $targetBranch = $runParameters.TargetBranch -$workflowName = "CICD.yaml" +$workflowName = " CI/CD" $workflowRunTime = Get-Date -AsUTC Write-Host "Running the workflow '$workflowName' on branch $targetBranch" -gh workflow run --repo $repository --ref $targetBranch $workflowName | Out-Null +gh workflow run --repo $repository --ref $targetBranch $workflowName # Get the workflow run URL to display in the message @@ -32,4 +32,4 @@ if ($workflowRun.createdAt -gt $workflowRunTime) { $result.Message = "'$workflowName' workflow started: $($workflowRun.url)" } -return $result +return $result \ No newline at end of file diff --git a/.github/actions/RunAutomation/UpdateAppBaselines/run.ps1 b/.github/actions/RunAutomation/UpdateAppBaselines/run.ps1 index 14880646dfa..39e3c49bd6b 100644 --- a/.github/actions/RunAutomation/UpdateAppBaselines/run.ps1 +++ b/.github/actions/RunAutomation/UpdateAppBaselines/run.ps1 @@ -9,7 +9,7 @@ Install-Module -Name BcContainerHelper -AllowPrerelease -Force Import-Module BcContainerHelper -DisableNameChecking Import-Module $PSScriptRoot\..\..\..\..\build\scripts\EnlistmentHelperFunctions.psm1 -$newVersion = Update-PackageVersion -PackageName "AppBaselines-BCArtifacts" -Branch $runParameters.TargetBranch +$newVersion = Update-PackageVersion -PackageName "AppBaselines-BCArtifacts" $result = @{ 'Files' = @() diff --git a/.github/actions/RunAutomation/UpdatePlatformVersion/run.ps1 b/.github/actions/RunAutomation/UpdatePlatformVersion/run.ps1 deleted file mode 100644 index ea45b3e8bb3..00000000000 --- a/.github/actions/RunAutomation/UpdatePlatformVersion/run.ps1 +++ /dev/null @@ -1,29 +0,0 @@ -[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', 'runParameters', Justification = 'The parameter is always passed to the script')] -param ( - [Parameter(Mandatory=$true)] - $runParameters -) - -Import-Module $PSScriptRoot\..\..\..\..\build\scripts\EnlistmentHelperFunctions.psm1 - -$result = @{ - 'Files' = @() - 'Message' = "No update available" -} - -# Defensively check whether the BCPlatform package is tracked in the Packages config. -# Some (older) release branches do not track the BCPlatform package, in which case there is nothing to update. -$platformPackage = Get-ConfigValue -Key "BCPlatform" -ConfigType Packages -if (-not $platformPackage) { - Write-Host "BCPlatform package is not present in the Packages config. Skipping update." - return $result -} - -$newVersion = Update-PackageVersion -PackageName "BCPlatform" - -if ($newVersion) { - $result.Files = @(Get-PackagesFilePath -Relative) - $result.Message = "Update platform version. New value: $newVersion" -} - -return $result diff --git a/.github/actions/RunAutomation/UpdateSystemFilesSchedule/run.ps1 b/.github/actions/RunAutomation/UpdateSystemFilesSchedule/run.ps1 deleted file mode 100644 index 32e716eeac8..00000000000 --- a/.github/actions/RunAutomation/UpdateSystemFilesSchedule/run.ps1 +++ /dev/null @@ -1,93 +0,0 @@ -<# -.Synopsis - Updates the branch list of the "Update AL-Go System Files" scheduled run so it only targets supported branches. -.Description - The "Update AL-Go System Files" workflow (UpdateGitHubGoSystemFiles.yaml) is an AL-Go system file and - picks the branches to run on from the 'workflowSchedule.includeBranches' setting in - '.github/Update AL-Go System Files.settings.json'. Unlike the other BCApps automations, it does not use - the GetGitBranches action and therefore has no knowledge of the "Branch is out of support" ruleset. - - This automation rewrites 'workflowSchedule.includeBranches' with the explicit list of every official - branch (main and releases/*) that is currently in support. The list contains no wildcards and is - recomputed on every run, so out-of-support branches are dropped and newly created branches are added. -.Parameter runParameters - A hashtable with the parameters passed by the RunAutomation action (Repository and TargetBranch). -#> -param ( - [Parameter(Mandatory = $true)] - $runParameters -) - -Import-Module $PSScriptRoot\..\..\..\..\build\scripts\EnlistmentHelperFunctions.psm1 -DisableNameChecking - -$repository = $runParameters.Repository - -$result = @{ - 'Files' = @() - 'Message' = "No update available" -} - -$settingsRelativePath = ".github/Update AL-Go System Files.settings.json" -$settingsPath = Join-Path (Get-BaseFolder) $settingsRelativePath - -if (-not (Test-Path $settingsPath)) { - Write-Host "Settings file '$settingsRelativePath' not found. Nothing to update." - return $result -} - -$settings = Get-Content -Path $settingsPath -Raw | ConvertFrom-Json - -if (-not $settings.workflowSchedule) { - Write-Host "No 'workflowSchedule' configured in '$settingsRelativePath'. Nothing to update." - return $result -} - -$currentBranches = @($settings.workflowSchedule.includeBranches) -Write-Host "Configured branches: $($currentBranches -join ', ')" - -# The official branches, matching the definition used by the GetGitBranches action. -$officialBranchPatterns = @('main', 'releases/*') - -# Fetch all remote branches so the official branches can be listed explicitly. -RunAndCheck git fetch --quiet origin "+refs/heads/*:refs/remotes/origin/*" -$allBranches = @(RunAndCheck git for-each-ref --format="%(refname:short)" refs/remotes/origin/) | Where-Object { $_ -ne 'origin' } | ForEach-Object { $_ -replace '^origin/', '' } - -# Keep only the official branches (main and releases/*) that are in support. -$supportedBranches = @( - $allBranches | Where-Object { - $branch = $_ - ($officialBranchPatterns | Where-Object { $branch -like $_ }) -and (Test-IsBranchInSupport -BranchName $branch -Repository $repository) - } -) - -# Order deterministically ('main' first, then release branches in natural numeric order) to keep diffs clean. -function Get-BranchSortKey { - param([string] $Branch) - if ($Branch -eq 'main') { - return '0' - } - # Zero-pad numeric segments so e.g. releases/26.2 sorts before releases/26.10. - $padded = [regex]::Replace($Branch, '\d+', { param($m) $m.Value.PadLeft(10, '0') }) - return "1$padded" -} -$supportedBranches = @($supportedBranches | Select-Object -Unique | Sort-Object { Get-BranchSortKey $_ }) - -if ($supportedBranches.Count -eq 0) { - Write-Host "::Warning::No supported official branches found; leaving the schedule unchanged." - return $result -} - -if (($currentBranches -join ',') -eq ($supportedBranches -join ',')) { - Write-Host "Scheduled branches already match the supported official branches. Nothing to update." - return $result -} - -Write-Host "Updated branches: $($supportedBranches -join ', ')" - -$settings.workflowSchedule.includeBranches = @($supportedBranches) -$settings | ConvertTo-Json -Depth 100 | Set-ContentLF -Path $settingsPath - -$result.Files = @($settingsRelativePath) -$result.Message = "Update Update AL-Go System Files schedule to only include supported branches" - -return $result diff --git a/.github/actions/RunAutomation/run.ps1 b/.github/actions/RunAutomation/run.ps1 index 38040d600fc..3211e6a070f 100644 --- a/.github/actions/RunAutomation/run.ps1 +++ b/.github/actions/RunAutomation/run.ps1 @@ -29,15 +29,6 @@ param( $ErrorActionPreference = "Stop"; $ProgressPreference = "SilentlyContinue"; Set-StrictMode -Version 2.0 -Import-Module $PSScriptRoot\..\..\..\build\scripts\EnlistmentHelperFunctions.psm1 -DisableNameChecking - -# Do not run automations on branches that are out of support (branches with the "Branch is out of support" ruleset). -# This is a safety net that also covers manual (workflow_dispatch) runs, which bypass the GetGitBranches filtering. -if (-not (Test-IsBranchInSupport -BranchName $TargetBranch -Repository $Repository)) { - Write-Host "::Notice::Skipping automations because branch '$TargetBranch' is out of support." - return -} - function RunAutomation { param( [Parameter(Mandatory=$true)] @@ -131,7 +122,7 @@ function OpenPR { git push -u origin $branch | Out-Null - $prDescription += "`n`nAB#640900" # Add link to a work item + $prDescription += "`n`nAB#539394" # Add link to a work item return New-GitHubPullRequest -Repository $Repository -BranchName $branch -TargetBranch $TargetBranch -Title $prTitle -Description $prDescription } diff --git a/.github/actions/TestObsoleteTagPreprocessors/action.ps1 b/.github/actions/TestObsoleteTagPreprocessors/action.ps1 deleted file mode 100644 index 456c87e3e74..00000000000 --- a/.github/actions/TestObsoleteTagPreprocessors/action.ps1 +++ /dev/null @@ -1,34 +0,0 @@ -# Current path is .github/actions/TestObsoleteTagPreprocessors - -Import-Module "$PSScriptRoot\..\..\..\build\scripts\TestObsoleteTagPreprocessors.psm1" -Force - -# Exception list for testing files (files that are used in testing and should be ignored). -# These are test libraries/fixtures that legitimately contain ObsoleteTag properties -# outside of preprocessor blocks. -$exceptionList = @( - "src\Layers\W1\Tests\TestLibraries\MergeDuplicateObsolete.Table.al", - "src\Layers\W1\Tests\TestLibraries\ObsoleteRemovedTable.Table.al", - "src\Layers\W1\Tests\TestLibraries\TableWithRemovedField.Table.al", - "src\Layers\W1\Tests\Upgrade\DataSetup\TableStateObsoleteRemoved.Table.al" -) - -Write-Host "Checking ObsoleteTag preprocessor compliance in .al files..." -Write-Host "Using $($exceptionList.Count) predefined exception(s) for test files" - -# Initialize array to store any invalid ObsoleteTag issues -$obsoleteTagIssues = @() - -$alfiles = (Get-ChildItem -Filter '*.al' -Recurse) | Select-Object -ExpandProperty FullName -foreach ($file in $alfiles) { - # Call the Test-ObsoleteTagPreprocessors function with the file path and exception list - $result = Test-ObsoleteTagPreprocessors -filePath $file -ExceptionList $exceptionList - if ($null -ne $result) { - $obsoleteTagIssues += $result.Issues - } -} - -if ($obsoleteTagIssues.Count -gt 0) { - throw "ObsoleteTag properties found outside preprocessor blocks:`n$($obsoleteTagIssues -join "`n")" -} - -Write-Host "All ObsoleteTag properties are properly surrounded by preprocessor symbols." diff --git a/.github/actions/TestObsoleteTagPreprocessors/action.yaml b/.github/actions/TestObsoleteTagPreprocessors/action.yaml deleted file mode 100644 index f07d9353ec5..00000000000 --- a/.github/actions/TestObsoleteTagPreprocessors/action.yaml +++ /dev/null @@ -1,13 +0,0 @@ -name: Test Obsolete Tag Preprocessors -author: Microsoft Corporation -description: Verifies that ObsoleteTag properties on .al files are surrounded by preprocessor symbols -runs: - using: composite - steps: - - name: Test Obsolete Tag Preprocessors - shell: pwsh - run: | - ${{ github.action_path }}/action.ps1 -branding: - icon: terminal - color: blue diff --git a/.github/actions/UpdateUnstableTests/action.ps1 b/.github/actions/UpdateUnstableTests/action.ps1 deleted file mode 100644 index 5ffc8ce7804..00000000000 --- a/.github/actions/UpdateUnstableTests/action.ps1 +++ /dev/null @@ -1,51 +0,0 @@ -<# -.Synopsis - Entry point for the Update Unstable Tests action. -.Description - Reads the failing tests from the supplied CI/CD (or PR Build) runs and invokes the shared updater - script, which builds the per-branch unstable-tests list and exposes the artifact name for upload. - - By default the list is recomputed from the supplied runs. When -additive is set, the failing tests - are merged into the existing artifact instead (every existing entry is preserved). - - The set of runs to read is computed by the calling workflow and passed in as a comma-separated list. - - Parameters are passed explicitly by the action.yaml run block. -#> -[CmdletBinding()] -param( - [Parameter(Mandatory = $true)] - [string] $branch, - - [string] $runId = '', - - [switch] $additive -) - -$ErrorActionPreference = 'Stop' -$ProgressPreference = 'SilentlyContinue' -Set-StrictMode -Version 2.0 - -$scriptsRoot = Join-Path $PSScriptRoot '..' '..' '..' 'build' 'scripts' 'TestTolerance' -Import-Module (Join-Path $scriptsRoot 'TestTolerance.psm1') -Force - -# Parse the comma-separated run ids. -$runIds = @($runId.Split(',') | ForEach-Object { $_.Trim() } | Where-Object { $_ }) -if ($runIds.Count -eq 0) { - throw "No valid run IDs were provided in 'run-id' (value: '$runId'). Provide at least one CI/CD (or PR Build) run ID." -} - -$outputPath = Join-Path '.unstable-tests' 'unstable-tests.json' - -& (Join-Path $scriptsRoot 'UpdateUnstableTestsArtifact.ps1') ` - -Branch $branch ` - -RunIds $runIds ` - -OutputPath $outputPath ` - -Additive:$additive - -# Expose the artifact name so the action's upload step can publish it. Only emit it when the artifact -# was actually produced, so the upload step can be skipped otherwise. -if ($env:GITHUB_OUTPUT -and (Test-Path $outputPath)) { - $artifactName = Get-UnstableTestsArtifactName -Branch $branch - Add-Content -Encoding UTF8 -Path $env:GITHUB_OUTPUT -Value "artifactName=$artifactName" -} diff --git a/.github/actions/UpdateUnstableTests/action.yaml b/.github/actions/UpdateUnstableTests/action.yaml deleted file mode 100644 index 3512d5c1021..00000000000 --- a/.github/actions/UpdateUnstableTests/action.yaml +++ /dev/null @@ -1,49 +0,0 @@ -name: Update Unstable Tests -author: Microsoft Corporation -description: > - Updates the per-branch unstable-tests artifact from a set of CI/CD runs. By default the list is - recomputed from the supplied runs; when additive is set, their failing tests are merged into the - existing artifact instead. The runs to read are computed by the calling workflow. -inputs: - branch: - description: Target branch (e.g. 'main', 'releases/26.0') - required: true - run-id: - description: Comma-separated CI/CD (or PR Build) run IDs to read failing tests from. - required: true - additive: - description: > - When 'true', merge the runs' failing tests into the existing per-branch artifact (preserving - every existing entry) instead of recomputing the list from scratch. - required: false - default: 'false' -runs: - using: composite - steps: - - name: Update Unstable Tests - id: update - shell: pwsh - env: - GH_TOKEN: ${{ github.token }} - _branch: ${{ inputs.branch }} - _runId: ${{ inputs.run-id }} - _additive: ${{ inputs.additive }} - run: | - ${{ github.action_path }}/action.ps1 ` - -branch $env:_branch ` - -runId $env:_runId ` - -additive:($env:_additive -eq 'true') - - - name: Upload unstable tests artifact - if: steps.update.outputs.artifactName != '' - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 - env: - ACTIONS_RUNNER_DISABLE_NODE_MAGLEV: 1 - with: - name: ${{ steps.update.outputs.artifactName }} - path: .unstable-tests/unstable-tests.json - if-no-files-found: warn - retention-days: 30 -branding: - icon: terminal - color: blue diff --git a/.github/actions/UpdateUnstableTestsCombined/action.ps1 b/.github/actions/UpdateUnstableTestsCombined/action.ps1 deleted file mode 100644 index 04f11b4645d..00000000000 --- a/.github/actions/UpdateUnstableTestsCombined/action.ps1 +++ /dev/null @@ -1,81 +0,0 @@ -<# -.Synopsis - Entry point for the Update Unstable Tests (Combined) action. -.Description - Invokes the combined updater script, which maintains the per-branch unstable-tests artifact from both - detection signals in a single run: the CI/CD sliding-window recompute (Path A) and the additive - cross-PR PR-build detector (Path B). It then exposes the artifact name so the action's upload step can - publish it, only when the artifact was actually produced. - - Parameters are passed explicitly by the action.yaml run block, which sources the numeric tuning - values (RunLimit / WindowHours / MinDistinctPrs) from its own input defaults so they live in a - single place rather than being duplicated as PowerShell parameter defaults. - -.Parameter Branch - Supported branch (main or releases/*) whose unstable-tests artifact should be updated. -.Parameter RunLimit - Path A: number of recent completed CI/CD runs to recompute the base list from. -.Parameter FilterPush - Path A: include CI/CD runs triggered by 'push' when discovering the window. -.Parameter FilterWorkflowDispatch - Path A: include CI/CD runs triggered by 'workflow_dispatch' when discovering the window. -.Parameter WindowHours - Path B: how many hours of recent PR builds (by completion time) to examine. -.Parameter MinDistinctPrs - Path B: minimum number of distinct PRs a test must fail on to be marked unstable. -#> -[CmdletBinding()] -param( - [Parameter(Mandatory = $true)] - [string] $Branch, - - [Parameter(Mandatory = $true)] - [int] $RunLimit, - - [switch] $FilterPush, - - [switch] $FilterWorkflowDispatch, - - [Parameter(Mandatory = $true)] - [int] $WindowHours, - - [Parameter(Mandatory = $true)] - [int] $MinDistinctPrs -) - -$ErrorActionPreference = 'Stop' -$ProgressPreference = 'SilentlyContinue' -Set-StrictMode -Version 2.0 - -$scriptsRoot = Join-Path -Path $PSScriptRoot -ChildPath '..' -AdditionalChildPath '..', '..', 'build', 'scripts', 'TestTolerance' -Import-Module (Join-Path -Path $scriptsRoot -ChildPath 'TestTolerance.psm1') -Force - -$outputPath = Join-Path -Path '.unstable-tests' -ChildPath 'unstable-tests.json' - -try { - & (Join-Path -Path $scriptsRoot -ChildPath 'UpdateUnstableTestsCombined.ps1') ` - -Branch $Branch ` - -RunLimit $RunLimit ` - -FilterPush:$FilterPush ` - -FilterWorkflowDispatch:$FilterWorkflowDispatch ` - -WindowHours $WindowHours ` - -MinDistinctPrs $MinDistinctPrs ` - -OutputPath $outputPath - - # Expose the artifact name so the action's upload step can publish it. Only emit it when the artifact - # was actually produced, so the upload step can be skipped otherwise. - if ($env:GITHUB_OUTPUT -and (Test-Path $outputPath)) { - $artifactName = Get-UnstableTestsArtifactName -Branch $Branch - Add-Content -Encoding UTF8 -Path $env:GITHUB_OUTPUT -Value "artifactName=$artifactName" - } -} -catch { - Write-Host "::error::Failed to update unstable tests for '$Branch': $($_.Exception.Message)" - exit 1 -} - -# The driver runs best-effort 'gh' commands (e.g. downloading results from still-running PR builds that may -# not have uploaded any artifacts yet), which can leave $LASTEXITCODE non-zero even though the update itself -# succeeded. GitHub's pwsh wrapper ends with 'exit $LASTEXITCODE', so normalize the exit code on success to -# avoid failing the step on a benign, already-tolerated 'gh' error. -exit 0 diff --git a/.github/actions/UpdateUnstableTestsCombined/action.yaml b/.github/actions/UpdateUnstableTestsCombined/action.yaml deleted file mode 100644 index b154081733b..00000000000 --- a/.github/actions/UpdateUnstableTestsCombined/action.yaml +++ /dev/null @@ -1,68 +0,0 @@ -name: Update Unstable Tests (Combined) -author: Microsoft Corporation -description: > - Maintains the per-branch unstable-tests artifact from both detection signals in a single run: the CI/CD - sliding-window recompute (Path A) and the additive cross-PR PR-build detector (Path B). Publishes the - updated per-branch artifact, and only uploads when an artifact was actually produced. -inputs: - branch: - description: Target branch (e.g. 'main', 'releases/26.0') - required: true - run-limit: - description: 'Path A: number of recent completed CI/CD runs to examine.' - required: false - default: '3' - filter-push: - description: "Path A: include CI/CD runs triggered by push ('true'/'false')." - required: false - default: 'false' - filter-workflow-dispatch: - description: "Path A: include CI/CD runs triggered by workflow_dispatch ('true'/'false')." - required: false - default: 'true' - window-hours: - description: 'Path B: how many hours of recent PR builds to examine.' - required: false - default: '6' - min-distinct-prs: - description: 'Path B: minimum number of distinct PRs a test must fail on to be marked unstable.' - required: false - default: '3' -runs: - using: composite - steps: - - name: Update unstable tests - id: update - shell: pwsh - env: - GH_TOKEN: ${{ github.token }} - _branch: ${{ inputs.branch }} - _runLimit: ${{ inputs.run-limit }} - _filterPush: ${{ inputs.filter-push }} - _filterWorkflowDispatch: ${{ inputs.filter-workflow-dispatch }} - _windowHours: ${{ inputs.window-hours }} - _minDistinctPrs: ${{ inputs.min-distinct-prs }} - run: | - ${{ github.action_path }}/action.ps1 ` - -Branch $env:_branch ` - -RunLimit ([int]$env:_runLimit) ` - -FilterPush:($env:_filterPush -eq 'true') ` - -FilterWorkflowDispatch:($env:_filterWorkflowDispatch -eq 'true') ` - -WindowHours ([int]$env:_windowHours) ` - -MinDistinctPrs ([int]$env:_minDistinctPrs) - - - name: Upload unstable tests artifact - if: steps.update.outputs.artifactName != '' - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 - env: - ACTIONS_RUNNER_DISABLE_NODE_MAGLEV: 1 - with: - name: ${{ steps.update.outputs.artifactName }} - path: .unstable-tests/unstable-tests.json - if-no-files-found: warn - # A fresh artifact is produced on every hourly run and PR builds only ever consume the latest, so - # a long retention just multiplies storage. 7 days still buffers a multi-day scheduler outage. - retention-days: 7 -branding: - icon: terminal - color: blue diff --git a/.github/actions/ValidateCountryProjects/action.ps1 b/.github/actions/ValidateCountryProjects/action.ps1 deleted file mode 100644 index 904b6ef7c35..00000000000 --- a/.github/actions/ValidateCountryProjects/action.ps1 +++ /dev/null @@ -1,6 +0,0 @@ -$repoRoot = & git rev-parse --show-toplevel -$result = & "$repoRoot/build/scripts/Update-CountryProjectSettings.ps1" -Validate -if ($result -eq $false) { - Write-Host "::error::Country project settings are out of date. Run 'build/scripts/Update-CountryProjectSettings.ps1' and commit the changes." - exit 1 -} diff --git a/.github/actions/ValidateCountryProjects/action.yaml b/.github/actions/ValidateCountryProjects/action.yaml deleted file mode 100644 index 56e23ab9b8d..00000000000 --- a/.github/actions/ValidateCountryProjects/action.yaml +++ /dev/null @@ -1,13 +0,0 @@ -name: Validate Country Projects -author: Microsoft Corporation -description: Validates that country project settings.json files have correct W1 app dependencies. -runs: - using: composite - steps: - - name: Validate Country Projects - shell: pwsh - run: | - ${{ github.action_path }}/action.ps1 -branding: - icon: terminal - color: blue diff --git a/.github/actions/VerifyMiappSync/action.ps1 b/.github/actions/VerifyMiappSync/action.ps1 deleted file mode 100644 index b6b30e0be18..00000000000 --- a/.github/actions/VerifyMiappSync/action.ps1 +++ /dev/null @@ -1,5 +0,0 @@ -# Current path is .github/actions/VerifyMiappSync - -Import-Module "$PSScriptRoot\..\..\..\build\scripts\Miapp\MicroSnapApp.psm1" -Force -$env:RepoBranchName = $env:GITHUB_BASE_REF -Invoke-MiSnapApp diff --git a/.github/actions/VerifyMiappSync/action.yaml b/.github/actions/VerifyMiappSync/action.yaml deleted file mode 100644 index aa5905dc00f..00000000000 --- a/.github/actions/VerifyMiappSync/action.yaml +++ /dev/null @@ -1,13 +0,0 @@ -name: Verify Miapp Sync -author: Microsoft Corporation -description: Verifies that all Miapp-dependent files are synchronized using Invoke-MiSnapApp. -runs: - using: composite - steps: - - name: Verify Miapp sync - shell: pwsh - run: | - ${{ github.action_path }}/action.ps1 -branding: - icon: terminal - color: blue diff --git a/build/scripts/AutomatedSubmission.psm1 b/build/scripts/AutomatedSubmission.psm1 index 4d6cbcfc2c1..c63a70db8ff 100644 --- a/build/scripts/AutomatedSubmission.psm1 +++ b/build/scripts/AutomatedSubmission.psm1 @@ -152,14 +152,7 @@ function New-GitHubPullRequest Write-Host "gh pr create $parameters" $prLink = Invoke-Expression "gh pr create $parameters" - - # Enabling auto-merge can fail due repository configuration or transient GitHub API issues. - # A PR has already been created at this point, so the automation should continue. - $mergeOutput = @(gh pr merge --auto --squash 2>&1) - if ($LASTEXITCODE -ne 0) { - Write-Host "::Warning::Failed to enable auto-merge for PR '$prLink'. Continuing without auto-merge. Details: $($mergeOutput -join ' ')" - $global:LASTEXITCODE = 0 - } + gh pr merge --auto --squash --delete-branch | Out-Null return $prLink } diff --git a/build/scripts/EnlistmentHelperFunctions.psm1 b/build/scripts/EnlistmentHelperFunctions.psm1 index bd4aebe37a6..6b5edb1bcb7 100644 --- a/build/scripts/EnlistmentHelperFunctions.psm1 +++ b/build/scripts/EnlistmentHelperFunctions.psm1 @@ -204,19 +204,13 @@ function Set-ConfigValue() { For example, if the repo version is 1.2, the function will look for the latest version of the package that has major.minor = 1.2. .Parameter PackageName The name of the package -.Parameter Branch - The branch the package version is being updated for (e.g. "main" or "releases/28.0"). - Used to decide which storage account to use for BCArtifacts baselines. When not provided, - it falls back to Get-CurrentBranch. .Returns The latest version of the package #> function Get-PackageLatestVersion() { param( [Parameter(Mandatory=$true)] - [string] $PackageName, - [Parameter(Mandatory=$false)] - [string] $Branch + [string] $PackageName ) $package = Get-ConfigValue -Key $PackageName -ConfigType Packages @@ -249,15 +243,7 @@ function Get-PackageLatestVersion() { } } - # Determine the branch this update is running for. The automation is triggered from a - # single workflow (running on 'main') that updates every release branch via a matrix, so - # Get-CurrentBranch (which returns $GITHUB_REF_NAME) reports 'main' for every job and - # cannot be used to pick the storage account. Prefer the explicit target branch passed in - # by the automation and only fall back to Get-CurrentBranch when it is not available. - $currentBranch = $Branch - if (-not $currentBranch) { - $currentBranch = Get-CurrentBranch - } + $currentBranch = Get-CurrentBranch Write-Host "Current branch: $currentBranch" $storageAccountOrder = @("bcartifacts", "bcinsider") if($currentBranch -eq "main") { @@ -275,20 +261,6 @@ function Get-PackageLatestVersion() { return $latestVersion } - 'BCPlatform' { - Import-Module $PSScriptRoot\PlatformHelper.psm1 -DisableNameChecking - - # Use the major.minor of the currently configured platform version, not repoVersion - [System.Version] $currentPlatformVersion = $package.Version - $majorMinor = "$($currentPlatformVersion.Major).$($currentPlatformVersion.Minor)" - $latestVersion = Get-LatestPlatformVersion -MajorMinor $majorMinor - - if (-not $latestVersion) { - throw "Could not find platform version (for major.minor: $majorMinor)" - } - - return $latestVersion - } default { throw "Unknown package source: $($package.Source)" } @@ -408,18 +380,13 @@ function Update-BCArtifactVersion { Updates the version of a package in the Packages config file to the latest version available. .Parameter PackageName The name of the package to update -.Parameter Branch - The branch the package version is being updated for (e.g. "main" or "releases/28.0"). - Forwarded to Get-PackageLatestVersion to select the correct BCArtifacts baseline storage account. .Returns The new version of the package, if it was updated #> function Update-PackageVersion ( [Parameter(Mandatory=$true)] - [string] $PackageName, - [Parameter(Mandatory=$false)] - [string] $Branch + [string] $PackageName ) { $currentPackage = Get-ConfigValue -Key $PackageName -ConfigType Packages @@ -431,13 +398,7 @@ function Update-PackageVersion $currentVersion = $currentPackage.Version Write-Host "Current $PackageName version: $currentVersion" - # If the current version is a major.minor pattern (e.g. "28.0"), it is intentionally pinned and should not be overwritten with a full version - if ($currentVersion.Split('.').Count -eq 2) { - Write-Host "$PackageName is pinned to the major.minor pattern '$currentVersion'. Skipping update." - return $null - } - - $latestVersion = Get-PackageLatestVersion -PackageName $PackageName -Branch $Branch + $latestVersion = Get-PackageLatestVersion -PackageName $PackageName Write-Host "Latest $PackageName version found: $latestVersion" $result = $null diff --git a/build/scripts/PlatformHelper.psm1 b/build/scripts/PlatformHelper.psm1 deleted file mode 100644 index 64bdc2b6ba4..00000000000 --- a/build/scripts/PlatformHelper.psm1 +++ /dev/null @@ -1,179 +0,0 @@ -$script:PlatformCdnUrl = 'https://bcinsider-fvh2ekdjecfjd6gk.b02.azurefd.net' -$script:PlatformIndexUrl = "$script:PlatformCdnUrl/platform/indexes/platform.json" -$script:PlatformVersionsCache = $null - -<# -.SYNOPSIS - Downloads and caches the platform version index. -.DESCRIPTION - Fetches the platform.json index file from the CDN and caches it - for subsequent calls within the same session. -.PARAMETER Force - When specified, forces a refresh of the cached version index. -.OUTPUTS - Array of version strings available in the platform index. -#> -function Get-PlatformVersions { - [CmdletBinding()] - param( - [Parameter(Mandatory = $false)] - [switch] $Force - ) - - if ($null -eq $script:PlatformVersionsCache -or $Force) { - try { - Write-Host "Fetching platform version index from $script:PlatformIndexUrl" - $response = Invoke-WebRequest -Uri $script:PlatformIndexUrl -ErrorAction Stop - $index = @($response.Content | ConvertFrom-Json) - if ($index.Count -gt 0 -and $index[0].PSObject.Properties['Version']) { - $script:PlatformVersionsCache = @($index | ForEach-Object { $_.Version }) - } else { - $script:PlatformVersionsCache = $index - } - } - catch { - throw "Failed to fetch platform version index from '$script:PlatformIndexUrl': $($_.Exception.Message)" - } - } - - return $script:PlatformVersionsCache -} - -<# -.SYNOPSIS - Gets the full CDN URL for a specific platform version. -.DESCRIPTION - Constructs and returns the full CDN URL for downloading a specific platform version. - Validates that the version exists in the platform index. -.PARAMETER Version - The full platform version string (e.g., '29.0.49913.0'). -.OUTPUTS - The full CDN URL for the specified platform version. -.EXAMPLE - Get-PlatformVersionUrl -Version '29.0.49913.0' - Returns: https://bcinsider-fvh2ekdjecfjd6gk.b02.azurefd.net/platform/29.0.49913.0 -#> -function Get-PlatformVersionUrl { - [CmdletBinding()] - param( - [Parameter(Mandatory = $true)] - [string] $Version - ) - - $availableVersions = Get-PlatformVersions - if ($availableVersions -notcontains $Version) { - throw "Platform version '$Version' is not available. Use Get-PlatformVersions to see available versions." - } - - return "$script:PlatformCdnUrl/platform/$Version" -} - -<# -.SYNOPSIS - Finds the latest platform version matching a major.minor pattern. -.DESCRIPTION - Searches the platform version index for versions matching the specified - major and minor version numbers, and returns the latest (highest) matching version. -.PARAMETER MajorMinor - The major.minor version pattern to match (e.g., '29.0'). -.OUTPUTS - The latest version string matching the major.minor pattern, or $null if no match found. -.EXAMPLE - Get-LatestPlatformVersion -MajorMinor '29.0' - Returns: '29.0.49913.0' (or whatever the latest 29.0.x.x version is) -#> -function Get-LatestPlatformVersion { - [CmdletBinding()] - param( - [Parameter(Mandatory = $true)] - [string] $MajorMinor - ) - - $availableVersions = Get-PlatformVersions - - # Parse the major.minor input - $parts = $MajorMinor.Split('.') - if ($parts.Count -lt 2) { - throw "Invalid MajorMinor format '$MajorMinor'. Expected format: 'major.minor' (e.g., '29.0')." - } - - $major = [int]$parts[0] - $minor = [int]$parts[1] - - # Filter versions matching major.minor and sort to find the latest - $matchingVersions = @($availableVersions | Where-Object { - try { - $ver = [System.Version]$_ - $ver.Major -eq $major -and $ver.Minor -eq $minor - } - catch { - $false - } - } | Sort-Object { [System.Version]$_ }) - - if ($matchingVersions.Count -eq 0) { - return $null - } - - return $matchingVersions[$matchingVersions.Count - 1] -} - -<# -.SYNOPSIS - Resolves a platform version setting to a full platform version. -.DESCRIPTION - Accepts either a full platform version (e.g. '29.0.49913.0') or a - major.minor pattern (e.g. '29.0'). When a major.minor pattern is given, - the highest available version matching that pattern is returned. -.PARAMETER Version - The platform version setting to resolve. Either a full version or a - major.minor pattern. -.OUTPUTS - The resolved full platform version string. -.EXAMPLE - Resolve-PlatformVersion -Version '29.0' - Returns: '29.0.49913.0' (the highest available 29.0.x.x version) -.EXAMPLE - Resolve-PlatformVersion -Version '29.0.49913.0' - Returns: '29.0.49913.0' -#> -function Resolve-PlatformVersion { - [CmdletBinding()] - param( - [Parameter(Mandatory = $true)] - [string] $Version - ) - - # A full version has 4 parts (major.minor.build.revision); a pattern has only major.minor - if ($Version.Split('.').Count -eq 2) { - $resolvedVersion = Get-LatestPlatformVersion -MajorMinor $Version - if ($null -eq $resolvedVersion) { - throw "No platform version found matching major.minor '$Version'." - } - return $resolvedVersion - } - - return $Version -} - -<# -.SYNOPSIS - Clears the cached platform version index. -.DESCRIPTION - Clears the in-memory cache of the platform version index, forcing a - fresh download on the next call to Get-PlatformVersions. -#> -function Clear-PlatformVersionCache { - [CmdletBinding()] - param() - - $script:PlatformVersionsCache = $null -} - -Export-ModuleMember -Function @( - 'Get-PlatformVersions', - 'Get-PlatformVersionUrl', - 'Get-LatestPlatformVersion', - 'Resolve-PlatformVersion', - 'Clear-PlatformVersionCache' -) diff --git a/build/scripts/tests/PlatformHelper.Test.ps1 b/build/scripts/tests/PlatformHelper.Test.ps1 deleted file mode 100644 index adbca55fef4..00000000000 --- a/build/scripts/tests/PlatformHelper.Test.ps1 +++ /dev/null @@ -1,138 +0,0 @@ -$errorActionPreference = "Stop"; $ProgressPreference = "SilentlyContinue"; Set-StrictMode -Version 2.0 - -Import-Module (Join-Path $PSScriptRoot '../PlatformHelper.psm1') -Force - -Describe "PlatformHelper" { - BeforeAll { - $script:testVersions = @( - '28.0.12345.0', - '28.0.12346.0', - '28.1.54321.0', - '29.0.49913.0', - '29.0.49914.0', - '29.1.11111.0', - '30.0.10000.0' - ) - } - - BeforeEach { - Clear-PlatformVersionCache - } - - Describe "Get-PlatformVersions" { - It "Should fetch and return platform versions" { - Mock -ModuleName PlatformHelper -CommandName Invoke-WebRequest -MockWith { - return @{ - Content = $script:testVersions | ConvertTo-Json - } - } - - $versions = Get-PlatformVersions - $versions | Should -Not -BeNullOrEmpty - $versions.Count | Should -Be 7 - } - - It "Should cache versions on subsequent calls" { - Mock -ModuleName PlatformHelper -CommandName Invoke-WebRequest -MockWith { - return @{ - Content = $script:testVersions | ConvertTo-Json - } - } - - Get-PlatformVersions | Out-Null - Get-PlatformVersions | Out-Null - - Should -Invoke -ModuleName PlatformHelper -CommandName Invoke-WebRequest -Times 1 -Exactly - } - - It "Should refresh cache when Force is specified" { - Mock -ModuleName PlatformHelper -CommandName Invoke-WebRequest -MockWith { - return @{ - Content = $script:testVersions | ConvertTo-Json - } - } - - Get-PlatformVersions | Out-Null - Get-PlatformVersions -Force | Out-Null - - Should -Invoke -ModuleName PlatformHelper -CommandName Invoke-WebRequest -Times 2 -Exactly - } - - It "Should throw on network error" { - Mock -ModuleName PlatformHelper -CommandName Invoke-WebRequest -MockWith { - throw "Network error" - } - - { Get-PlatformVersions } | Should -Throw "*Failed to fetch platform version index*" - } - } - - Describe "Get-PlatformVersionUrl" { - BeforeEach { - Mock -ModuleName PlatformHelper -CommandName Invoke-WebRequest -MockWith { - return @{ - Content = $script:testVersions | ConvertTo-Json - } - } - } - - It "Should return correct URL for valid version" { - $url = Get-PlatformVersionUrl -Version '29.0.49913.0' - $url | Should -Be 'https://bcinsider-fvh2ekdjecfjd6gk.b02.azurefd.net/platform/29.0.49913.0' - } - - It "Should throw for invalid version" { - { Get-PlatformVersionUrl -Version '99.0.00000.0' } | Should -Throw "*is not available*" - } - } - - Describe "Get-LatestPlatformVersion" { - BeforeEach { - Mock -ModuleName PlatformHelper -CommandName Invoke-WebRequest -MockWith { - return @{ - Content = $script:testVersions | ConvertTo-Json - } - } - } - - It "Should return latest version for major.minor '29.0'" { - $version = Get-LatestPlatformVersion -MajorMinor '29.0' - $version | Should -Be '29.0.49914.0' - } - - It "Should return latest version for major.minor '28.0'" { - $version = Get-LatestPlatformVersion -MajorMinor '28.0' - $version | Should -Be '28.0.12346.0' - } - - It "Should return latest version for major.minor '28.1'" { - $version = Get-LatestPlatformVersion -MajorMinor '28.1' - $version | Should -Be '28.1.54321.0' - } - - It "Should return null for non-existent major.minor" { - $version = Get-LatestPlatformVersion -MajorMinor '99.0' - $version | Should -BeNullOrEmpty - } - - It "Should throw for invalid MajorMinor format" { - { Get-LatestPlatformVersion -MajorMinor '29' } | Should -Throw "*Invalid MajorMinor format*" - } - } - - Describe "Clear-PlatformVersionCache" { - It "Should clear the cache and force re-fetch" { - Mock -ModuleName PlatformHelper -CommandName Invoke-WebRequest -MockWith { - return @{ - Content = $script:testVersions | ConvertTo-Json - } - } - - Get-PlatformVersions | Out-Null - Clear-PlatformVersionCache - Get-PlatformVersions | Out-Null - - Should -Invoke -ModuleName PlatformHelper -CommandName Invoke-WebRequest -Times 2 -Exactly - } - } -} From 866516c89edcc320ae5ae2ba4e90df0260187dac Mon Sep 17 00:00:00 2001 From: Maria Zhelezova <43066499+mazhelez@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:32:24 +0100 Subject: [PATCH 5/6] Correct comment about the 'Layers' folder 'Layers' exists on release branches from 29.0 onwards. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/actions/TestObjectIdsAndManifests/action.ps1 | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/actions/TestObjectIdsAndManifests/action.ps1 b/.github/actions/TestObjectIdsAndManifests/action.ps1 index 24d21db153e..ff7a7142362 100644 --- a/.github/actions/TestObjectIdsAndManifests/action.ps1 +++ b/.github/actions/TestObjectIdsAndManifests/action.ps1 @@ -11,8 +11,8 @@ $w1Apps = @(Join-Path $sourceCodeFolder "Apps\W1") $w1Layers = @(Join-Path $sourceCodeFolder "Layers\W1") # All Folders (For Apps) $allApps = @(Join-Path $sourceCodeFolder "Apps") -# The 'Layers' folder only exists on main and not on release branches. Guard the -# Get-ChildItem call so it does not fail when the folder is missing. +# The 'Layers' folder only exists on main and on release branches from 29.0 onwards. +# Guard the Get-ChildItem call so it does not fail when the folder is missing. $layersFolder = Join-Path $sourceCodeFolder 'Layers' $allBaseApps = @( if (Test-Path -Path $layersFolder) { From 2203e9d55d41193aff983f8acaa9ec1c036a26da Mon Sep 17 00:00:00 2001 From: Maria Zhelezova <43066499+mazhelez@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:47:53 +0100 Subject: [PATCH 6/6] Expand inner wildcards in AL-Go testFolders Release branches use testFolders such as 'src/Apps/W1/*/Test'. Expand these to the matching folders so added files in those test apps are excluded from the object ID range check. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- build/scripts/AppObjectValidation.psm1 | 12 ++++++++- .../tests/AppObjectValidation.Test.ps1 | 26 +++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/build/scripts/AppObjectValidation.psm1 b/build/scripts/AppObjectValidation.psm1 index 5afdde3122b..2570e7f7a49 100644 --- a/build/scripts/AppObjectValidation.psm1 +++ b/build/scripts/AppObjectValidation.psm1 @@ -370,6 +370,7 @@ function Test-IsObjectIdInAllowedRange { Reads every build project settings.json and resolves its testFolders entries to absolute paths. It also includes projects marked isTest in projects.json, which covers test utilities listed as AL-Go appFolders. A trailing wildcard is treated as the containing test folder because every application below it is a test app. + Wildcards elsewhere in the path (e.g. 'src/Apps/W1/*/Test') are expanded to the matching existing folders. .PARAMETER ProjectsPath The directory containing the AL-Go build projects. .PARAMETER ProjectsJsonPath @@ -392,7 +393,16 @@ function Get-ALGoTestFolders { foreach ($testFolder in @($settings.testFolders)) { $testFolderWithoutWildcard = $testFolder -replace '[\\/]\*$', '' $projectFolder = $settingsFile.Directory.Parent.FullName - $testFolders += [System.IO.Path]::GetFullPath((Join-Path -Path $projectFolder -ChildPath $testFolderWithoutWildcard)) + $testFolderPath = [System.IO.Path]::GetFullPath((Join-Path -Path $projectFolder -ChildPath $testFolderWithoutWildcard)) + if ([System.Management.Automation.WildcardPattern]::ContainsWildcardCharacters($testFolderPath)) { + # Expand wildcards inside the path (e.g. 'src/Apps/W1/*/Test') to the matching folders. + $testFolders += @(Get-Item -Path $testFolderPath -ErrorAction SilentlyContinue | + Where-Object { $_.PSIsContainer } | + ForEach-Object { $_.FullName }) + } + else { + $testFolders += $testFolderPath + } } } diff --git a/build/scripts/tests/AppObjectValidation.Test.ps1 b/build/scripts/tests/AppObjectValidation.Test.ps1 index da4290b9ebc..80cf1a30088 100644 --- a/build/scripts/tests/AppObjectValidation.Test.ps1 +++ b/build/scripts/tests/AppObjectValidation.Test.ps1 @@ -115,6 +115,32 @@ Describe "AppObjectValidation" { $testFolders | Should -Contain ([System.IO.Path]::GetFullPath($expected)) } + It "expands wildcards inside the path to the matching test folders" { + $layout = New-ValidationLayout + $otherTestApp = Join-Path $layout.Source 'Apps\W1\Other\Test' + New-Item -ItemType Directory -Path $otherTestApp -Force | Out-Null + @{ + testFolders = @('../../../src/Apps/W1/*/Test') + } | ConvertTo-Json | Set-Content -Path (Join-Path $layout.Projects 'Apps W1\.AL-Go\settings.json') -Encoding UTF8 + + $testFolders = Get-ALGoTestFolders -ProjectsPath $layout.Projects + + $testFolders | Should -Contain ([System.IO.Path]::GetFullPath($layout.TestApp)) + $testFolders | Should -Contain ([System.IO.Path]::GetFullPath($otherTestApp)) + $testFolders | Should -Not -Contain ([System.IO.Path]::GetFullPath($layout.Production)) + @($testFolders | Where-Object { $_.Contains('*') }) | Should -BeNullOrEmpty + } + + It "excludes added files in test apps matched by an inner wildcard" { + $layout = New-ValidationLayout + @{ + testFolders = @('../../../src/Apps/W1/*/Test') + } | ConvertTo-Json | Set-Content -Path (Join-Path $layout.Projects 'Apps W1\.AL-Go\settings.json') -Encoding UTF8 + $file = New-TestAlFile -Path (Join-Path $layout.TestApp 'Helper.al') -Declaration 'table 139500 "Helper"' + + { Invoke-AddedFileValidation -Layout $layout -FilePaths @($file) } | Should -Not -Throw + } + It "includes projects canonically marked as tests even when they are AL-Go app folders" { $layout = New-ValidationLayout $testUtility = Join-Path $layout.Source 'Apps\W1\LibraryNoTransactions\app'