jamesfredley commented on code in PR #15467: URL: https://github.com/apache/grails-core/pull/15467#discussion_r3214125770
########## grails-gradle/bom-property-overrides/src/main/groovy/org/grails/gradle/plugin/bom/BomManagedVersions.groovy: ########## @@ -0,0 +1,378 @@ +/* + * 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 + * + * https://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. + */ +package org.grails.gradle.plugin.bom + +import groovy.transform.CompileStatic +import org.gradle.api.Project +import org.gradle.api.artifacts.Configuration +import org.gradle.api.artifacts.DependencyResolveDetails +import org.gradle.api.logging.Logger +import org.gradle.api.logging.Logging +import org.w3c.dom.Document +import org.w3c.dom.Element +import org.w3c.dom.NodeList + +import javax.xml.parsers.DocumentBuilderFactory + +/** + * Lightweight replacement for the Spring Dependency Management plugin's + * version property override feature. + * + * <p>Parses BOM POM files to build a mapping of Maven property names + * (e.g., {@code slf4j.version}) to the artifacts they control. At + * dependency resolution time, checks whether the user has overridden + * any of these properties via {@code ext['property.name']} in + * {@code build.gradle} or via {@code gradle.properties}, and applies + * those overrides using Gradle's {@code ResolutionStrategy.eachDependency()}.</p> + * + * <p>Gradle's native {@code platform()} mechanism handles the base + * BOM import and default version management. This class only adds the + * one feature Gradle lacks: property-based version customization + * (see <a href="https://github.com/gradle/gradle/issues/9160">Gradle #9160</a>).</p> + * + * <p>This is the underlying utility used by the + * {@code org.apache.grails.gradle.bom-property-overrides} plugin. It is + * BOM-agnostic and can be used directly with any BOM that follows the + * Maven {@code <properties>} convention for managed versions.</p> + * + * @since 8.0 + */ +@CompileStatic +class BomManagedVersions { + + private static final Logger LOG = Logging.getLogger(BomManagedVersions) + private static final int MAX_PROPERTY_INTERPOLATION_DEPTH = 10 + + private final Map<String, String> versionOverrides = new LinkedHashMap<>() + + /** + * Resolves a BOM, parses its POM chain, and determines which managed + * dependency versions need to be overridden based on project properties. + * + * @param project the Gradle project (used for artifact resolution and property lookup) + * @param bomCoordinates the BOM coordinates in {@code group:artifact:version} format + * @return a BomManagedVersions instance containing any version overrides to apply + */ + static BomManagedVersions resolve(Project project, String bomCoordinates) { + return resolve(project, [bomCoordinates]) + } + + /** + * Resolves multiple BOMs, parses their POM chains, and determines which + * managed dependency versions need to be overridden based on project + * properties. Useful when a project applies several platforms (e.g., a + * Grails BOM plus a Micronaut BOM) and any of them may declare overridable + * properties. + * + * @param project the Gradle project (used for artifact resolution and property lookup) + * @param bomCoordinatesList list of BOM coordinates in {@code group:artifact:version} format + * @return a BomManagedVersions instance containing any version overrides to apply + */ + static BomManagedVersions resolve(Project project, Collection<String> bomCoordinatesList) { + BomManagedVersions instance = new BomManagedVersions() + + Map<String, String> bomProperties = new LinkedHashMap<>() + Map<String, List<String>> propertyToArtifacts = new LinkedHashMap<>() + Set<String> processed = new HashSet<>() + + for (String bomCoordinates : bomCoordinatesList) { + String[] parts = bomCoordinates?.split(':') + if (parts == null || parts.length != 3) { + LOG.warn('Invalid BOM coordinates: {}', bomCoordinates) + continue + } + processBom(project, parts[0], parts[1], parts[2], bomProperties, propertyToArtifacts, processed) + } + + for (Map.Entry<String, List<String>> entry : propertyToArtifacts.entrySet()) { + String propertyName = entry.key + if (project.hasProperty(propertyName)) { + String overrideVersion = project.property(propertyName).toString() + String defaultVersion = bomProperties.get(propertyName) + + if (overrideVersion != defaultVersion) { + for (String artifactKey : entry.value) { + instance.versionOverrides.put(artifactKey, overrideVersion) + } + LOG.lifecycle( + 'BOM version override: {} = {} (BOM default: {})', + propertyName, overrideVersion, defaultVersion ?: 'unknown' + ) + } + } + } + + if (!instance.versionOverrides.isEmpty()) { + LOG.info('BOM property overrides: {} version override(s) will be applied', instance.versionOverrides.size()) + } + + return instance + } + + /** + * Applies version overrides to a Gradle configuration's resolution strategy. + * + * @param configuration the configuration to apply overrides to + */ + void applyTo(Configuration configuration) { + if (versionOverrides.isEmpty()) { + return + } + + Map<String, String> overrides = this.versionOverrides + configuration.resolutionStrategy.eachDependency { DependencyResolveDetails details -> + String key = "${details.requested.group}:${details.requested.name}" as String + String override = overrides.get(key) + if (override != null) { + details.useVersion(override) + details.because('BOM version override via project property') + } + } + } + + /** + * Returns whether any version overrides were detected. + */ + boolean hasOverrides() { + return !versionOverrides.isEmpty() + } + + /** + * Returns an unmodifiable view of the version overrides. + * Keys are {@code group:artifact}, values are the override version strings. + */ + Map<String, String> getOverrides() { + return Collections.unmodifiableMap(versionOverrides) + } + + /** + * Parses a BOM POM file and extracts the property-to-artifact mapping. + * This method does not follow imported BOMs recursively - it only processes + * the given file. Intended for testing and direct POM inspection. + * + * @param pomFile the BOM POM file to parse + * @param bomProperties output map to receive property name to default value mappings + * @param propertyToArtifacts output map to receive property name to artifact coordinate mappings + */ + static void parseBomFile(File pomFile, Map<String, String> bomProperties, Map<String, List<String>> propertyToArtifacts) { + Document doc = parseXml(pomFile) + if (doc == null) { + return + } + extractProperties(doc, bomProperties) + + NodeList depMgmtNodes = doc.getElementsByTagName('dependencyManagement') + if (depMgmtNodes.length == 0) { + return + } + Element depMgmt = (Element) depMgmtNodes.item(0) + NodeList dependenciesNodes = depMgmt.getElementsByTagName('dependencies') + if (dependenciesNodes.length == 0) { + return + } + Element dependenciesElement = (Element) dependenciesNodes.item(0) + NodeList depNodes = dependenciesElement.getElementsByTagName('dependency') + + for (int i = 0; i < depNodes.length; i++) { + Element dep = (Element) depNodes.item(i) + String depGroupId = getChildText(dep, 'groupId') + String depArtifactId = getChildText(dep, 'artifactId') + String depVersion = getChildText(dep, 'version') + + if (!depGroupId || !depArtifactId || !depVersion) { + continue + } + + if (depVersion.contains('${')) { + String propertyName = extractPropertyName(depVersion) + if (propertyName) { + String artifactKey = "${depGroupId}:${depArtifactId}" as String + propertyToArtifacts.computeIfAbsent(propertyName) { new ArrayList<String>() }.add(artifactKey) + } + } + } + } + + private static void processBom( + Project project, String group, String artifact, String version, + Map<String, String> bomProperties, + Map<String, List<String>> propertyToArtifacts, + Set<String> processed + ) { + String bomKey = "${group}:${artifact}:${version}" as String + if (!processed.add(bomKey)) { + return + } + + File pomFile = resolvePomFile(project, group, artifact, version) + if (pomFile == null) { + return + } + + Document doc = parseXml(pomFile) + if (doc == null) { + return + } + + extractProperties(doc, bomProperties) + processManagedDependencies(doc, project, bomProperties, propertyToArtifacts, processed) + } + + private static File resolvePomFile(Project project, String group, String artifact, String version) { + try { + Configuration detached = project.configurations.detachedConfiguration( + project.dependencies.create("${group}:${artifact}:${version}@pom" as String) + ) + detached.transitive = false + return detached.singleFile + } + catch (Exception e) { + LOG.info('Could not resolve BOM POM: {}:{}:{} - {}', group, artifact, version, e.message) + return null + } + } + + private static Document parseXml(File pomFile) { + try { Review Comment: I considered this and went the JDK-XML route deliberately - the rationale (and the trade-offs) are worth being explicit about, and I'd rather discuss it than silently switch. **Why not Maven libraries:** 1. **Zero new runtime dependencies on the Gradle plugin classpath.** This plugin is meant to be applied to user builds, including ones that aren't Grails. Adding `org.apache.maven:maven-model` (or `maven-model-builder` if you want the inheritance/profile machinery) pulls in Plexus, SisuGuice, Aether/Resolver, and a handful of transitive deps that *also* happen to live in user buildscripts (where they'll show up in `buildscript`-vs-build classpath conflicts pretty fast). For a 350-line utility whose entire job is read 3 sections out of a POM, that footprint isn't worth it. 2. **Maven Resolver in particular brings real complexity.** `maven-model-builder` does property interpolation, profile activation, parent POM resolution against repository sessions etc - all of which we'd have to wire up against a Gradle `Configuration` because Maven's repository session model is not Gradle's. The simpler thing is to do the one specific thing Gradle's own `platform()` *almost* does (read `<properties>` + `<dependencyManagement>` + follow `<scope>import</scope>`) and stop there. 3. **What we actually need is *less* than `maven-model`.** We don't need profile activation, encrypted password handling, mirror resolution, or repository policies - all of which are unwanted side effects when you're using `maven-model-builder` to look at a single POM. The `parseBomFile`/`processBom`/`processManagedDependencies` triple in `BomManagedVersions` is intentionally narrower: read `<properties>`, read `<dependencyManagement>`, recurse on `<scope>import</scope>`, stop. That fits in 350 lines and is straightforward to test. 4. **Gradle resolves the POM file itself.** `resolvePomFile()` uses `project.configurations.detachedConfiguration(... '@pom' ...)` so the actual fetching, caching, repository lookup, and authentication is delegated to Gradle's resolver - *not* re-implemented. We only parse the bytes Gradle hands us. That's the part that benefits from the `maven-resolver` ecosystem, and we're already using Gradle's equivalent. The one place where this matters in practice is interpolation depth and parent POM imports - both of which are exercised by the `BomPlatformFunctionalSpec` end-to-end test (grails-bom imports spring-boot-dependencies; an `slf4j.version` override declared on the consumer flows all the way through to `org.slf4j:slf4j-api`). That said - if there's a specific scenario you're worried about that the JDK-XML route doesn't cover (e.g. classifier handling, dependency exclusions inside `<dependencyManagement>`, version ranges) please flag it and I'll either add a test case or pick up `maven-model` if it's strictly necessary. Leaving open for that discussion. ########## grails-gradle/bom-property-overrides/src/main/groovy/org/grails/gradle/plugin/bom/BomManagedVersions.groovy: ########## @@ -0,0 +1,378 @@ +/* + * 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 + * + * https://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. + */ +package org.grails.gradle.plugin.bom + +import groovy.transform.CompileStatic +import org.gradle.api.Project +import org.gradle.api.artifacts.Configuration +import org.gradle.api.artifacts.DependencyResolveDetails +import org.gradle.api.logging.Logger +import org.gradle.api.logging.Logging +import org.w3c.dom.Document +import org.w3c.dom.Element +import org.w3c.dom.NodeList + +import javax.xml.parsers.DocumentBuilderFactory + +/** + * Lightweight replacement for the Spring Dependency Management plugin's + * version property override feature. + * + * <p>Parses BOM POM files to build a mapping of Maven property names + * (e.g., {@code slf4j.version}) to the artifacts they control. At + * dependency resolution time, checks whether the user has overridden + * any of these properties via {@code ext['property.name']} in + * {@code build.gradle} or via {@code gradle.properties}, and applies + * those overrides using Gradle's {@code ResolutionStrategy.eachDependency()}.</p> + * + * <p>Gradle's native {@code platform()} mechanism handles the base + * BOM import and default version management. This class only adds the + * one feature Gradle lacks: property-based version customization + * (see <a href="https://github.com/gradle/gradle/issues/9160">Gradle #9160</a>).</p> + * + * <p>This is the underlying utility used by the + * {@code org.apache.grails.gradle.bom-property-overrides} plugin. It is + * BOM-agnostic and can be used directly with any BOM that follows the + * Maven {@code <properties>} convention for managed versions.</p> + * + * @since 8.0 + */ +@CompileStatic +class BomManagedVersions { + + private static final Logger LOG = Logging.getLogger(BomManagedVersions) + private static final int MAX_PROPERTY_INTERPOLATION_DEPTH = 10 + + private final Map<String, String> versionOverrides = new LinkedHashMap<>() + + /** + * Resolves a BOM, parses its POM chain, and determines which managed + * dependency versions need to be overridden based on project properties. + * + * @param project the Gradle project (used for artifact resolution and property lookup) + * @param bomCoordinates the BOM coordinates in {@code group:artifact:version} format + * @return a BomManagedVersions instance containing any version overrides to apply + */ + static BomManagedVersions resolve(Project project, String bomCoordinates) { + return resolve(project, [bomCoordinates]) + } + + /** + * Resolves multiple BOMs, parses their POM chains, and determines which + * managed dependency versions need to be overridden based on project + * properties. Useful when a project applies several platforms (e.g., a + * Grails BOM plus a Micronaut BOM) and any of them may declare overridable + * properties. + * + * @param project the Gradle project (used for artifact resolution and property lookup) + * @param bomCoordinatesList list of BOM coordinates in {@code group:artifact:version} format + * @return a BomManagedVersions instance containing any version overrides to apply + */ + static BomManagedVersions resolve(Project project, Collection<String> bomCoordinatesList) { + BomManagedVersions instance = new BomManagedVersions() + + Map<String, String> bomProperties = new LinkedHashMap<>() + Map<String, List<String>> propertyToArtifacts = new LinkedHashMap<>() + Set<String> processed = new HashSet<>() + + for (String bomCoordinates : bomCoordinatesList) { + String[] parts = bomCoordinates?.split(':') + if (parts == null || parts.length != 3) { + LOG.warn('Invalid BOM coordinates: {}', bomCoordinates) + continue + } + processBom(project, parts[0], parts[1], parts[2], bomProperties, propertyToArtifacts, processed) + } + + for (Map.Entry<String, List<String>> entry : propertyToArtifacts.entrySet()) { + String propertyName = entry.key + if (project.hasProperty(propertyName)) { + String overrideVersion = project.property(propertyName).toString() + String defaultVersion = bomProperties.get(propertyName) + + if (overrideVersion != defaultVersion) { + for (String artifactKey : entry.value) { + instance.versionOverrides.put(artifactKey, overrideVersion) + } + LOG.lifecycle( + 'BOM version override: {} = {} (BOM default: {})', + propertyName, overrideVersion, defaultVersion ?: 'unknown' + ) + } + } + } + + if (!instance.versionOverrides.isEmpty()) { + LOG.info('BOM property overrides: {} version override(s) will be applied', instance.versionOverrides.size()) + } + + return instance + } + + /** + * Applies version overrides to a Gradle configuration's resolution strategy. + * + * @param configuration the configuration to apply overrides to + */ + void applyTo(Configuration configuration) { + if (versionOverrides.isEmpty()) { + return + } + + Map<String, String> overrides = this.versionOverrides + configuration.resolutionStrategy.eachDependency { DependencyResolveDetails details -> + String key = "${details.requested.group}:${details.requested.name}" as String + String override = overrides.get(key) + if (override != null) { + details.useVersion(override) + details.because('BOM version override via project property') + } + } + } + + /** + * Returns whether any version overrides were detected. + */ + boolean hasOverrides() { + return !versionOverrides.isEmpty() + } + + /** + * Returns an unmodifiable view of the version overrides. + * Keys are {@code group:artifact}, values are the override version strings. + */ + Map<String, String> getOverrides() { + return Collections.unmodifiableMap(versionOverrides) + } + + /** + * Parses a BOM POM file and extracts the property-to-artifact mapping. Review Comment: We do recurse - the recursion just lives in `processManagedDependencies` rather than in `parseBomFile`. Specifically: ```groovy if ('import' == depScope) { String resolvedVersion = interpolateProperties(depVersion, bomProperties) if (resolvedVersion) { processBom(project, depGroupId, depArtifactId, resolvedVersion, bomProperties, propertyToArtifacts, processed) } continue } ``` That's the BOM-import handling: when a `<dependency>` inside `<dependencyManagement>` has `<scope>import</scope>` (which is how `grails-bom` pulls in `spring-boot-dependencies`, and how `spring-boot-dependencies` itself pulls in `spring-framework-bom`, `reactor-bom`, `netty-bom`, `slf4j-bom`, etc.), `processBom` recurses on the imported BOM with the *same* shared `bomProperties` and `propertyToArtifacts` accumulators, plus the `processed` set to short-circuit cycles. The doc you flagged on `parseBomFile` (line 165) is for the `static` testing helper that I added so the unit tests can exercise property/artifact extraction without spinning up a `Project`. That helper deliberately doesn't recurse - it's just "give me a single POM, give me the property→artifact map for that single file." The doc says so. The production path that the plugin actually uses is `resolve(Project, ...) → processBom → processManagedDependencies → processBom (recursive)`. The `BomPlatformFunctionalSpec` end-to-end test verifies a transitive override flows through: setting `slf4j.version` overrides `org.slf4j:slf4j-api` even though `slf4j.version` is declared on `spring-boot-dependencies` (imported by grails-bom), not on `grails-bom` directly. So the recursion is exercised, not just present in code. Leaving open in case I'm misreading what you wanted - if there's a specific BOM whose properties don't get picked up, please point me at it. ########## grails-gradle/bom-property-overrides/src/main/groovy/org/grails/gradle/plugin/bom/BomManagedVersions.groovy: ########## @@ -0,0 +1,378 @@ +/* + * 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 + * + * https://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. + */ +package org.grails.gradle.plugin.bom + +import groovy.transform.CompileStatic +import org.gradle.api.Project +import org.gradle.api.artifacts.Configuration +import org.gradle.api.artifacts.DependencyResolveDetails +import org.gradle.api.logging.Logger +import org.gradle.api.logging.Logging +import org.w3c.dom.Document +import org.w3c.dom.Element +import org.w3c.dom.NodeList + +import javax.xml.parsers.DocumentBuilderFactory + +/** + * Lightweight replacement for the Spring Dependency Management plugin's + * version property override feature. + * + * <p>Parses BOM POM files to build a mapping of Maven property names + * (e.g., {@code slf4j.version}) to the artifacts they control. At + * dependency resolution time, checks whether the user has overridden + * any of these properties via {@code ext['property.name']} in + * {@code build.gradle} or via {@code gradle.properties}, and applies + * those overrides using Gradle's {@code ResolutionStrategy.eachDependency()}.</p> + * + * <p>Gradle's native {@code platform()} mechanism handles the base + * BOM import and default version management. This class only adds the + * one feature Gradle lacks: property-based version customization + * (see <a href="https://github.com/gradle/gradle/issues/9160">Gradle #9160</a>).</p> + * + * <p>This is the underlying utility used by the + * {@code org.apache.grails.gradle.bom-property-overrides} plugin. It is + * BOM-agnostic and can be used directly with any BOM that follows the + * Maven {@code <properties>} convention for managed versions.</p> + * + * @since 8.0 + */ +@CompileStatic +class BomManagedVersions { + + private static final Logger LOG = Logging.getLogger(BomManagedVersions) + private static final int MAX_PROPERTY_INTERPOLATION_DEPTH = 10 + + private final Map<String, String> versionOverrides = new LinkedHashMap<>() + + /** + * Resolves a BOM, parses its POM chain, and determines which managed + * dependency versions need to be overridden based on project properties. + * + * @param project the Gradle project (used for artifact resolution and property lookup) + * @param bomCoordinates the BOM coordinates in {@code group:artifact:version} format + * @return a BomManagedVersions instance containing any version overrides to apply + */ + static BomManagedVersions resolve(Project project, String bomCoordinates) { + return resolve(project, [bomCoordinates]) + } + + /** + * Resolves multiple BOMs, parses their POM chains, and determines which + * managed dependency versions need to be overridden based on project + * properties. Useful when a project applies several platforms (e.g., a + * Grails BOM plus a Micronaut BOM) and any of them may declare overridable + * properties. + * + * @param project the Gradle project (used for artifact resolution and property lookup) + * @param bomCoordinatesList list of BOM coordinates in {@code group:artifact:version} format + * @return a BomManagedVersions instance containing any version overrides to apply + */ + static BomManagedVersions resolve(Project project, Collection<String> bomCoordinatesList) { + BomManagedVersions instance = new BomManagedVersions() + + Map<String, String> bomProperties = new LinkedHashMap<>() + Map<String, List<String>> propertyToArtifacts = new LinkedHashMap<>() + Set<String> processed = new HashSet<>() + + for (String bomCoordinates : bomCoordinatesList) { + String[] parts = bomCoordinates?.split(':') + if (parts == null || parts.length != 3) { + LOG.warn('Invalid BOM coordinates: {}', bomCoordinates) + continue + } + processBom(project, parts[0], parts[1], parts[2], bomProperties, propertyToArtifacts, processed) + } + + for (Map.Entry<String, List<String>> entry : propertyToArtifacts.entrySet()) { + String propertyName = entry.key + if (project.hasProperty(propertyName)) { + String overrideVersion = project.property(propertyName).toString() + String defaultVersion = bomProperties.get(propertyName) + + if (overrideVersion != defaultVersion) { + for (String artifactKey : entry.value) { + instance.versionOverrides.put(artifactKey, overrideVersion) + } + LOG.lifecycle( + 'BOM version override: {} = {} (BOM default: {})', + propertyName, overrideVersion, defaultVersion ?: 'unknown' + ) + } + } + } + + if (!instance.versionOverrides.isEmpty()) { + LOG.info('BOM property overrides: {} version override(s) will be applied', instance.versionOverrides.size()) + } + + return instance + } + + /** + * Applies version overrides to a Gradle configuration's resolution strategy. + * + * @param configuration the configuration to apply overrides to + */ + void applyTo(Configuration configuration) { + if (versionOverrides.isEmpty()) { + return + } + + Map<String, String> overrides = this.versionOverrides + configuration.resolutionStrategy.eachDependency { DependencyResolveDetails details -> + String key = "${details.requested.group}:${details.requested.name}" as String + String override = overrides.get(key) + if (override != null) { + details.useVersion(override) + details.because('BOM version override via project property') + } + } + } + + /** + * Returns whether any version overrides were detected. + */ + boolean hasOverrides() { + return !versionOverrides.isEmpty() + } + + /** + * Returns an unmodifiable view of the version overrides. + * Keys are {@code group:artifact}, values are the override version strings. + */ + Map<String, String> getOverrides() { + return Collections.unmodifiableMap(versionOverrides) + } + + /** + * Parses a BOM POM file and extracts the property-to-artifact mapping. + * This method does not follow imported BOMs recursively - it only processes + * the given file. Intended for testing and direct POM inspection. + * + * @param pomFile the BOM POM file to parse + * @param bomProperties output map to receive property name to default value mappings + * @param propertyToArtifacts output map to receive property name to artifact coordinate mappings + */ + static void parseBomFile(File pomFile, Map<String, String> bomProperties, Map<String, List<String>> propertyToArtifacts) { + Document doc = parseXml(pomFile) + if (doc == null) { + return + } + extractProperties(doc, bomProperties) + + NodeList depMgmtNodes = doc.getElementsByTagName('dependencyManagement') + if (depMgmtNodes.length == 0) { + return + } + Element depMgmt = (Element) depMgmtNodes.item(0) + NodeList dependenciesNodes = depMgmt.getElementsByTagName('dependencies') + if (dependenciesNodes.length == 0) { + return + } + Element dependenciesElement = (Element) dependenciesNodes.item(0) + NodeList depNodes = dependenciesElement.getElementsByTagName('dependency') + + for (int i = 0; i < depNodes.length; i++) { + Element dep = (Element) depNodes.item(i) + String depGroupId = getChildText(dep, 'groupId') + String depArtifactId = getChildText(dep, 'artifactId') + String depVersion = getChildText(dep, 'version') + + if (!depGroupId || !depArtifactId || !depVersion) { + continue + } + + if (depVersion.contains('${')) { + String propertyName = extractPropertyName(depVersion) + if (propertyName) { + String artifactKey = "${depGroupId}:${depArtifactId}" as String + propertyToArtifacts.computeIfAbsent(propertyName) { new ArrayList<String>() }.add(artifactKey) + } + } + } + } + + private static void processBom( + Project project, String group, String artifact, String version, + Map<String, String> bomProperties, + Map<String, List<String>> propertyToArtifacts, + Set<String> processed + ) { + String bomKey = "${group}:${artifact}:${version}" as String + if (!processed.add(bomKey)) { + return + } + + File pomFile = resolvePomFile(project, group, artifact, version) + if (pomFile == null) { + return + } + + Document doc = parseXml(pomFile) + if (doc == null) { + return + } + + extractProperties(doc, bomProperties) + processManagedDependencies(doc, project, bomProperties, propertyToArtifacts, processed) + } + + private static File resolvePomFile(Project project, String group, String artifact, String version) { + try { + Configuration detached = project.configurations.detachedConfiguration( + project.dependencies.create("${group}:${artifact}:${version}@pom" as String) + ) + detached.transitive = false + return detached.singleFile + } + catch (Exception e) { + LOG.info('Could not resolve BOM POM: {}:{}:{} - {}', group, artifact, version, e.message) + return null + } + } + + private static Document parseXml(File pomFile) { + try { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance() + factory.setNamespaceAware(false) + factory.setValidating(false) + factory.setXIncludeAware(false) + factory.setFeature('http://apache.org/xml/features/nonvalidating/load-external-dtd', false) + factory.setFeature('http://xml.org/sax/features/external-general-entities', false) + factory.setFeature('http://xml.org/sax/features/external-parameter-entities', false) + return factory.newDocumentBuilder().parse(pomFile) + } + catch (Exception e) { + LOG.warn('Failed to parse BOM POM: {} - {}', pomFile.name, e.message) + return null + } + } + + private static void extractProperties(Document doc, Map<String, String> bomProperties) { + NodeList propertiesNodes = doc.getElementsByTagName('properties') + if (propertiesNodes.length == 0) { + return + } + + Element propertiesElement = (Element) propertiesNodes.item(0) + NodeList children = propertiesElement.childNodes + for (int i = 0; i < children.length; i++) { + if (children.item(i) instanceof Element) { + Element prop = (Element) children.item(i) + String name = prop.tagName + String value = prop.textContent?.trim() + if (name && value) { + bomProperties.put(name, value) + } + } + } + } + + private static void processManagedDependencies( + Document doc, Project project, + Map<String, String> bomProperties, + Map<String, List<String>> propertyToArtifacts, + Set<String> processed + ) { + NodeList depMgmtNodes = doc.getElementsByTagName('dependencyManagement') + if (depMgmtNodes.length == 0) { + return + } + + Element depMgmt = (Element) depMgmtNodes.item(0) + NodeList dependenciesNodes = depMgmt.getElementsByTagName('dependencies') + if (dependenciesNodes.length == 0) { + return + } + + Element dependenciesElement = (Element) dependenciesNodes.item(0) + NodeList depNodes = dependenciesElement.getElementsByTagName('dependency') + + for (int i = 0; i < depNodes.length; i++) { + Element dep = (Element) depNodes.item(i) + String depGroupId = getChildText(dep, 'groupId') + String depArtifactId = getChildText(dep, 'artifactId') + String depVersion = getChildText(dep, 'version') + String depScope = getChildText(dep, 'scope') + + if (!depGroupId || !depArtifactId) { + continue + } + + if ('import' == depScope) { + String resolvedVersion = interpolateProperties(depVersion, bomProperties) + if (resolvedVersion) { + processBom(project, depGroupId, depArtifactId, resolvedVersion, + bomProperties, propertyToArtifacts, processed) + } + continue + } + + if (depVersion && depVersion.contains('${')) { + String propertyName = extractPropertyName(depVersion) + if (propertyName) { + String artifactKey = "${depGroupId}:${depArtifactId}" as String + propertyToArtifacts.computeIfAbsent(propertyName) { new ArrayList<String>() }.add(artifactKey) + } + } + } + } + + private static String extractPropertyName(String versionStr) { + if (versionStr == null) { + return null + } + int start = versionStr.indexOf('${') + int end = versionStr.indexOf('}', start) + if (start >= 0 && end > start) { + return versionStr.substring(start + 2, end) + } + return null + } + + private static String interpolateProperties(String value, Map<String, String> properties) { + if (value == null || !value.contains('${')) { Review Comment: This is exactly why `bomProperties` is *one* shared `Map<String, String>` accumulated across the entire recursion chain rather than a per-BOM map. Walk back through `resolve()`: ```groovy Map<String, String> bomProperties = new LinkedHashMap<>() Map<String, List<String>> propertyToArtifacts = new LinkedHashMap<>() Set<String> processed = new HashSet<>() for (String bomCoordinates : bomCoordinatesList) { ... processBom(project, group, artifact, version, bomProperties, propertyToArtifacts, processed) } ``` Both maps are passed by reference all the way down: `processBom` → `extractProperties(doc, bomProperties)` → `processManagedDependencies(doc, project, bomProperties, propertyToArtifacts, processed)` → recursive `processBom` (when `<scope>import</scope>` is hit). Every `<properties>` block we encounter - from the leaf BOM, every imported parent BOM, every grandparent imported through that - gets merged into the same map. By the time `interpolateProperties` runs at line 351 (your comment line), `properties` is the union of every `<properties>` block in the entire BOM chain. Concrete worked example: `grails-bom` imports `spring-boot-dependencies`. `spring-boot-dependencies` declares `<slf4j.version>X</slf4j.version>` in *its* `<properties>` block, and uses it via `<dependency>...<version>${slf4j.version}</version>...</dependency>`. Both the property *and* the dependency live on the parent BOM, never on `grails-bom` itself. After the recursion in `processManagedDependencies` runs, `bomProperties` contains `slf4j.version → X` and `propertyToArtifacts` contains `slf4j.version → [org.slf4j:slf4j-api, org.slf4j:slf4j-simple, ...]` - all derived from the parent. Setting `slf4j.version=Y` on the *consumer* project then triggers an override against `org.slf4j:slf4j-api` and friends, which is exactly what `BomPlatformFunctionalSpec` exercises. Last-write-wins is the same precedence rule Spring DM (and Maven `<dependencyManagement>` itself, when reading parent POMs) used: a child BOM can shadow a parent's property by redeclaring it. If that's not the precedence we want we can flip the merge order, but the existing behaviour matches what users were already getting under Spring DM. Is there a specific BOM or property you saw failing that prompted this comment? Happy to chase a concrete repro - leaving open. ########## grails-gradle/bom-property-overrides/src/main/groovy/org/grails/gradle/plugin/bom/BomPropertyOverridesPlugin.groovy: ########## @@ -0,0 +1,167 @@ +/* + * 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 + * + * https://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. + */ +package org.grails.gradle.plugin.bom + +import groovy.transform.CompileStatic +import org.gradle.api.Plugin +import org.gradle.api.Project +import org.gradle.api.artifacts.Configuration +import org.gradle.api.artifacts.Dependency +import org.gradle.api.artifacts.ModuleDependency +import org.gradle.api.attributes.Category + +/** + * Standalone Gradle plugin that enables Maven-style property-based version + * overrides for {@code platform()} BOMs. + * + * <p>This is the BOM-agnostic, generically reusable extraction of the + * property-override mechanism that historically lived inside the Spring + * Dependency Management plugin. Apply it to any project that consumes a + * BOM published with version property references in its + * {@code <dependencyManagement>} block:</p> + * + * <pre> + * plugins { + * id 'org.apache.grails.gradle.bom-property-overrides' + * } + * + * dependencies { + * implementation platform('com.example:my-bom:1.0.0') + * } + * + * // gradle.properties or build.gradle + * ext['slf4j.version'] = '2.0.13' + * </pre> + * + * <h2>How it works</h2> + * <ol> + * <li>Auto-detects all {@code platform()} / {@code enforcedPlatform()} + * dependencies declared on the project's configurations (configurable + * via {@link BomPropertyOverridesExtension#autoDetect}).</li> + * <li>Resolves each BOM POM in a detached configuration, parses the + * {@code <properties>} block and the + * {@code <dependencyManagement>} entries, and recursively follows + * {@code <scope>import</scope>} BOMs.</li> + * <li>For every property the BOM declares, checks whether the project + * has a property with the same name (via {@code gradle.properties} + * or {@code ext['property.name']}). If so, applies the override at + * resolution time using + * {@link Configuration#getResolutionStrategy()}'s + * {@code eachDependency} hook.</li> + * </ol> + * + * <p>The plugin does <strong>not</strong> declare any platforms itself. + * Consumers (or other plugins like {@code grails-app}) remain responsible + * for declaring the {@code platform()} dependencies; this plugin only + * adds the property-override layer on top.</p> + * + * @since 8.0 + * @see BomManagedVersions + * @see BomPropertyOverridesExtension + */ +@CompileStatic +class BomPropertyOverridesPlugin implements Plugin<Project> { + + /** + * The plugin id, exposed as a constant for programmatic application + * (e.g. {@code project.plugins.apply(BomPropertyOverridesPlugin.PLUGIN_ID)}). + */ + static final String PLUGIN_ID = 'org.apache.grails.gradle.bom-property-overrides' + + @Override + void apply(Project project) { + BomPropertyOverridesExtension extension = project.extensions.create( + BomPropertyOverridesExtension.EXTENSION_NAME, + BomPropertyOverridesExtension, + project.objects + ) + + project.afterEvaluate { Review Comment: Yes - it's intentional, and removing the `afterEvaluate` would actually break `autoDetect = true` (the default). The reasoning: 1. **`detectDeclaredBoms(project)` walks `project.configurations.each { conf.dependencies }`** to find every declared `platform()` / `enforcedPlatform()`. Those dependencies are added by the user's `dependencies { ... }` block in their `build.gradle`, which is evaluated *after* the plugin's `apply` callback. If we read `conf.dependencies` synchronously at apply time, we'd see an empty list (or only the platforms that were added by *earlier* plugins that ran before us, e.g. `grails-app` injecting `platform(grails-bom)`) and miss everything the user declared themselves. 2. **`extension.boms.get()` requires the user's DSL block to have run** - `bomPropertyOverrides { bom 'g:a:v' }` is a regular extension method whose append happens during script evaluation, not at apply time. 3. **`BomManagedVersions.resolve(...)` triggers a detached-configuration resolution** for each BOM POM (`@pom` artifact) to get the file off the network/cache. Doing that synchronously inside `apply` would force resolution before the user has had a chance to declare repositories (`pluginManagement {}` and `dependencyResolutionManagement {}` are evaluated earlier than `repositories {}` in the script), which on a clean cache would fail. Given the mechanism is fundamentally "observe declared platforms after the user has declared them, then apply override hooks", `afterEvaluate` is the natural lifecycle hook. The alternative would be `project.configurations.configureEach { conf -> conf.incoming.beforeResolve { ... } }`, but that defers work into resolution time on every configuration which is much heavier than running once after evaluation. That said - if the concern is specifically about *configuration cache*, that's a real issue worth digging into; the plugin would need to capture project-property snapshots and BOM coordinates at configuration time and apply overrides via a build service. Happy to follow up on that as a separate hardening pass. Leaving open. ########## grails-gradle/plugins/src/main/groovy/org/grails/gradle/plugin/core/GrailsGradlePlugin.groovy: ########## @@ -360,19 +359,81 @@ ${importStatements} protected void applyDefaultPlugins(Project project) { applySpringBootPlugin(project) - project.afterEvaluate { - GrailsExtension ge = project.extensions.getByType(GrailsExtension) - if (ge.springDependencyManagement) { - Plugin dependencyManagementPlugin = project.plugins.findPlugin(DependencyManagementPlugin) - if (dependencyManagementPlugin == null) { - project.plugins.apply(DependencyManagementPlugin) - } - - DependencyManagementExtension dme = project.extensions.findByType(DependencyManagementExtension) + applyGrailsBom(project) + } - applyBomImport(dme, project) + /** + * Applies the Grails BOM as a Gradle platform and enables property-based + * version overrides via the standalone + * {@code org.apache.grails.gradle.bom-property-overrides} plugin. + * + * <p>This replaces the Spring Dependency Management plugin with two + * orthogonal pieces:</p> + * <ol> + * <li><strong>BOM import</strong>: {@code grails-bom} is added as a + * Gradle {@code platform()} dependency on every declarable + * configuration, mirroring the global behaviour Spring DM provided + * via {@code configurations.all() + resolutionStrategy.eachDependency()}.</li> + * <li><strong>Property overrides</strong>: the BOM-agnostic + * {@link BomPropertyOverridesPlugin} reads the BOM's + * {@code <properties>} block and applies any project-level + * overrides via Gradle's + * {@code ResolutionStrategy.eachDependency()}.</li> + * </ol> + * + * <p>Usage: to override a version managed by the Grails or Spring Boot BOM, set the + * corresponding property in {@code gradle.properties} or {@code build.gradle}:</p> + * <pre> + * // gradle.properties + * slf4j.version=1.7.36 + * + * // or build.gradle + * ext['slf4j.version'] = '1.7.36' + * </pre> + * + * @see BomPropertyOverridesPlugin + * @since 8.0 + */ + protected void applyGrailsBom(Project project) { + String grailsVersion = (project.findProperty('grailsVersion') ?: BuildSettings.grailsVersion) as String + String bomCoordinates = "org.apache.grails:grails-bom:${grailsVersion}" as String + + // Ensure the developmentOnly configuration exists. Spring Boot's plugin + // normally creates this, but using maybeCreate guarantees it is available + // even if plugin ordering changes or Spring Boot is not applied. Review Comment: We do still apply the Spring Boot plugin (and depend on it - `BootArchive`/`BootRun`/`SpringBootExtension` are all wired up later in this class). The ordering is also already correct synchronously: ```groovy protected void applyDefaultPlugins(Project project) { applySpringBootPlugin(project) applyGrailsBom(project) } ``` `applySpringBootPlugin` synchronously calls `project.plugins.apply(SpringBootPlugin)` (when not already applied), so by the time `applyGrailsBom` runs Spring Boot's plugin has already configured `developmentOnly` etc. The `maybeCreate('developmentOnly')` you flagged is a defensive guard - if a downstream plugin (e.g. the `grails-plugin` Gradle plugin which doesn't apply Spring Boot but reuses some of this code path) calls `applyGrailsBom` directly, we don't want it to NPE on a missing configuration. Reads as "either Spring Boot already created this, or we'll create a stub for non-boot consumers". If the suggestion is specifically to use `project.pluginManager.withPlugin('org.springframework.boot') { ... }` *inside* `applyGrailsBom` - i.e., run the BOM injection only after Spring Boot has applied - that would actually be a regression for `grails-plugin` projects (they apply this code without Spring Boot and still need the `grails-bom` platform). The current guarantee is the stronger one: BOM injection happens regardless of whether Spring Boot is in play. Let me know if I'm misreading the concern - happy to switch to `withPlugin` if you'd like the BOM injection to be conditional on Spring Boot being present, but I don't think we want that semantically. Leaving open. ########## grails-gradle/plugins/src/main/groovy/org/grails/gradle/plugin/core/GrailsGradlePlugin.groovy: ########## @@ -360,19 +359,81 @@ ${importStatements} protected void applyDefaultPlugins(Project project) { applySpringBootPlugin(project) - project.afterEvaluate { - GrailsExtension ge = project.extensions.getByType(GrailsExtension) - if (ge.springDependencyManagement) { - Plugin dependencyManagementPlugin = project.plugins.findPlugin(DependencyManagementPlugin) - if (dependencyManagementPlugin == null) { - project.plugins.apply(DependencyManagementPlugin) - } - - DependencyManagementExtension dme = project.extensions.findByType(DependencyManagementExtension) + applyGrailsBom(project) + } - applyBomImport(dme, project) + /** + * Applies the Grails BOM as a Gradle platform and enables property-based + * version overrides via the standalone + * {@code org.apache.grails.gradle.bom-property-overrides} plugin. + * + * <p>This replaces the Spring Dependency Management plugin with two + * orthogonal pieces:</p> + * <ol> + * <li><strong>BOM import</strong>: {@code grails-bom} is added as a + * Gradle {@code platform()} dependency on every declarable + * configuration, mirroring the global behaviour Spring DM provided + * via {@code configurations.all() + resolutionStrategy.eachDependency()}.</li> + * <li><strong>Property overrides</strong>: the BOM-agnostic + * {@link BomPropertyOverridesPlugin} reads the BOM's + * {@code <properties>} block and applies any project-level + * overrides via Gradle's + * {@code ResolutionStrategy.eachDependency()}.</li> + * </ol> + * + * <p>Usage: to override a version managed by the Grails or Spring Boot BOM, set the + * corresponding property in {@code gradle.properties} or {@code build.gradle}:</p> + * <pre> + * // gradle.properties + * slf4j.version=1.7.36 + * + * // or build.gradle + * ext['slf4j.version'] = '1.7.36' + * </pre> + * + * @see BomPropertyOverridesPlugin + * @since 8.0 + */ + protected void applyGrailsBom(Project project) { + String grailsVersion = (project.findProperty('grailsVersion') ?: BuildSettings.grailsVersion) as String + String bomCoordinates = "org.apache.grails:grails-bom:${grailsVersion}" as String + + // Ensure the developmentOnly configuration exists. Spring Boot's plugin + // normally creates this, but using maybeCreate guarantees it is available + // even if plugin ordering changes or Spring Boot is not applied. + project.configurations.maybeCreate('developmentOnly') + + // Apply the BOM platform to all declarable project configurations, matching + // the behavior of the Spring Dependency Management plugin which applied version + // constraints globally via configurations.all() + resolutionStrategy.eachDependency(). + // Non-declarable configurations (e.g. apiElements, runtimeElements) inherit + // constraints through their parent configurations. Tool/annotation-processor + // configurations are excluded because they hold independent classpaths that + // already use their own platforms (e.g. Micronaut's annotation processors + // import io.micronaut.platform:micronaut-platform). Adding grails-bom as a + // second non-enforced platform on those configurations causes version conflict + // resolution to upgrade transitives and break the tools/processors - unlike + // resolutionStrategy hooks, platform() constraints participate in version + // conflict resolution. + project.configurations.configureEach { Configuration conf -> Review Comment: Reasonable feature request - we already have the `GrailsExtension.springDependencyManagement` flag (currently deprecated, no-op) which we could repurpose into something like `grails { useGrailsBomPlatform = true }` defaulting to opt-in for backwards compatibility. Two design questions before I code it though, because the answer changes how it gets wired: 1. **What's the *opt-out* escape hatch supposed to look like?** Disabling the platform injection entirely (so `grails-app` projects get *no* BOM and have to declare it themselves), or only disabling the auto-application to *all* declarable configurations and letting the user declare it on the configurations they want? 2. **Should the same flag govern the `bom-property-overrides` plugin application** or should that be a second knob? They're orthogonal mechanisms today (the standalone plugin works without the `applyGrailsBom` injection if a user declares `platform()` themselves). My preference would be: - **`grails { autoApplyBom = true }`** controls *both* the platform injection and the property-override plugin application (single knob, default on, easy to flip globally for projects that want to take ownership of their BOM) - **`grails { autoApplyBomToConfigurations = ['implementation', ...] }`** for fine-grained control (with a sensible default that matches today's `canBeDeclared && !isExcludedFromBomPlatform`) I'd rather pull this into a follow-up PR than add it inside #15467 (which is already large) - if you're OK with that, I'll file an issue tracking it and link it here. Leaving open. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
