diff --git a/.github/actions/TestObjectIdsAndManifests/action.ps1 b/.github/actions/TestObjectIdsAndManifests/action.ps1 index 0c09ed336e7..ff7a7142362 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 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 $_ } + } ) -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/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 diff --git a/build/scripts/AppObjectValidation.psm1 b/build/scripts/AppObjectValidation.psm1 index f120cf4e4a8..2570e7f7a49 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,233 @@ 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. + 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 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/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\)' + } + } +}