diff --git a/.github/actions/TestObjectIdsAndManifests/action.ps1 b/.github/actions/TestObjectIdsAndManifests/action.ps1 index 261447eca95..ff7a7142362 100644 --- a/.github/actions/TestObjectIdsAndManifests/action.ps1 +++ b/.github/actions/TestObjectIdsAndManifests/action.ps1 @@ -1,4 +1,5 @@ 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 @@ -10,12 +11,28 @@ $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 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) { + Get-ChildItem -Path $layersFolder -Directory | + ForEach-Object { Join-Path $_.FullName 'BaseApp' } | + Where-Object { Test-Path -Path $_ } + } +) # 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 = @( @@ -81,4 +98,49 @@ $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 \ No newline at end of file +# 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/workflows/AddUnstableTestsFromRun.yaml b/.github/workflows/AddUnstableTestsFromRun.yaml index 40004084381..c4dfac6bb78 100644 --- a/.github/workflows/AddUnstableTestsFromRun.yaml +++ b/.github/workflows/AddUnstableTestsFromRun.yaml @@ -37,26 +37,33 @@ jobs: - name: Build branch filter id: filter shell: pwsh + env: + BRANCH_FILTER: ${{ inputs.branch }} run: | # Convert the comma-separated branch filter into the JSON array that GetGitBranches expects. - $patterns = '${{ inputs.branch }}'.Split(',') | ForEach-Object { $_.Trim() } | Where-Object { $_ } + $patterns = $env:BRANCH_FILTER.Split(',') | ForEach-Object { $_.Trim() } | Where-Object { $_ } $json = ConvertTo-Json @($patterns) -Compress Write-Host "Branch filter: $json" Add-Content -Encoding UTF8 -Path $env:GITHUB_OUTPUT -Value "includeJson=$json" + - 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: ${{ steps.filter.outputs.includeJson }} - name: Ensure JSON array id: ensureArray shell: pwsh + env: + BRANCHES_JSON: ${{ steps.getOfficialBranches.outputs.branchesJson }} run: | # PowerShell's ConvertTo-Json emits a bare string for single-element arrays. # Wrap it in an array if needed so the matrix strategy always receives a JSON array. - $raw = '${{ steps.getOfficialBranches.outputs.branchesJson }}' + $raw = $env:BRANCHES_JSON $parsed = $raw | ConvertFrom-Json if ($parsed -is [string]) { $parsed = @($parsed) } $json = ConvertTo-Json @($parsed) -Compress @@ -73,8 +80,11 @@ jobs: branch: ${{ fromJson(needs.GetBranches.outputs.updateBranches) }} fail-fast: false steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - name: Add unstable tests from run - uses: microsoft/BCApps/.github/actions/UpdateUnstableTests@main + uses: ./.github/actions/UpdateUnstableTests with: branch: ${{ matrix.branch }} run-id: ${{ inputs.runId }} diff --git a/.github/workflows/PullRequestHandler.yaml b/.github/workflows/PullRequestHandler.yaml index 188f06e3b36..a8a2331251c 100644 --- a/.github/workflows/PullRequestHandler.yaml +++ b/.github/workflows/PullRequestHandler.yaml @@ -210,6 +210,9 @@ jobs: if: (!failure() && !cancelled()) runs-on: windows-latest name: Verify App Changes + # Runs actions from the PR checkout, so only grant read access (no id-token or other write permissions) + permissions: + contents: read steps: - name: Checkout uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -217,10 +220,10 @@ 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 - - uses: microsoft/BCApps/.github/actions/VerifyMiappSync@main + - uses: ./.github/actions/VerifyMiappSync - - uses: microsoft/BCApps/.github/actions/ValidateCountryProjects@main + - uses: ./.github/actions/ValidateCountryProjects diff --git a/.github/workflows/SubmitStabilityJobs.yaml b/.github/workflows/SubmitStabilityJobs.yaml index 61a3a9dd8b8..1a5948345de 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: "['main', '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 e773e3188e4..26fa243739c 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/UpdateALGoSupportedBranches.yaml b/.github/workflows/UpdateALGoSupportedBranches.yaml index 62dfba81ebd..a0ad4bcf4ee 100644 --- a/.github/workflows/UpdateALGoSupportedBranches.yaml +++ b/.github/workflows/UpdateALGoSupportedBranches.yaml @@ -39,7 +39,7 @@ jobs: - name: Update AL-Go Supported Branches env: GH_TOKEN: ${{ steps.app-token.outputs.token }} - uses: microsoft/BCApps/.github/actions/RunAutomation@main + uses: ./.github/actions/RunAutomation with: automations: UpdateSystemFilesSchedule targetBranch: main diff --git a/.github/workflows/UpdateBCArtifactVersion.yaml b/.github/workflows/UpdateBCArtifactVersion.yaml index 51898a23137..7cfa09eb13e 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,UpdatePlatformVersion diff --git a/.github/workflows/UpdatePackageVersions.yaml b/.github/workflows/UpdatePackageVersions.yaml index 03916e5f8a0..be48df80149 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/UpdateUnstableTests.yaml b/.github/workflows/UpdateUnstableTests.yaml index ac030ed7bce..87efa45b553 100644 --- a/.github/workflows/UpdateUnstableTests.yaml +++ b/.github/workflows/UpdateUnstableTests.yaml @@ -58,9 +58,12 @@ jobs: outputs: updateBranches: ${{ steps.ensureArray.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: "['main', 'releases/*']" @@ -101,7 +104,7 @@ jobs: uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Update unstable tests - uses: microsoft/BCApps/.github/actions/UpdateUnstableTestsCombined@main + uses: ./.github/actions/UpdateUnstableTestsCombined with: branch: ${{ matrix.branch }} run-limit: ${{ inputs.runLimit || 3 }} diff --git a/build/scripts/AppObjectValidation.psm1 b/build/scripts/AppObjectValidation.psm1 index b20ca34b215..2570e7f7a49 100644 --- a/build/scripts/AppObjectValidation.psm1 +++ b/build/scripts/AppObjectValidation.psm1 @@ -147,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. @@ -155,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 = @() @@ -168,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 } @@ -178,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 @@ -188,6 +200,7 @@ function Get-FilesCollection return [PSCustomObject] @{ ObjectSignatures = $SourceFiles + ObjectDetails = $ObjectDetails TestObjects = $TestObjectSignatures DuplicateObjects = $DuplicateObjectSignatures } @@ -195,12 +208,13 @@ function Get-FilesCollection function GetALObjectInformation ( - [string] $FilePath + [string] $FilePath, + [string] $ObjectTypePattern = 'codeunit|page|table|query|report|xmlport' ) { # (? +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. + 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 + 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 + $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 + } + } + } + + 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/BuildOptimization.psm1 b/build/scripts/BuildOptimization.psm1 index 10a374ecca3..2c5d5a53037 100644 --- a/build/scripts/BuildOptimization.psm1 +++ b/build/scripts/BuildOptimization.psm1 @@ -169,6 +169,39 @@ function Get-AffectedApps { 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. @@ -178,26 +211,45 @@ function Get-AffectedApps { 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() + 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 } @@ -221,6 +273,9 @@ function Get-ChangedFilesForCI { } 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 } @@ -230,11 +285,40 @@ function Get-ChangedFilesForCI { $prevErrorAction = $ErrorActionPreference $ErrorActionPreference = 'Continue' try { - # Best-effort fetch of base commit (may not be in shallow clone) - git fetch origin $baseSha --depth=1 2>$null + # 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 + } + } - $files = @(git diff --name-only $baseSha $headSha 2>$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 } diff --git a/build/scripts/Miapp/MicroAppGitHelper.psm1 b/build/scripts/Miapp/MicroAppGitHelper.psm1 index e84a2abad6f..59c476a03e3 100644 --- a/build/scripts/Miapp/MicroAppGitHelper.psm1 +++ b/build/scripts/Miapp/MicroAppGitHelper.psm1 @@ -436,20 +436,52 @@ function Get-GitCurrentBranch { $script:MiappBaseBranch = $null +function Test-MiappRemoteBranchExists { + <# + .SYNOPSIS + Returns $true when 'refs/remotes/origin/' resolves in the current + repository. + #> + [CmdletBinding()] + [OutputType([bool])] + param( + [Parameter(Mandatory=$true)] + [ValidateNotNullOrEmpty()] + [string] $Branch + ) + + $null = (git rev-parse --verify --quiet "refs/remotes/origin/$Branch" 2>$null) + return ($LASTEXITCODE -eq 0) +} + function Get-MiappBaseBranch { <# .SYNOPSIS - Returns the base branch Miapp integrates from, derived from the repository - Miapp operates on - not from any environment variable. + Returns the base branch Miapp integrates from. .DESCRIPTION - The base branch is resolved from 'origin/HEAD' of the current repository so - that Miapp always targets that repository's own default branch, even when it - runs inside a submodule whose default branch differs from the outer repo. - Deriving it from the repository (rather than an ambient variable such as - $env:RepoBranchName) avoids constructing a non-existent ref like - 'origin/master' when the outer repo and the submodule use different default - branch names. The resolved value is cached for the lifetime of the module. + Resolution order: + + 1. An explicitly requested base branch in $env:RepoBranchName - but only when + 'origin/' actually exists in the current repository. Callers such as + the VerifyMiappSync action set this to the pull request target branch + ($env:GITHUB_BASE_REF), so a PR that targets a release branch (e.g. + 'releases/29.x') is diffed against that branch. Without this, the base falls + through to the default branch and the changelist becomes the entire + divergence between the release branch and the default branch - thousands of + files - even for PRs that change nothing Miapp-relevant. + + 2. Otherwise 'origin/HEAD' of the current repository, via + 'git symbolic-ref --short refs/remotes/origin/HEAD' with 'git remote show + origin' as a fallback. This makes Miapp target that repository's own default + branch even when it runs inside a submodule whose default branch differs from + the outer repo, avoiding a non-existent ref like 'origin/master'. + + Requiring the requested branch to exist in step 1 preserves the submodule + behaviour: an ambient 'RepoBranchName=master' that does not exist in this + repository is ignored, and resolution falls back to 'origin/HEAD'. + + The resolved value is cached for the lifetime of the module. #> [CmdletBinding()] [OutputType([string])] @@ -459,6 +491,11 @@ function Get-MiappBaseBranch { return $script:MiappBaseBranch } + if ($env:RepoBranchName -and (Test-MiappRemoteBranchExists $env:RepoBranchName)) { + $script:MiappBaseBranch = $env:RepoBranchName + return $script:MiappBaseBranch + } + [string] $originHeadRef = (git symbolic-ref --quiet --short refs/remotes/origin/HEAD 2>$null) if ($originHeadRef -imatch '^origin/(.+)$') { $script:MiappBaseBranch = $Matches[1] diff --git a/build/scripts/Miapp/MicroAppIntegrate.psm1 b/build/scripts/Miapp/MicroAppIntegrate.psm1 index 5879b8b3a83..4157fd1db71 100644 --- a/build/scripts/Miapp/MicroAppIntegrate.psm1 +++ b/build/scripts/Miapp/MicroAppIntegrate.psm1 @@ -177,7 +177,7 @@ function IntegrateBranchedObjects { if($Params.Country) { # Match country code from paths like src/Layers/CZ/, src/Layers/MX/, etc. - $Matched = $branch -match 'src/Layers/(?.+?(?=/)' + $Matched = $branch -match 'src/Layers/(?.+?(?=/))' if($Matched) { $Matched = $Matches.Country -eq $Params.Country diff --git a/build/scripts/Miapp/MicroSnapApp.psm1 b/build/scripts/Miapp/MicroSnapApp.psm1 index e0f9692a831..937b8d46db0 100644 --- a/build/scripts/Miapp/MicroSnapApp.psm1 +++ b/build/scripts/Miapp/MicroSnapApp.psm1 @@ -29,7 +29,10 @@ function Invoke-MiSnapApp Write-Host "Validating propagation for $($Files.Count) file(s)..." - [string[]] $actualFiles = $Files | select -Unique + [string[]] $actualFiles = $Files ` + | % { Expand-MiappExclusionFile $_ } ` + | ? { $_ } ` + | select -Unique [string[]] $expectedFiles = $actualFiles | % { GetBranchedObjectFileNames "$(Get-GitRoot)/$_" } | select -Unique [string[]] $missingFiles = $expectedFiles | ? { $actualFiles -inotcontains $_ } @@ -43,6 +46,34 @@ function Invoke-MiSnapApp } } +<# +.SYNOPSIS +Expands a committed Miapp exclusion snapshot into the file paths it excludes. + +.DESCRIPTION +When a file lives under `MiappConfig.ExclusionDir` (the `.miappsnap` snapshot folder), +it is a JSON list of paths that were explicitly excluded from propagation via +'Invoke-Miapp'. Those paths are returned so they are treated as already integrated and +not reported as missing. Any other file is returned unchanged. This mirrors the original +NAV GitMiapp behavior that was lost when the verification step was ported to git. +#> +function Expand-MiappExclusionFile { + [CmdletBinding()] + [OutputType([string[]], [string])] + param( + [Parameter(Mandatory=$true)] + [ValidateNotNullOrEmpty()] + [string] $File + ) + + [string] $parentPath = Get-CanonicalParentPath "$(Get-GitRoot)/$File" -RelativeToRepoRoot + if ($parentPath -ieq $MiappConfig.ExclusionDir) { + Get-ExclusionList "$(Get-GitRoot)/$File" + } else { + $File + } +} + <# .SYNOPSIS Returns files committed locally since the base branch (origin/HEAD), relative to the repo root. diff --git a/build/scripts/tests/AppObjectValidation.Test.ps1 b/build/scripts/tests/AppObjectValidation.Test.ps1 new file mode 100644 index 00000000000..80cf1a30088 --- /dev/null +++ b/build/scripts/tests/AppObjectValidation.Test.ps1 @@ -0,0 +1,310 @@ +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 "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' + 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/BuildOptimization.Test.ps1 b/build/scripts/tests/BuildOptimization.Test.ps1 index 76340ab3c81..8ee671c9766 100644 --- a/build/scripts/tests/BuildOptimization.Test.ps1 +++ b/build/scripts/tests/BuildOptimization.Test.ps1 @@ -243,6 +243,43 @@ Describe "BuildOptimization" { if ($tempFile) { Remove-Item $tempFile -ErrorAction SilentlyContinue } } } + + It "returns only newly added files when the A diff filter is requested" { + $savedActions = $env:GITHUB_ACTIONS + $savedEvent = $env:GITHUB_EVENT_NAME + $savedEventPath = $env:GITHUB_EVENT_PATH + $tempFile = [System.IO.Path]::GetTempFileName() + try { + $env:GITHUB_ACTIONS = 'true' + $env:GITHUB_EVENT_NAME = 'pull_request' + @{ + pull_request = @{ + base = @{ sha = 'base-sha' } + head = @{ sha = 'head-sha' } + } + } | ConvertTo-Json -Depth 5 | Set-Content $tempFile + $env:GITHUB_EVENT_PATH = $tempFile + Mock -ModuleName BuildOptimization git { + $global:LASTEXITCODE = 0 + if ($args -contains 'merge-base') { + return 'merge-base-sha' + } + if ($args -contains '--diff-filter=A') { + return 'src/Apps/W1/Example/App/Added.al' + } + } + + $result = @(Get-ChangedFilesForCI -DiffFilter 'A' -CompareFromMergeBase -RequireChangeDetection) + + $result | Should -Be @('src/Apps/W1/Example/App/Added.al') + } + finally { + $env:GITHUB_ACTIONS = $savedActions + $env:GITHUB_EVENT_NAME = $savedEvent + $env:GITHUB_EVENT_PATH = $savedEventPath + Remove-Item $tempFile -ErrorAction SilentlyContinue + } + } } Context "Test-FullBuildPatternsMatch" {