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

gnodet pushed a commit to branch maven-4.0.x
in repository https://gitbox.apache.org/repos/asf/maven.git


The following commit(s) were added to refs/heads/maven-4.0.x by this push:
     new 56802315af [Backport maven-4.0.x] #14032: Merge combine.id and 
combine.keys matches in place (#14060)
56802315af is described below

commit 56802315afc27ffe245830551e42e1695fe21a81
Author: Guillaume Nodet <[email protected]>
AuthorDate: Wed Nov 18 09:57:01 2026 +0100

    [Backport maven-4.0.x] #14032: Merge combine.id and combine.keys matches in 
place (#14060)
    
    * [Backport maven-4.0.x] #14032: Merge combine.id and combine.keys matches 
in place
    
    Backport of #14032 to `maven-4.0.x`.
    
    When a recessive child matches a dominant child through combine.id or 
combine.keys,
    DefaultXmlService.doMerge merges it into the next dominant sibling with the 
same
    element name rather than into the matching one, so inherited configuration 
lands in
    the wrong element. This fix computes the id/keys matches upfront and merges 
each
    recessive child into its matching dominant child directly.
    
    Cherry-picked from aabb958b67e0d50b6248770a5b045723e69cdf4f
    
    * fix: apply spotless formatting to DefaultXmlService.java
    
    ---------
    
    Co-authored-by: Sharang Gupta <[email protected]>
---
 .../maven/internal/xml/DefaultXmlService.java      | 140 +++++++++++++--------
 .../apache/maven/internal/xml/XmlNodeImplTest.java | 123 ++++++++++++++++++
 2 files changed, 212 insertions(+), 51 deletions(-)

diff --git 
a/impl/maven-xml/src/main/java/org/apache/maven/internal/xml/DefaultXmlService.java
 
b/impl/maven-xml/src/main/java/org/apache/maven/internal/xml/DefaultXmlService.java
index a05b66a2b0..21619a217d 100644
--- 
a/impl/maven-xml/src/main/java/org/apache/maven/internal/xml/DefaultXmlService.java
+++ 
b/impl/maven-xml/src/main/java/org/apache/maven/internal/xml/DefaultXmlService.java
@@ -28,13 +28,14 @@
 import java.io.Reader;
 import java.io.Writer;
 import java.util.ArrayList;
+import java.util.Collections;
 import java.util.HashMap;
 import java.util.HashSet;
+import java.util.IdentityHashMap;
 import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
 import java.util.Objects;
-import java.util.Optional;
 import java.util.Set;
 import java.util.stream.Collectors;
 import java.util.stream.Stream;
@@ -287,8 +288,10 @@ private static void writeAttributes(
      *     </ol></li>
      *   <li> Iterate through the recessive children, and:
      *     <ol type="i">
-     *     <li> if mergeChildren == true and there is a corresponding dominant 
child (matched by element name),
-     *          merge the two.</li>
+     *     <li> if there is a dominant child with the same 'combine.id' 
attribute or, when the recessive node has a
+     *          'combine.keys' attribute, with the same values for the 
attributes it lists, merge the two.</li>
+     *     <li> otherwise, if mergeChildren == true and there is a 
corresponding dominant child (matched by element
+     *          name), merge the two.</li>
      *     <li> otherwise, add the recessive child as a new child on the 
dominant root node.</li>
      *     </ol></li>
      *   </ol></li>
@@ -340,6 +343,27 @@ public XmlNode doMerge(XmlNode dominant, XmlNode 
recessive, Boolean childMergeOv
                     }
                 }
 
+                String keysValue = 
recessive.attribute(KEYS_COMBINATION_MODE_ATTRIBUTE);
+                String[] keys = isEmpty(keysValue) ? null : 
keysValue.split(",");
+
+                // the dominant children matching a recessive child by 
combine.id or combine.keys
+                Map<XmlNode, XmlNode> matches = new IdentityHashMap<>();
+                for (XmlNode recessiveChild : recessive.children()) {
+                    String idValue = 
recessiveChild.attribute(ID_COMBINATION_MODE_ATTRIBUTE);
+                    XmlNode match = null;
+                    if (!isEmpty(idValue)) {
+                        match = findNodeById(dominant.children(), idValue);
+                    } else if (keys != null) {
+                        match = findNodeByKeys(dominant.children(), 
recessiveChild, keys);
+                    }
+                    if (match != null) {
+                        matches.put(recessiveChild, match);
+                    }
+                }
+                Set<XmlNode> matchedChildren = Collections.newSetFromMap(new 
IdentityHashMap<>());
+                matchedChildren.addAll(matches.values());
+
+                // the other dominant children are merged in order with the 
recessive children of the same name
                 Map<String, Iterator<XmlNode>> commonChildren = new 
HashMap<>();
                 Set<String> names =
                         
recessive.children().stream().map(XmlNode::name).collect(Collectors.toSet());
@@ -348,78 +372,83 @@ public XmlNode doMerge(XmlNode dominant, XmlNode 
recessive, Boolean childMergeOv
                             .filter(n -> n.name().equals(name))
                             .toList();
                     if (!dominantChildren.isEmpty()) {
-                        commonChildren.put(name, dominantChildren.iterator());
+                        commonChildren.put(
+                                name,
+                                dominantChildren.stream()
+                                        .filter(n -> 
!matchedChildren.contains(n))
+                                        .iterator());
                     }
                 }
 
-                String keysValue = 
recessive.attribute(KEYS_COMBINATION_MODE_ATTRIBUTE);
+                // the dominant children already merged with a recessive 
child, and the result of that merge
+                Map<XmlNode, XmlNode> mergedChildren = new IdentityHashMap<>();
 
                 int recessiveChildIndex = 0;
                 for (XmlNode recessiveChild : recessive.children()) {
                     String idValue = 
recessiveChild.attribute(ID_COMBINATION_MODE_ATTRIBUTE);
 
-                    XmlNode childDom = null;
-                    if (!isEmpty(idValue)) {
-                        for (XmlNode dominantChild : dominant.children()) {
-                            if 
(idValue.equals(dominantChild.attribute(ID_COMBINATION_MODE_ATTRIBUTE))) {
-                                childDom = dominantChild;
-                                // we have a match, so don't append but merge
-                                mergeChildren = true;
-                            }
-                        }
-                    } else if (!isEmpty(keysValue)) {
-                        String[] keys = keysValue.split(",");
-                        Map<String, Optional<String>> recessiveKeyValues = 
Stream.of(keys)
-                                .collect(Collectors.toMap(
-                                        k -> k, k -> 
Optional.ofNullable(recessiveChild.attribute(k))));
-
-                        for (XmlNode dominantChild : dominant.children()) {
-                            Map<String, Optional<String>> dominantKeyValues = 
Stream.of(keys)
-                                    .collect(Collectors.toMap(
-                                            k -> k, k -> 
Optional.ofNullable(dominantChild.attribute(k))));
-
-                            if (recessiveKeyValues.equals(dominantKeyValues)) {
-                                childDom = dominantChild;
-                                // we have a match, so don't append but merge
-                                mergeChildren = true;
-                            }
+                    XmlNode childDom;
+                    boolean matched = false;
+                    if (!isEmpty(idValue) || keys != null) {
+                        childDom = matches.get(recessiveChild);
+                        if (childDom != null) {
+                            matched = true;
+                            // we have a match, so don't append but merge
+                            mergeChildren = true;
                         }
                     } else {
                         childDom = dominant.child(recessiveChild.name());
                     }
 
                     if (mergeChildren && childDom != null) {
-                        String name = recessiveChild.name();
-                        Iterator<XmlNode> it =
-                                commonChildren.computeIfAbsent(name, n1 -> 
Stream.of(dominant.children().stream()
-                                                .filter(n2 -> 
n2.name().equals(n1))
-                                                .collect(Collectors.toList()))
-                                        .filter(l -> !l.isEmpty())
-                                        .map(List::iterator)
-                                        .findFirst()
-                                        .orElse(null));
-                        if (it == null) {
-                            if (children == null) {
-                                children = new 
ArrayList<>(dominant.children());
+                        XmlNode dominantChild = null;
+                        if (matched) {
+                            // merge with the matching child, wherever it is 
among its siblings
+                            dominantChild = childDom;
+                        } else {
+                            String name = recessiveChild.name();
+                            Iterator<XmlNode> it =
+                                    commonChildren.computeIfAbsent(name, n1 -> 
Stream.of(dominant.children().stream()
+                                                    .filter(n2 -> 
n2.name().equals(n1))
+                                                    
.collect(Collectors.toList()))
+                                            .filter(l -> !l.isEmpty())
+                                            .findFirst()
+                                            .map(List::iterator)
+                                            .orElse(null));
+                            if (it == null) {
+                                if (children == null) {
+                                    children = new 
ArrayList<>(dominant.children());
+                                }
+                                children.add(recessiveChild);
+                            } else if (it.hasNext()) {
+                                dominantChild = it.next();
                             }
-                            children.add(recessiveChild);
-                        } else if (it.hasNext()) {
-                            XmlNode dominantChild = it.next();
+                        }
+                        if (dominantChild != null) {
+                            // several recessive children can match the same 
dominant child
+                            XmlNode current = 
mergedChildren.getOrDefault(dominantChild, dominantChild);
 
-                            String dominantChildCombinationMode = 
getSelfCombinationMode(dominantChild);
+                            String dominantChildCombinationMode = 
getSelfCombinationMode(current);
                             if 
(SELF_COMBINATION_REMOVE.equals(dominantChildCombinationMode)) {
                                 if (children == null) {
                                     children = new 
ArrayList<>(dominant.children());
                                 }
-                                children.remove(dominantChild);
+                                int idx = indexOfSame(children, current);
+                                if (idx >= 0) {
+                                    children.remove(idx);
+                                }
                             } else {
-                                int idx = 
dominant.children().indexOf(dominantChild);
-                                XmlNode merged = merge(dominantChild, 
recessiveChild, childMergeOverride);
-                                if (merged != dominantChild) {
+                                XmlNode merged = merge(current, 
recessiveChild, childMergeOverride);
+                                if (merged != current) {
                                     if (children == null) {
                                         children = new 
ArrayList<>(dominant.children());
                                     }
-                                    children.set(idx, merged);
+                                    // recessive children may have been added 
before the dominant child
+                                    int mergeIdx = indexOfSame(children, 
current);
+                                    if (mergeIdx >= 0) {
+                                        children.set(mergeIdx, merged);
+                                        mergedChildren.put(dominantChild, 
merged);
+                                    }
                                 }
                             }
                         }
@@ -464,6 +493,15 @@ private static boolean isEmpty(String str) {
         return str == null || str.isEmpty();
     }
 
+    private static int indexOfSame(List<XmlNode> nodes, XmlNode node) {
+        for (int i = 0; i < nodes.size(); i++) {
+            if (nodes.get(i) == node) {
+                return i;
+            }
+        }
+        return -1;
+    }
+
     private static String getSelfCombinationMode(XmlNode node) {
         String value = node.attribute(SELF_COMBINATION_MODE_ATTRIBUTE);
         return !isEmpty(value) ? value : DEFAULT_SELF_COMBINATION_MODE;
diff --git 
a/impl/maven-xml/src/test/java/org/apache/maven/internal/xml/XmlNodeImplTest.java
 
b/impl/maven-xml/src/test/java/org/apache/maven/internal/xml/XmlNodeImplTest.java
index 87285da367..2e03918b52 100644
--- 
a/impl/maven-xml/src/test/java/org/apache/maven/internal/xml/XmlNodeImplTest.java
+++ 
b/impl/maven-xml/src/test/java/org/apache/maven/internal/xml/XmlNodeImplTest.java
@@ -283,6 +283,129 @@ void testCombineKeys() throws Exception {
         assertEquals("right", p2.child("value").inputLocation());
     }
 
+    @Test
+    void testCombineIdMergesMatchingElement() throws Exception {
+        String lhs = "<props>" + "<property 
combine.id='A'><name>A</name></property>"
+                + "<property combine.id='B'><name>B</name></property>" + 
"</props>";
+
+        String rhs = "<props>" + "<property 
combine.id='B'><value>RHS</value></property>" + "</props>";
+
+        assertRecessiveValueIsMergedIntoSecondProperty(lhs, rhs);
+    }
+
+    @Test
+    void testCombineKeysMergesMatchingElement() throws Exception {
+        String lhs = "<props combine.keys='key'>" + "<property 
key='A'><name>A</name></property>"
+                + "<property key='B'><name>B</name></property>" + "</props>";
+
+        String rhs = "<props combine.keys='key'>" + "<property 
key='B'><value>RHS</value></property>" + "</props>";
+
+        assertRecessiveValueIsMergedIntoSecondProperty(lhs, rhs);
+    }
+
+    @Test
+    void testCombineIdMergesMatchingElementAfterAppendedSibling() throws 
Exception {
+        String lhs =
+                "<props combine.children='append'>" + "<property 
combine.id='A'><name>A</name></property>" + "</props>";
+
+        String rhs = "<props>" + "<property 
combine.id='X'><name>X</name></property>"
+                + "<property combine.id='A'><value>RHS</value></property>" + 
"</props>";
+
+        XmlNode leftDom = XmlService.read(new StringReader(lhs), new 
FixedInputLocationBuilder("left"));
+        XmlNode rightDom = XmlService.read(new StringReader(rhs), new 
FixedInputLocationBuilder("right"));
+
+        XmlNode mergeResult = XmlService.merge(leftDom, rightDom);
+        assertEquals(2, getChildren(mergeResult, "property").size());
+
+        XmlNode p0 = getNthChild(mergeResult, "property", 0);
+        assertEquals("X", p0.child("name").value());
+        assertEquals("right", p0.child("name").inputLocation());
+
+        XmlNode p1 = getNthChild(mergeResult, "property", 1);
+        assertEquals("A", p1.child("name").value());
+        assertEquals("RHS", p1.child("value").value());
+    }
+
+    @Test
+    void testCombineIdLeavesOtherElementsMergedInOrder() throws Exception {
+        String lhs = "<props>" + "<property 
combine.id='A'><name>A</name></property>"
+                + "<property><name>B</name></property>" + "</props>";
+
+        String rhs = "<props>" + "<property 
combine.id='A'><other>RHS-A</other></property>"
+                + "<property><value>RHS</value></property>" + "</props>";
+
+        XmlNode leftDom = XmlService.read(new StringReader(lhs), new 
FixedInputLocationBuilder("left"));
+        XmlNode rightDom = XmlService.read(new StringReader(rhs), new 
FixedInputLocationBuilder("right"));
+
+        XmlNode mergeResult = XmlService.merge(leftDom, rightDom, true);
+        assertEquals(2, getChildren(mergeResult, "property").size());
+
+        XmlNode p0 = getNthChild(mergeResult, "property", 0);
+        assertEquals("A", p0.child("name").value());
+        assertEquals("RHS-A", p0.child("other").value());
+        assertNull(p0.child("value"));
+
+        XmlNode p1 = getNthChild(mergeResult, "property", 1);
+        assertEquals("B", p1.child("name").value());
+        assertEquals("RHS", p1.child("value").value());
+    }
+
+    @Test
+    void testCombineIdMergesEveryElementWithTheSameId() throws Exception {
+        String lhs = "<props>" + "<property 
combine.id='A'><name>A</name></property>" + "</props>";
+
+        String rhs = "<props>" + "<property 
combine.id='A'><value>RHS</value></property>"
+                + "<property combine.id='A'><other>RHS</other></property>" + 
"</props>";
+
+        XmlNode leftDom = XmlService.read(new StringReader(lhs), new 
FixedInputLocationBuilder("left"));
+        XmlNode rightDom = XmlService.read(new StringReader(rhs), new 
FixedInputLocationBuilder("right"));
+
+        XmlNode mergeResult = XmlService.merge(leftDom, rightDom, true);
+        assertEquals(1, getChildren(mergeResult, "property").size());
+
+        XmlNode p0 = getNthChild(mergeResult, "property", 0);
+        assertEquals("A", p0.child("name").value());
+        assertEquals("RHS", p0.child("value").value());
+        assertEquals("RHS", p0.child("other").value());
+    }
+
+    @Test
+    void testCombineIdAppendsWhenNoDominantMatchExists() throws Exception {
+        String lhs = "<props>" + "<property 
combine.id='A'><name>A</name></property>" + "</props>";
+
+        String rhs = "<props>" + "<property 
combine.id='NEW'><name>NEW</name></property>" + "</props>";
+
+        XmlNode leftDom = XmlService.read(new StringReader(lhs), new 
FixedInputLocationBuilder("left"));
+        XmlNode rightDom = XmlService.read(new StringReader(rhs), new 
FixedInputLocationBuilder("right"));
+
+        XmlNode mergeResult = XmlService.merge(leftDom, rightDom, true);
+        assertEquals(2, getChildren(mergeResult, "property").size());
+
+        XmlNode p0 = getNthChild(mergeResult, "property", 0);
+        assertEquals("A", p0.child("name").value());
+
+        XmlNode p1 = getNthChild(mergeResult, "property", 1);
+        assertEquals("NEW", p1.child("name").value());
+        assertEquals("right", p1.child("name").inputLocation());
+    }
+
+    private static void assertRecessiveValueIsMergedIntoSecondProperty(String 
lhs, String rhs) throws Exception {
+        XmlNode leftDom = XmlService.read(new StringReader(lhs), new 
FixedInputLocationBuilder("left"));
+        XmlNode rightDom = XmlService.read(new StringReader(rhs), new 
FixedInputLocationBuilder("right"));
+
+        XmlNode mergeResult = XmlService.merge(leftDom, rightDom, true);
+        assertEquals(2, getChildren(mergeResult, "property").size());
+
+        XmlNode p0 = getNthChild(mergeResult, "property", 0);
+        assertEquals("A", p0.child("name").value());
+        assertNull(p0.child("value"));
+
+        XmlNode p1 = getNthChild(mergeResult, "property", 1);
+        assertEquals("B", p1.child("name").value());
+        assertEquals("RHS", p1.child("value").value());
+        assertEquals("right", p1.child("value").inputLocation());
+    }
+
     @Test
     void testPreserveDominantBlankValue() throws XMLStreamException, 
IOException {
         String lhs = "<parameter xml:space=\"preserve\"> </parameter>";

Reply via email to