This is an automated email from the ASF dual-hosted git repository.

rombert pushed a commit to branch issue/SLING-13436
in repository https://gitbox.apache.org/repos/asf/sling-tooling-jenkins.git

commit da31f32ed32d61aed68219632e1d1916239d4ae5
Author: Robert Munteanu <[email protected]>
AuthorDate: Tue Nov 24 10:54:14 2026 +0100

    SLING-13436 - Run PR checks on changed modules only for selected repos
---
 README.md                        |  26 ++++++
 tests/changed-modules.groovy     | 166 +++++++++++++++++++++++++++++++++++++++
 vars/slingOsgiBundleBuild.groovy | 129 ++++++++++++++++++++++++++++--
 3 files changed, 314 insertions(+), 7 deletions(-)

diff --git a/README.md b/README.md
index 71f8f19..a4918d3 100644
--- a/README.md
+++ b/README.md
@@ -11,6 +11,32 @@ builds and used as [Jenkins Shared 
Library](https://www.jenkins.io/doc/book/pipe
 See <https://cwiki.apache.org/confluence/display/SLING/Sling+Jenkins+Setup>
 for more info.
 
+## Build only changed modules on pull requests
+
+For multi-module repositories, opt in via the root `.sling-module.json`:
+
+```json
+{
+  "jenkins": {
+    "buildChangedModules": true
+  }
+}
+```
+
+Jenkins compares the checkout with its merge base with the PR target. When all 
changes map to
+leaf modules declared in the root Maven reactor, the sanity check and build 
matrix run with
+`-pl <module paths> -am`. This includes required reactor prerequisites, not 
unchanged modules
+that depend on the selected modules. SonarCloud analysis is skipped for these 
partial builds.
+
+The flag defaults to `false` and does not affect non-PR builds. Jenkins uses 
its normal Maven
+commands if the diff is unavailable or empty, changes fall outside leaf 
modules (including root or
+aggregator changes), or custom Maven options, extensions or profiles make 
reactor selection uncertain.
+
+A partial build includes `module <path>` (or `modules <paths>` for several) in 
its Jenkins build
+name and reports a check with that name through the Jenkins Checks API. 
Without a configured
+GitHub Checks publisher with Checks write permission, the scope is visible 
only in Jenkins.
+The existing Jenkins commit status is unchanged.
+
 ## Test Changes
 
 As changes to master are active immediately on all jobs, it is recommended to 
test any changes in the Jenkins Shared Library by pushing them to a dedicated 
branch (in this example named `mybranch`) and then reference that branch from 
within a branch of any other project, by using a `Jenkinsfile` explicitly via 
`@Library` as follows
diff --git a/tests/changed-modules.groovy b/tests/changed-modules.groovy
new file mode 100644
index 0000000..7b4b7eb
--- /dev/null
+++ b/tests/changed-modules.groovy
@@ -0,0 +1,166 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+// Run from the repository root with: groovy tests/changed-modules.groovy
+class Build {
+    String result = 'SUCCESS'
+    String displayName
+    String getCurrentResult() { result }
+}
+
+def loader = new GroovyClassLoader(getClass().classLoader)
+loader.parseClass('''
+    package org.apache.sling.jenkins
+    class SlingJenkinsHelper {
+        def runWithErrorHandling(config, Closure build) {
+            try {
+                build()
+            } catch (Exception e) {
+                build.owner.currentBuild.result = e instanceof 
InterruptedException ? 'ABORTED' : 'FAILURE'
+                throw e
+            }
+        }
+    }
+''')
+
+// Jenkins' Groovy accepts the two pre-existing local static constants; stock 
Groovy does not.
+def source = new File('vars/slingOsgiBundleBuild.groovy').text.replace('static 
final String', 'final String')
+def start = { Map scenario = [:] ->
+    def poms = scenario.poms ?: [
+        'pom.xml': ['slingshot', 'mail-archive'],
+        'slingshot/pom.xml': [],
+        'mail-archive/pom.xml': ['server', 'ui'],
+        'mail-archive/server/pom.xml': [],
+        'mail-archive/ui/pom.xml': []
+    ]
+    def commands = [:].withDefault { [] }
+    def checks = []
+    def log = []
+    def build = new Build()
+    def stageName
+    def nodeLabel
+    def runMaven = { command, launcher ->
+        if ( command.startsWith('mvn ') ) {
+            commands[launcher].add(command.toString())
+            if ( scenario.failStage == stageName ) {
+                throw scenario.failure
+            }
+        }
+    }
+    def config = [jdks: [17], mavenGoal: 'verify'] + (scenario.config ?: [:])
+    def bindings = new Binding([
+        env: [BRANCH_NAME: 'PR-1', CHANGE_ID: '1', CHANGE_TARGET: 'master', 
BUILD_NUMBER: '7'] + (scenario.env ?: [:]),
+        BRANCH_NAME: scenario.env?.BRANCH_NAME ?: 'PR-1', CHANGE_BRANCH: 
'example', CHANGE_ID: '1', CHANGE_TARGET: 'master',
+        currentBuild: build,
+        scm: 'scm',
+        checkout: { scm -> },
+        node: { label, Closure body -> nodeLabel = label; body() },
+        stage: { name, Closure body -> stageName = name; body() },
+        timeout: { Map options, Closure body -> body() },
+        dir: { name, Closure body -> body() },
+        withMaven: { Map options, Closure body -> body() },
+        withCredentials: { List options, Closure body -> body() },
+        parallel: { Map branches -> branches.findAll { it.key != 'failFast' 
}.values()*.call() },
+        sh: { command ->
+            if ( command instanceof Map ) {
+                if ( command.script.startsWith('git config') ) {
+                    return 'https://github.com/apache/sling-samples.git\n'
+                }
+                assert command.script.contains('git diff --merge-base 
--name-only -z --no-renames FETCH_HEAD HEAD --')
+                if ( scenario.gitFailure ) {
+                    throw scenario.gitFailure
+                }
+                return scenario.get('diff', 
'slingshot/src/main/Example.java\u0000')
+            }
+            runMaven(command, 'sh')
+        },
+        bat: { command -> runMaven(command, 'bat') },
+        isUnix: { nodeLabel != 'Windows' },
+        fileExists: { path -> path == '.sling-module.json' || path in 
(scenario.files ?: []) },
+        readJSON: { Map args -> [jenkins: config] },
+        readMavenPom: { Map args = [:] ->
+            if (!args.file) return [version: '1.0']
+            assert poms.containsKey(args.file.toString())
+            [modules: poms[args.file.toString()], profiles: args.file == 
'pom.xml' ? scenario.profiles ?: [] : []]
+        },
+        publishChecks: { Map args ->
+            if (scenario.noChecks) throw new NoSuchMethodError('publishChecks')
+            checks.add(args)
+        },
+        echo: { message -> log.add(message.toString()) }
+    ])
+    ['properties', 'pipelineTriggers', 'buildDiscarder', 'logRotator', 'cron', 
'artifactsPublisher',
+     'junitPublisher', 'openTasksPublisher', 
'dependenciesFingerprintPublisher', 'string'].each { name ->
+        bindings.setVariable(name, { arg -> arg })
+    }
+    def pipeline = new GroovyShell(loader, bindings).parse(source)
+    Throwable thrown = null
+    try {
+        pipeline.call()
+    } catch (Exception e) {
+        thrown = e
+    }
+    [commands: commands.values().flatten(), windowsCommands: commands.bat, 
checks: checks,
+     build: build, log: log, thrown: thrown]
+}
+
+def enabled = [config: [buildChangedModules: true]]
+def partial = start(enabled)
+assert !partial.thrown
+assert partial.commands.size() == 3 // Sanity check and two matrix legs, no 
SonarCloud.
+assert partial.windowsCommands.size() == 1
+assert partial.commands.every { it.endsWith(' -pl slingshot -am') }
+assert partial.build.displayName == '#7 (module slingshot)'
+assert partial.checks*.name == ['module slingshot']
+assert partial.checks*.conclusion == ['SUCCESS']
+
+def nested = start(enabled + [diff: 
'slingshot/pom.xml\u0000mail-archive/ui/src/example\nname\u0000mail-archive/ui/README.md\u0000'])
+assert !nested.thrown
+assert nested.commands.every { it.endsWith(' -pl mail-archive/ui,slingshot 
-am') }
+assert nested.checks*.name == ['modules mail-archive/ui, slingshot']
+
+def fullBuilds = [[:], enabled + [env: [BRANCH_NAME: 'master', CHANGE_ID: 
null, CHANGE_TARGET: null]],
+    enabled + [env: [BRANCH_NAME: 'feature', CHANGE_ID: null, CHANGE_TARGET: 
null]],
+    enabled + [gitFailure: new IOException('Missing base')], enabled + [files: 
['.mvn/maven.config']],
+    [config: [buildChangedModules: true, additionalMavenParams: 
'--projects=slingshot']],
+    enabled + [profiles: [[modules: ['jdk-specific']]]]]
+['', 'slingshot/src/Example.java\u0000pom.xml\u0000', 
'mail-archive/pom.xml\u0000',
+ 'slingshot/src/Example.java\u0000DEPRECATED/other/pom.xml\u0000'].each { diff 
->
+    fullBuilds.add(enabled + [diff: diff])
+}
+fullBuilds.each { scenario ->
+    def full = start(scenario)
+    assert !full.thrown
+    assert full.commands.every { !it.contains(' -am') }
+    assert full.commands.any { it.contains(':sonar ') }
+    assert !full.checks
+    assert !full.build.displayName
+}
+
+[(new IOException('Build failed')): 'FAILURE', (new 
InterruptedException('Interrupted')): 'CANCELED'].each { error, result ->
+    def failed = start(enabled + [failStage: 'Sanity Check', failure: error])
+    assert failed.thrown.is(error)
+    assert failed.checks*.conclusion == [result]
+}
+
+def withoutChecks = start(enabled + [noChecks: true])
+assert !withoutChecks.thrown
+assert withoutChecks.build.displayName == '#7 (module slingshot)'
+assert withoutChecks.log.any { it.contains('Checks API step is unavailable') }
+println 'Changed-module pipeline tests passed.'
diff --git a/vars/slingOsgiBundleBuild.groovy b/vars/slingOsgiBundleBuild.groovy
index 8632b1e..29dc0a4 100644
--- a/vars/slingOsgiBundleBuild.groovy
+++ b/vars/slingOsgiBundleBuild.groovy
@@ -23,6 +23,7 @@ def call(Map params = [:]) {
         archivePatterns: [],
         mavenGoal: '',
         additionalMavenParams: '',
+        buildChangedModules: false,
         rebuildFrequency: '@weekly',
         enabled: true,
         emailRecipients: [],
@@ -32,6 +33,7 @@ def call(Map params = [:]) {
         buildTimeout: 30 // default timeout in minutes
     ]
     boolean shouldDeploy = false
+    List<String> changedModules = []
     node(globalConfig.mainNodeLabel) {
         timeout(time:5, unit: 'MINUTES') {
             stage('Init') {
@@ -54,6 +56,10 @@ def call(Map params = [:]) {
                 }
                 echo "Final job config: ${jobConfig}"
                 shouldDeploy = getShouldDeploy()
+                if ( jobConfig.enabled && jobConfig.buildChangedModules == 
true &&
+                        env.CHANGE_ID && env.CHANGE_TARGET && 
!isOnMainBranch() ) {
+                    changedModules = selectChangedModules(jobConfig)
+                }
             }
         }
     }
@@ -78,8 +84,9 @@ def call(Map params = [:]) {
     }
 
     if ( jobConfig.enabled ) {
+        String reactorArgs = changedModules ? " -pl 
${changedModules.join(',')} -am" : ''
         def helper = new SlingJenkinsHelper()
-        helper.runWithErrorHandling(jobConfig, {
+        def build = {
             // the reference build is always the first one, and the only one 
to deploy, archive artifacts, etc
             // usually this is the build done with the oldest JDK version, to 
ensure maximum compatibility
             boolean isReferenceStage = true
@@ -90,7 +97,7 @@ def call(Map params = [:]) {
             // parallel execution of all build jobs
             jobConfig.jdks.each { jdkVersion -> 
                 jobConfig.operatingSystems.each { operatingSystem ->
-                    stageDefinition = defineStage(globalConfig, jobConfig, 
jdkVersion, operatingSystem, isReferenceStage, shouldDeploy)
+                    stageDefinition = defineStage(globalConfig, jobConfig, 
jdkVersion, operatingSystem, isReferenceStage, shouldDeploy, reactorArgs)
                     if ( isReferenceStage ) {
                         referenceJdkVersion = jdkVersion
                     }
@@ -109,7 +116,7 @@ def call(Map params = [:]) {
                         withMaven(maven: globalConfig.mvnVersion,
                             jdk: jenkinsJdkLabel(referenceJdkVersion, 
globalConfig),
                             publisherStrategy: 'EXPLICIT') {
-                                String mvnCommand = "mvn --show-version -U -B 
-e clean compile ${additionalMavenParams(jobConfig)}"
+                                String mvnCommand = "mvn --show-version -U -B 
-e clean compile ${additionalMavenParams(jobConfig)}${reactorArgs}"
                                 if (isUnix()) {
                                     sh mvnCommand
                                 } else {
@@ -132,12 +139,119 @@ def call(Map params = [:]) {
                     }
                 }
             }
-        })
+        }
+        String checkName = changedModules ? moduleCheckName(changedModules) : 
''
+        if ( checkName ) {
+            currentBuild.displayName = "#${env.BUILD_NUMBER} (${checkName})"
+        }
+        try {
+            helper.runWithErrorHandling(jobConfig, build)
+        } finally {
+            if ( checkName ) {
+                publishModuleCheck(checkName, changedModules)
+            }
+        }
     } else {
         echo "Job is disabled, not building"
     }
 }
 
+def selectChangedModules(def jobConfig) {
+    try {
+        // Do not combine two independent sources of reactor selection or 
execute a custom Maven root.
+        def reactorOptions = 
/(?:^|\s)(?:-pl|--projects|-am|-amd|--also-make(?:-dependents)?|-N|--non-recursive|-rf|--resume-from|-f|--file)(?:[=\s]|$)/
+        if ( fileExists('.mvn/maven.config') || 
fileExists('.mvn/extensions.xml') ||
+                additionalMavenParams(jobConfig) =~ reactorOptions || 
jobConfig.mavenGoal =~ reactorOptions ) {
+            echo 'Building full Maven reactor: custom Maven reactor options 
may be in use.'
+            return []
+        }
+
+        // Jenkins changelogs are relative to the previous build, not the PR 
target. Fetch the
+        // target explicitly so head and merge checkouts work without relying 
on a cached ref.
+        String diff = sh(returnStdout: true, script: '''
+            set -e
+            test "$(git rev-parse --is-shallow-repository)" = false
+            GIT_TERMINAL_PROMPT=0 git fetch --no-tags --no-recurse-submodules 
origin "refs/heads/$CHANGE_TARGET"
+            git diff --merge-base --name-only -z --no-renames FETCH_HEAD HEAD 
--
+        ''', encoding: 'UTF-8')
+        List<String> modules = changedReactorModules(diff)
+        if ( modules ) {
+            echo "Building changed Maven modules (plus reactor prerequisites): 
${modules.join(', ')}"
+        } else {
+            echo 'Building full Maven reactor: the PR changes cannot be 
limited to reactor modules.'
+        }
+        return modules
+    } catch ( InterruptedException e ) {
+        throw e
+    } catch ( Exception e ) {
+        echo "Building full Maven reactor: could not determine changed modules 
(${e.message})."
+        return []
+    }
+}
+
+def changedReactorModules(String diff) {
+    if ( !diff ) {
+        return []
+    }
+
+    // Walk only declared reactor modules, not every pom.xml in the checkout 
(e.g. standalone samples).
+    def projects = [:]
+    def pending = ['']
+    for ( int i = 0; i < pending.size(); i++ ) {
+        String path = pending[i]
+        def pom = readMavenPom(file: path ? "${path}/pom.xml" : 'pom.xml')
+        if ( pom.profiles.any { it.modules } ) {
+            return [] // The reactor may differ across profiles, JDKs or 
operating systems.
+        }
+        projects[path] = !pom.modules.isEmpty()
+        for ( String module : pom.modules ) {
+            // Paths become Maven arguments on both Unix and Windows. Accept 
only simple relative directories.
+            if ( !(module ==~ 
/[A-Za-z0-9_][A-Za-z0-9_.-]*(\/[A-Za-z0-9_][A-Za-z0-9_.-]*)*/) ) {
+                return []
+            }
+            String child = path ? "${path}/${module}" : module
+            if ( pending.contains(child) ) {
+                return []
+            }
+            pending.add(child)
+        }
+    }
+
+    Set<String> changed = [] as Set
+    for ( String file : diff.split('\u0000') ) {
+        String module = ''
+        for ( String candidate : pending ) {
+            if ( candidate.length() > module.length() && 
file.startsWith(candidate + '/') ) {
+                module = candidate
+            }
+        }
+        if ( !module || projects[module] ) {
+            return [] // Unmapped paths and changes owned by an aggregator may 
affect other projects.
+        }
+        changed.add(module)
+    }
+    return changed.toList().sort()
+}
+
+def moduleCheckName(List<String> modules) {
+    String name = "${modules.size() == 1 ? 'module' : 'modules'} 
${modules.join(', ')}"
+    return name.size() <= 100 ? name : name.take(97) + '...'
+}
+
+def publishModuleCheck(String name, List<String> modules) {
+    def conclusions = [SUCCESS: 'SUCCESS', ABORTED: 'CANCELED', NOT_BUILT: 
'SKIPPED']
+    try {
+        publishChecks name: name, conclusion: 
conclusions[currentBuild.currentResult] ?: 'FAILURE',
+            summary: "Selected Maven modules: ${modules.join(', ')}. Required 
reactor prerequisites are included via `-am`."
+    } catch ( InterruptedException e ) {
+        throw e
+    } catch ( NoSuchMethodError e ) {
+        echo 'Cannot publish module check: the Jenkins Checks API step is 
unavailable.'
+    } catch ( Exception e ) {
+        echo "Could not publish module check: ${e.message}"
+    }
+}
+
 def jenkinsJdkLabel(int jdkVersion, def globalConfig) {
     def label = globalConfig.availableJDKs[jdkVersion]
     if ( !label )
@@ -165,7 +279,7 @@ def additionalMavenParams(def jobConfig) {
         branchConfig.additionalMavenParams : jobConfig.additionalMavenParams
 }
 
-def defineStage(def globalConfig, def jobConfig, def jdkVersion, def 
operatingSystem, boolean isReferenceStage, boolean shouldDeploy) {
+def defineStage(def globalConfig, def jobConfig, def jdkVersion, def 
operatingSystem, boolean isReferenceStage, boolean shouldDeploy, String 
reactorArgs = '') {
 
     def goal = jobConfig.mavenGoal ? jobConfig.mavenGoal : ( isReferenceStage 
? "deploy" : "verify" )
     def additionalMavenParams = additionalMavenParams(jobConfig)
@@ -204,7 +318,7 @@ def defineStage(def globalConfig, def jobConfig, def 
jdkVersion, def operatingSy
                 openTasksPublisher(disabled: !isReferenceStage),
                 dependenciesFingerprintPublisher(disabled: !isReferenceStage)
             ] ) {
-            String mvnCommand = "mvn --show-version -U -B -e clean ${goal} 
${additionalMavenParams} -Dci"
+            String mvnCommand = "mvn --show-version -U -B -e clean ${goal} 
${additionalMavenParams} -Dci${reactorArgs}"
             if (isUnix()) {
                 sh mvnCommand
             } else {
@@ -233,7 +347,8 @@ def defineStage(def globalConfig, def jobConfig, def 
jdkVersion, def operatingSy
                 }
                 if ( isReferenceStage ) {
                     // SonarQube must be executed on the same node in order to 
reuse artifact from the Maven build
-                    if ( jobConfig.sonarQubeEnabled ) {
+                    // A repository-wide scan needs build outputs from the 
full reactor.
+                    if ( jobConfig.sonarQubeEnabled && !reactorArgs ) {
                         stage('Analyse with SonarCloud') {
                             timeout(time: 30, unit: 'MINUTES') {
                                 analyseWithSonarCloud(globalConfig, jobConfig)

Reply via email to