Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .github/workflows/PullRequestHandler.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,13 @@ jobs:
lfs: true
ref: ${{ github.event_name == 'pull_request' && github.sha || github.event_name == 'merge_group' && github.ref || format('refs/pull/{0}/merge', github.event.pull_request.number) }}

- name: Scope pull request build
if: github.event_name == 'pull_request'
shell: pwsh
run: |
Import-Module ./build/scripts/PullRequestBuildScope.psm1 -Force
Set-PullRequestBuildScope -BaseFolder $env:GITHUB_WORKSPACE

- name: Initialize the workflow
id: init
uses: microsoft/AL-Go/Actions/WorkflowInitialize@ea8d8a61e8d3968406c09635951edb7f0f95200a
Expand Down
97 changes: 95 additions & 2 deletions build/scripts/BuildOptimization.psm1
Original file line number Diff line number Diff line change
Expand Up @@ -335,6 +335,62 @@ function Get-ChangedFilesForCI {
}
}

<#
.SYNOPSIS
Returns the files changed by a pull request, using the pull request merge commit.
.DESCRIPTION
For pull_request events GitHub checks out refs/pull/N/merge, whose first parent is the
base branch tip and whose second parent is the pull request head. Diffing the merge commit
against its first parent yields exactly the pull request's changes, unlike diffing the head
against a base branch commit, which also reports base-branch changes the pull request
branch does not contain yet. Needs only the first parent commit, so it works with shallow
checkouts.
.OUTPUTS
String array of changed file paths relative to the repo root, or $null when the checked-out
commit is not the pull request merge commit or the diff cannot be computed.
#>
function Get-PullRequestMergeChangedFiles {
[CmdletBinding()]
[OutputType([string[]])]
param()

if ($env:GITHUB_EVENT_NAME -notmatch 'pull_request') { return $null }
if (-not $env:GITHUB_EVENT_PATH -or -not (Test-Path $env:GITHUB_EVENT_PATH)) { return $null }
$headSha = (Get-Content $env:GITHUB_EVENT_PATH -Raw | ConvertFrom-Json).pull_request.head.sha
if (-not $headSha) { return $null }

$prevErrorAction = $ErrorActionPreference
$ErrorActionPreference = 'Continue'
try {
$parents = @((& git cat-file -p HEAD 2>$null) | Where-Object { $_ -match '^parent ' } | ForEach-Object { ($_ -split ' ')[1] })
if ($parents.Count -ne 2 -or $parents[1] -ne $headSha) {
Write-Host "BUILD OPTIMIZATION: HEAD is not the merge commit for pull request head $headSha"
return $null
}

& git cat-file -e "$($parents[0])^{commit}" 2>$null
if ($LASTEXITCODE -ne 0) {
& git fetch --no-tags --depth=1 origin $parents[0] 2>$null
}

$files = @(& git -c core.quotePath=false diff --name-only $parents[0] HEAD -- 2>$null)
if ($LASTEXITCODE -ne 0 -or $files.Count -eq 0) { return $null }
# RESEARCH ONLY (do not merge): hide the CI stack's own files so probe changes measure a single PR class

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

$\textbf{🟡\ Medium\ Severity\ —\ Agent}$

The committed research-only filter removes build/* and .github/* changes from the shared pull-request change set before country selection and fullBuildPatterns evaluation. In a mixed infrastructure/app PR such as this one, the infrastructure changes are therefore invisible, so the build omits the intended sentinel country and affected-test analysis does not force the full test run. Remove the research filter and its ResearchIgnorePaths.txt file so all changed files reach the production scoping safeguards.

👍 useful · ❤️ especially valuable · 👎 wrong - reply with why · AL review agent v10.0.7

$ignoreFile = Join-Path $PSScriptRoot 'ResearchIgnorePaths.txt'
if (Test-Path $ignoreFile) {
$ignore = @(Get-Content $ignoreFile | Where-Object { $_ -and -not $_.StartsWith('#') })
$files = @($files | Where-Object { $f = $_; -not ($ignore | Where-Object { $f -like $_ }) })
Write-Host "BUILD OPTIMIZATION: RESEARCH ignoring CI stack files, $($files.Count) probe file(s) remain: $($files -join ', ')"
if ($files.Count -eq 0) { return $null }
}
Write-Host "BUILD OPTIMIZATION: Pull request merge commit changes $($files.Count) file(s)"
return [string[]]$files
}
finally {
$ErrorActionPreference = $prevErrorAction
}
}

<#
.SYNOPSIS
Checks whether any changed files match the fullBuildPatterns from AL-Go settings.
Expand Down Expand Up @@ -413,7 +469,10 @@ function Get-AffectedAppNames {
return [PSCustomObject]$runAll
}

$changedFiles = Get-ChangedFilesForCI
$changedFiles = Get-PullRequestMergeChangedFiles
if (-not $changedFiles) {
$changedFiles = Get-ChangedFilesForCI -CompareFromMergeBase
}
if (-not $changedFiles) {
Write-Host "BUILD OPTIMIZATION: Running all tests - could not determine changed files"
return [PSCustomObject]$runAll
Expand Down Expand Up @@ -500,4 +559,38 @@ function Test-ShouldSkipTestApp {
return $false
}

Export-ModuleMember -Function Get-AppDependencyGraph, Get-AppForFile, Get-AffectedApps, Get-ChangedFilesForCI, Test-FullBuildPatternsMatch, Get-AffectedAppNames, Test-ShouldSkipTestApp
<#
.SYNOPSIS
Filters the test apps to run in a pull request build to those affected by the change.
.DESCRIPTION
Pull request builds run only test apps that depend, directly or transitively, on an app the
pull request changes. All other events (merge queue, push, schedule, workflow_dispatch) run
every test app, which is where full coverage is assured. Falls back to running every app
whenever the change set cannot be mapped safely (see Get-AffectedAppNames).
.PARAMETER AppNames
Test app names the job would otherwise run.
.PARAMETER BaseFolder
Root of the repository.
.OUTPUTS
String array of test app names to run.
#>
function Select-TestAppsToRun {
[CmdletBinding()]
[OutputType([string[]])]
param(
[Parameter(Mandatory)]
[AllowEmptyCollection()]
[string[]] $AppNames,
[Parameter(Mandatory)]
[string] $BaseFolder,
[string] $CacheFile = (Join-Path ([System.IO.Path]::GetTempPath()) 'BuildOptimization_AffectedApps.json')
)

if ($env:GITHUB_EVENT_NAME -ne 'pull_request') { return $AppNames }

$selected = @($AppNames | Where-Object { -not (Test-ShouldSkipTestApp -AppName $_ -BaseFolder $BaseFolder -CacheFile $CacheFile) })
Write-Host "BUILD OPTIMIZATION: Running $($selected.Count) of $($AppNames.Count) test app(s) affected by this pull request"
return [string[]]$selected
}

Export-ModuleMember -Function Get-AppDependencyGraph, Get-AppForFile, Get-AffectedApps, Get-ChangedFilesForCI, Get-PullRequestMergeChangedFiles, Test-FullBuildPatternsMatch, Get-AffectedAppNames, Test-ShouldSkipTestApp, Select-TestAppsToRun
2 changes: 2 additions & 0 deletions build/scripts/ParallelTestExecution.psm1
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ if (-not (Get-Command Write-Log -ErrorAction SilentlyContinue)) {
}
}
Import-Module (Join-Path $PSScriptRoot "ALAppBuild.psm1" -Resolve)
Import-Module (Join-Path $PSScriptRoot "BuildOptimization.psm1" -Resolve)

<#
.SYNOPSIS
Expand Down Expand Up @@ -1557,6 +1558,7 @@ function Invoke-PerProjectTestRun {

$installed = Get-InstalledTestAppNames -ContainerName $parameters.containerName -Tenant $parameters.tenant -Country $country
$appNamesToTest = Get-AppNamesForBucket -InstalledTestAppNames $installed -TestType $testType -BucketNumber $bucketNumber
$appNamesToTest = @(Select-TestAppsToRun -AppNames $appNamesToTest -BaseFolder (Get-BaseFolder))

if ($appNamesToTest.Count -eq 0) {
Write-Host "No test apps to run for testType '$testType' in this project."
Expand Down
179 changes: 179 additions & 0 deletions build/scripts/PullRequestBuildScope.psm1
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
<#
.SYNOPSIS
Narrows the Pull Request Build matrix to the countries and test modes a pull request affects.
.DESCRIPTION
Every country project (Apps XX) also contains the W1 apps, so with AL-Go incremental builds any
W1 change rebuilds and retests all countries. Pull request builds instead run W1 plus the
countries whose own code the pull request changes. Full country coverage is provided by the
merge queue (all-country compilation) and scheduled full-matrix runs on official branches.
Runs in the Initialization job before AL-Go reads settings, and only rewrites files in that
job's workspace.
#>

$ErrorActionPreference = "Stop"

Import-Module (Join-Path $PSScriptRoot "BuildOptimization.psm1" -Resolve)

$script:FullMatrixLabel = 'full-country-matrix'
$script:SentinelCountries = @('DE', 'US')
$script:RegionCountries = @{ APAC = @('AU', 'NZ'); DACH = @('AT', 'CH', 'DE'); NA = @('CA', 'MX', 'US') }
$script:InfrastructurePatterns = @(
'build/*',
'src/rulesets/*',
'.github/*.json',
'.github/actions/*',
'.github/workflows/PullRequestHandler.yaml',
'.github/workflows/_BuildALGoProject.yaml'
)

<#
.SYNOPSIS
Determines which country projects a pull request needs, based on its changed files.
.PARAMETER ChangedFiles
Files changed by the pull request, relative to the repo root.
.PARAMETER Countries
All country codes that have country projects (excluding W1).
.OUTPUTS
PSCustomObject with Countries (string[]) and Reasons (string[]).
#>
function Get-PullRequestCountries {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[string[]] $ChangedFiles,
[Parameter(Mandatory)]
[string[]] $Countries
)

$selected = [System.Collections.Generic.SortedSet[string]]::new()
$reasons = [System.Collections.Generic.List[string]]::new()

foreach ($file in $ChangedFiles) {
$path = $file.Replace('\', '/')
$codes = @()
if ($path -match '^src/(Apps|Layers)/([^/]+)/') {
$folder = $Matches[2].ToUpperInvariant()
if ($script:RegionCountries.ContainsKey($folder)) { $codes = $script:RegionCountries[$folder] }
elseif ($Countries -contains $folder) { $codes = @($folder) }
}
elseif ($path -match '^build/projects/(Test )?Apps ([A-Za-z]{2})/') {
$folder = $Matches[2].ToUpperInvariant()
if ($Countries -contains $folder) { $codes = @($folder) }
}
elseif ($script:InfrastructurePatterns | Where-Object { $path -like $_ }) {
$codes = $script:SentinelCountries
}

foreach ($code in ($codes | Where-Object { $Countries -contains $_ })) {
if ($selected.Add($code)) { $reasons.Add("$code <- $path") }
}
}

return [PSCustomObject]@{ Countries = [string[]]@($selected); Reasons = [string[]]@($reasons) }
}

<#
.SYNOPSIS
Removes legacy test buckets when the pull request cannot affect any legacy test app.
.PARAMETER BuildModes
Build modes configured for a test project.
.PARAMETER Affected
Result of Get-AffectedAppNames (RunAll, AppNames).
.PARAMETER LegacyTestAppNames
App names listed in the LegacyTests-* buckets of TestConfiguration.json.
#>
function Get-PullRequestTestBuildModes {
[CmdletBinding()]
[OutputType([string[]])]
param(
[Parameter(Mandatory)]
[AllowEmptyCollection()]
[string[]] $BuildModes,
[Parameter(Mandatory)]
$Affected,
[Parameter(Mandatory)]
[string[]] $LegacyTestAppNames
)

if ($Affected.RunAll) { return $BuildModes }
if (@($Affected.AppNames | Where-Object { $LegacyTestAppNames -contains $_ }).Count -gt 0) { return $BuildModes }
return [string[]]@($BuildModes | Where-Object { $_ -notlike 'LegacyTestsBucket*' })
}

<#
.SYNOPSIS
Rewrites the Pull Request Build settings in the current workspace to scope a pull request build.
.DESCRIPTION
No-op for other events, when the pull request has the full-country-matrix label, or when the
pull request's changes cannot be determined (AL-Go then builds as before).
.PARAMETER BaseFolder
Root of the repository checkout.
#>
function Set-PullRequestBuildScope {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[string] $BaseFolder
)

if ($env:GITHUB_EVENT_NAME -ne 'pull_request') { return }

$prEvent = Get-Content $env:GITHUB_EVENT_PATH -Raw | ConvertFrom-Json
if (@($prEvent.pull_request.labels | Where-Object { $_.name -eq $script:FullMatrixLabel }).Count -gt 0) {
Write-Host "PR BUILD SCOPE: '$($script:FullMatrixLabel)' label present - building every country"
return
}

$changedFiles = Get-PullRequestMergeChangedFiles
if (-not $changedFiles) {
Write-Host "PR BUILD SCOPE: Could not determine pull request changes - building every country"
return
}

$projectsFolder = Join-Path $BaseFolder 'build/projects'
$projectNames = @(Get-ChildItem -Path $projectsFolder -Directory | Where-Object { Test-Path (Join-Path $_.FullName '.AL-Go/settings.json') } | Select-Object -ExpandProperty Name)
$countries = @($projectNames | Where-Object { $_ -match '^Apps ([A-Z]{2})$' -and $Matches[1] -ne 'W1' } | ForEach-Object { $_.Substring(5) })

$scope = Get-PullRequestCountries -ChangedFiles $changedFiles -Countries $countries
$projects = @($projectNames | Where-Object {
-not ($_ -match '^(Test )?Apps ([A-Z]{2})$' -and $Matches[2] -ne 'W1' -and $scope.Countries -notcontains $Matches[2])
} | ForEach-Object { Join-Path 'build' (Join-Path 'projects' $_) })

$settingsFile = Join-Path $BaseFolder '.github/Pull Request Build.settings.json'
$settings = Get-Content $settingsFile -Raw | ConvertFrom-Json
$conditional = @($settings.conditionalSettings | Where-Object { $_.triggers -notcontains 'pull_request' })
$conditional += [PSCustomObject]@{ triggers = @('pull_request'); settings = [PSCustomObject]@{ projects = $projects } }
$settings.conditionalSettings = $conditional
$settings | ConvertTo-Json -Depth 10 | Set-Content -Path $settingsFile -Encoding UTF8

$affected = Get-AffectedAppNames -BaseFolder $BaseFolder
$testConfig = Get-Content (Join-Path $BaseFolder 'build/scripts/TestConfiguration.json') -Raw | ConvertFrom-Json
$legacyApps = @($testConfig.PSObject.Properties | Where-Object { $_.Name -like 'LegacyTests-*' } | ForEach-Object { $_.Value })
$droppedModes = @()
foreach ($project in @($projectNames | Where-Object { $_ -like 'Test Apps *' })) {
$projectSettingsFile = Join-Path $projectsFolder "$project/.AL-Go/settings.json"
$projectSettings = Get-Content $projectSettingsFile -Raw | ConvertFrom-Json
if (-not $projectSettings.buildModes) { continue }
$modes = Get-PullRequestTestBuildModes -BuildModes $projectSettings.buildModes -Affected $affected -LegacyTestAppNames $legacyApps
if ($modes.Count -ne @($projectSettings.buildModes).Count) {
$droppedModes += @($projectSettings.buildModes | Where-Object { $modes -notcontains $_ })
$projectSettings.buildModes = $modes
$projectSettings | ConvertTo-Json -Depth 20 | Set-Content -Path $projectSettingsFile -Encoding UTF8
}
}

$countryText = if ($scope.Countries.Count) { $scope.Countries -join ', ' } else { 'none' }
$modeText = if ($droppedModes.Count) { ($droppedModes | Select-Object -Unique) -join ', ' } else { 'none' }
$summary = @(
"### Pull request build scope",
"",
"- Countries built besides W1: $countryText",
"- Test modes skipped (no affected legacy test app): $modeText",
"- Add the ``$($script:FullMatrixLabel)`` label and re-run to build every country.",
""
) + @($scope.Reasons | ForEach-Object { " - $_" })
$summary | ForEach-Object { Write-Host "PR BUILD SCOPE: $_" }
if ($env:GITHUB_STEP_SUMMARY) { $summary | Add-Content -Path $env:GITHUB_STEP_SUMMARY -Encoding UTF8 }
}

Export-ModuleMember -Function Get-PullRequestCountries, Get-PullRequestTestBuildModes, Set-PullRequestBuildScope
3 changes: 3 additions & 0 deletions build/scripts/ResearchIgnorePaths.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# RESEARCH ONLY: paths changed by the CI stack itself
build/*
.github/*
Loading
Loading