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

slachiewicz pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/maven-assembly-plugin.git


The following commit(s) were added to refs/heads/master by this push:
     new a38dba40 Aggregate files in SimpleAggregatingDescriptorHandler and 
assert it in the ITs
a38dba40 is described below

commit a38dba40727520dddf26480ee2eab7b8a7ef386e
Author: Sylwester Lachiewicz <[email protected]>
AuthorDate: Thu Nov 26 04:10:18 2026 +0000

    Aggregate files in SimpleAggregatingDescriptorHandler and assert it in the 
ITs
    
    The finalizer wrote the aggregate before the archiver visited its 
resources, so it was empty. It now walks the resources itself, reads each 
source once, and resets its state after writing.
    Fixes #1420, fixes #1024.
---
 .../verify.groovy                                  |  55 +-----
 .../custom-handler-withFileEntries/verify.groovy   |   4 +-
 .../filter/SimpleAggregatingDescriptorHandler.java |  56 ++++--
 .../SimpleAggregatingDescriptorHandlerTest.java    | 201 +++++++++++++++++++++
 4 files changed, 251 insertions(+), 65 deletions(-)

diff --git 
a/src/it/projects/container-descriptors/custom-containerDescriptorHandler/verify.groovy
 
b/src/it/projects/container-descriptors/custom-containerDescriptorHandler/verify.groovy
index f8e96dac..0c1caf18 100644
--- 
a/src/it/projects/container-descriptors/custom-containerDescriptorHandler/verify.groovy
+++ 
b/src/it/projects/container-descriptors/custom-containerDescriptorHandler/verify.groovy
@@ -17,50 +17,11 @@
  * under the License.
  */
 
-boolean result = true
-
-try {
-    File a = new File(basedir, "assembly/target/assembly-1-bin/file.txt")
-    File b = new File(basedir, "assembly/target/assembly-1-bin/b/file.txt")
-
-    if(result && !a.exists()) {
-        System.out.println("File: " + a + " should have been generated, but 
was not.")
-        result = false
-    }
-
-    if(result) {
-        BufferedReader r = new BufferedReader(new FileReader(a))
-        String s = null
-
-        boolean foundA = false
-        boolean foundB = false
-        while((s = r.readLine()) != null) {
-            if (s.equals("file A")) {
-                foundA = true
-            }
-            else if (s.equals("file B")) {
-                foundB = true
-            }
-
-            if (foundA && foundB) {
-                result = true
-                break
-            }
-        }
-
-        if (!result) {
-            System.out.println("File: " + a + " should contain lines:\nfile 
A\nfile B\n\n ...but didn't.")
-        }
-    }
-
-    if(result && b.exists()) {
-        System.out.println("File: " + b + " should not exist, but does.")
-        result = false
-    }
-}
-catch(IOException e) {
-    e.printStackTrace()
-    result = false
-}
-
-return result
+File a = new File(basedir, "assembly/target/assembly-1-bin/file.txt")
+File b = new File(basedir, "assembly/target/assembly-1-bin/b/file.txt")
+
+assert a.exists() : "File: " + a + " should have been generated, but was not."
+List<String> lines = a.readLines('UTF-8')
+assert lines.contains("file A") && lines.contains("file B") : "File: " + a + " 
should contain lines:\nfile A\nfile B\n\n ...but contained:\n" + lines
+assert !b.exists() : "File: " + b + " should not exist, but does."
+return true
diff --git 
a/src/it/projects/container-descriptors/custom-handler-withFileEntries/verify.groovy
 
b/src/it/projects/container-descriptors/custom-handler-withFileEntries/verify.groovy
index 587f8f41..3764c7e7 100644
--- 
a/src/it/projects/container-descriptors/custom-handler-withFileEntries/verify.groovy
+++ 
b/src/it/projects/container-descriptors/custom-handler-withFileEntries/verify.groovy
@@ -17,13 +17,13 @@
  * under the License.
  */
 
-// The aggregated content of file.txt is not asserted: the aggregate is 
written before the fileSet entries are
-// added, see https://github.com/apache/maven-assembly-plugin/issues/1024
 // "bin" lists both files as <file> entries, "bin-mixed" lists one as <file> 
and the other as <fileSet>
 for (String assemblyId : ["bin", "bin-mixed"]) {
     File a = new File(basedir, "assembly/target/assembly-1-" + assemblyId + 
"/file.txt")
     File b = new File(basedir, "assembly/target/assembly-1-" + assemblyId + 
"/b/file.txt")
     assert a.exists() : "File: " + a + " should have been generated, but was 
not."
+    List<String> lines = a.readLines('UTF-8')
+    assert lines.count("file A") == 1 && lines.count("file B") == 1 : "File: " 
+ a + " should contain lines file A and file B once each, but contained:\n" + 
lines
     assert !b.exists() : "File: " + b + " should not exist, but does."
 }
 return true
diff --git 
a/src/main/java/org/apache/maven/plugins/assembly/filter/SimpleAggregatingDescriptorHandler.java
 
b/src/main/java/org/apache/maven/plugins/assembly/filter/SimpleAggregatingDescriptorHandler.java
index af30cf56..19fdbfc9 100644
--- 
a/src/main/java/org/apache/maven/plugins/assembly/filter/SimpleAggregatingDescriptorHandler.java
+++ 
b/src/main/java/org/apache/maven/plugins/assembly/filter/SimpleAggregatingDescriptorHandler.java
@@ -38,8 +38,10 @@ import org.apache.commons.io.IOUtils;
 import org.apache.maven.plugins.assembly.utils.AssemblyFileUtils;
 import org.codehaus.plexus.archiver.Archiver;
 import org.codehaus.plexus.archiver.ArchiverException;
+import org.codehaus.plexus.archiver.ResourceIterator;
 import org.codehaus.plexus.archiver.UnArchiver;
 import org.codehaus.plexus.components.io.fileselectors.FileInfo;
+import org.codehaus.plexus.components.io.resources.PlexusIoResource;
 
 /**
  * <code>file-aggregator</code>: Generic aggregating handler, configured with 
filePattern and outputPath.
@@ -51,7 +53,7 @@ public class SimpleAggregatingDescriptorHandler implements 
ContainerDescriptorHa
     @SuppressWarnings("FieldCanBeLocal")
     private final String commentChars = "#";
 
-    private final StringWriter aggregateWriter = new StringWriter();
+    private StringWriter aggregateWriter = new StringWriter();
 
     private final List<String> filenames = new ArrayList<>();
 
@@ -63,27 +65,44 @@ public class SimpleAggregatingDescriptorHandler implements 
ContainerDescriptorHa
 
     private boolean overrideFilterAction;
 
+    private boolean collecting;
+
     @Override
     public void finalizeArchiveCreation(final Archiver archiver) {
         checkConfig();
 
-        if (outputPath.endsWith("/")) {
-            throw new ArchiverException("Cannot write aggregated properties to 
a directory. "
-                    + "You must specify a file name in the outputPath 
configuration for this"
-                    + " handler. (handler: " + getClass().getName());
-        }
-
-        if (outputPath.startsWith("/")) {
-            outputPath = outputPath.substring(1);
-        }
+        try {
+            // Finalizers run before the archiver visits its resources, so 
iterate them here to make
+            // isSelected() collect the matching files before the aggregate is 
written.
+            collecting = true;
+            try {
+                for (final ResourceIterator it = archiver.getResources(); 
it.hasNext(); ) {
+                    it.next();
+                }
+            } finally {
+                collecting = false;
+            }
 
-        final File temp = writePropertiesFile();
+            if (outputPath.endsWith("/")) {
+                throw new ArchiverException("Cannot write aggregated 
properties to a directory. "
+                        + "You must specify a file name in the outputPath 
configuration for this"
+                        + " handler. (handler: " + getClass().getName());
+            }
 
-        overrideFilterAction = true;
+            if (outputPath.startsWith("/")) {
+                outputPath = outputPath.substring(1);
+            }
 
-        archiver.addFile(temp, outputPath);
+            final File temp = writePropertiesFile();
 
-        overrideFilterAction = false;
+            overrideFilterAction = true;
+            archiver.addFile(temp, outputPath);
+        } finally {
+            overrideFilterAction = false;
+            // this component is shared between assemblies and formats, so do 
not carry content over
+            filenames.clear();
+            aggregateWriter = new StringWriter();
+        }
     }
 
     private File writePropertiesFile() {
@@ -139,8 +158,13 @@ public class SimpleAggregatingDescriptorHandler implements 
ContainerDescriptorHa
         String name = AssemblyFileUtils.normalizeFileInfo(fileInfo);
 
         if (fileInfo.isFile() && name.matches(filePattern)) {
-            readProperties(fileInfo);
-            filenames.add(name);
+            // Files that reach the archiver are visited by several walks 
(other finalizers, execute()).
+            // Read them only during our own walk. Files filtered when they 
are added, which are plain
+            // FileInfo objects rather than archiver resources, are read at 
that time.
+            if (collecting || !(fileInfo instanceof PlexusIoResource)) {
+                readProperties(fileInfo);
+                filenames.add(name);
+            }
 
             return false;
         }
diff --git 
a/src/test/java/org/apache/maven/plugins/assembly/filter/SimpleAggregatingDescriptorHandlerTest.java
 
b/src/test/java/org/apache/maven/plugins/assembly/filter/SimpleAggregatingDescriptorHandlerTest.java
new file mode 100644
index 00000000..b49b2f99
--- /dev/null
+++ 
b/src/test/java/org/apache/maven/plugins/assembly/filter/SimpleAggregatingDescriptorHandlerTest.java
@@ -0,0 +1,201 @@
+/*
+ * 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.
+ */
+package org.apache.maven.plugins.assembly.filter;
+
+import java.io.ByteArrayInputStream;
+import java.io.File;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import org.codehaus.plexus.archiver.ArchiveEntry;
+import org.codehaus.plexus.archiver.ArchiverException;
+import org.codehaus.plexus.archiver.ResourceIterator;
+import org.codehaus.plexus.archiver.diags.NoOpArchiver;
+import org.codehaus.plexus.components.io.fileselectors.FileInfo;
+import org.codehaus.plexus.components.io.resources.PlexusIoResource;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+class SimpleAggregatingDescriptorHandlerTest {
+
+    private SimpleAggregatingDescriptorHandler handler;
+
+    @BeforeEach
+    void setUp() {
+        handler = new SimpleAggregatingDescriptorHandler();
+        handler.setFilePattern(".*file.txt");
+        handler.setOutputPath("file.txt");
+    }
+
+    @Test
+    void 
finalizeArchiveCreationShouldAggregateResourcesVisitedAfterFinalizersRun() 
throws Exception {
+        PlexusIoResource a = resource("a/file.txt", "file A");
+        PlexusIoResource b = resource("b/file.txt", "file B");
+
+        List<String> lines = finalizeWith(new WalkingArchiver(handler, a, b));
+
+        assertEquals(1, count(lines, "file A"), lines.toString());
+        assertEquals(1, count(lines, "file B"), lines.toString());
+    }
+
+    @Test
+    void shouldAggregateFilesWithTheSameNameFromDifferentSources() throws 
Exception {
+        // <file> entries are checked when added, and are named after the file 
alone
+        assertFalse(handler.isSelected(info("file.txt", "file A")));
+        assertFalse(handler.isSelected(info("file.txt", "file B")));
+        // unpacked dependencies carry the same archive-internal path
+        PlexusIoResource one = resource("META-INF/file.txt", "from jar 1");
+        PlexusIoResource two = resource("META-INF/file.txt", "from jar 2");
+
+        List<String> lines = finalizeWith(new WalkingArchiver(handler, one, 
two));
+
+        for (String expected : new String[] {"file A", "file B", "from jar 1", 
"from jar 2"}) {
+            assertEquals(1, count(lines, expected), lines.toString());
+        }
+    }
+
+    @Test
+    void shouldNotDuplicateContentWhenResourcesAreWalkedAgain() throws 
Exception {
+        PlexusIoResource a = resource("a/file.txt", "file A");
+        WalkingArchiver archiver = new WalkingArchiver(handler, a);
+
+        // another finalizer's walk before ours
+        archiver.walk();
+
+        List<String> lines = finalizeWith(archiver);
+        // execute() walks again after the aggregate was written
+        archiver.walk();
+
+        assertEquals(1, count(lines, "file A"), lines.toString());
+    }
+
+    @Test
+    void shouldNotCarryContentOverToTheNextArchive() throws Exception {
+        finalizeWith(new WalkingArchiver(handler, resource("a/file.txt", "file 
A")));
+        // the walk of the first archive's execute()
+        assertFalse(handler.isSelected(resource("a/file.txt", "file A")));
+
+        List<String> lines = finalizeWith(new WalkingArchiver(handler, 
resource("b/file.txt", "file B")));
+
+        assertEquals(1, count(lines, "file B"), lines.toString());
+        assertEquals(0, count(lines, "file A"), lines.toString());
+    }
+
+    private static long count(List<String> lines, String line) {
+        return lines.stream().filter(line::equals).count();
+    }
+
+    private List<String> finalizeWith(WalkingArchiver archiver) throws 
IOException {
+        handler.finalizeArchiveCreation(archiver);
+        assertNotNull(archiver.aggregate, "aggregate should have been added");
+        return Files.readAllLines(archiver.aggregate.toPath(), 
StandardCharsets.UTF_8);
+    }
+
+    private static PlexusIoResource resource(String name, String content) 
throws IOException {
+        PlexusIoResource r = mock(PlexusIoResource.class);
+        when(r.getName()).thenReturn(name);
+        when(r.isFile()).thenReturn(true);
+        when(r.getContents()).thenAnswer(i -> new 
ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8)));
+        return r;
+    }
+
+    private static FileInfo info(String name, String content) {
+        return new FileInfo() {
+            @Override
+            public String getName() {
+                return name;
+            }
+
+            @Override
+            public boolean isFile() {
+                return true;
+            }
+
+            @Override
+            public boolean isDirectory() {
+                return false;
+            }
+
+            @Override
+            public boolean isSymbolicLink() {
+                return false;
+            }
+
+            @Override
+            public java.io.InputStream getContents() {
+                return new 
ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8));
+            }
+        };
+    }
+
+    /** Hands out its resources by running them past the handler, as the 
archiver does. */
+    private static final class WalkingArchiver extends NoOpArchiver {
+        private final SimpleAggregatingDescriptorHandler handler;
+        private final List<PlexusIoResource> resources = new ArrayList<>();
+        File aggregate;
+
+        WalkingArchiver(SimpleAggregatingDescriptorHandler handler, 
PlexusIoResource... resources) {
+            this.handler = handler;
+            this.resources.addAll(Arrays.asList(resources));
+        }
+
+        void walk() {
+            for (ResourceIterator it = getResources(); it.hasNext(); ) {
+                it.next();
+            }
+        }
+
+        @Override
+        public ResourceIterator getResources() throws ArchiverException {
+            return new ResourceIterator() {
+                private int index;
+
+                @Override
+                public boolean hasNext() {
+                    return index < resources.size();
+                }
+
+                @Override
+                public ArchiveEntry next() {
+                    try {
+                        handler.isSelected(resources.get(index++));
+                    } catch (IOException e) {
+                        throw new ArchiverException(e.getMessage(), e);
+                    }
+                    return null;
+                }
+            };
+        }
+
+        @Override
+        public void addFile(File inputFile, String destFileName) {
+            aggregate = inputFile;
+        }
+    }
+}

Reply via email to