jamesfredley commented on code in PR #15467:
URL: https://github.com/apache/grails-core/pull/15467#discussion_r3344075277


##########
grails-gradle/plugins/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:
   For context on why `BomManagedVersions` parses POMs with the JDK's 
`DocumentBuilderFactory` rather than a Maven library: it was modeled on an 
existing precedent already shipping in this codebase. `grails-forge`'s 
`PomDependencyVersionResolver` 
(`org.grails.forge.build.dependencies.PomDependencyVersionResolver` in 
`grails-forge-core`) parses `pom.xml` the same way - 
`DocumentBuilderFactory.newInstance()` + `getElementsByTagName("dependency")` 
with manual child-node reads - to resolve dependency coordinates and versions. 
The `BomManagedVersions` parser followed that same approach for consistency 
with what was already here, and to keep the runtime Grails Gradle plugin 
classpath free of the `maven-model`/Plexus transitive stack (this plugin is 
applied to user builds, including non-Grails ones).
   
   Note this is the runtime plugin path, distinct from the docs-only 
`ExtractDependenciesTask`, which is now on `maven-model` (20f3304490) per the 
other thread. If we'd prefer to standardize `BomManagedVersions` on 
`maven-model` as well I'm happy to do that as a follow-up - just flagging that 
the current implementation matches the existing forge precedent rather than 
being a new pattern introduced by this PR.
   



-- 
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]

Reply via email to