You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@maven.apache.org by de...@apache.org on 2026/09/24 10:59:19 UTC

(maven-jar-plugin) branch master updated: Skip creating a JAR when includes match no files (#598)

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

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


The following commit(s) were added to refs/heads/master by this push:
     new 68eace3  Skip creating a JAR when includes match no files (#598)
68eace3 is described below

commit 68eace39bc2c3e09ec99df54f9b170f17fda438a
Author: Martin Desruisseaux <ma...@geomatys.com>
AuthorDate: Thu Sep 24 12:59:14 2026 +0200

    Skip creating a JAR when includes match no files (#598)
    
    Original request: https://github.com/apache/maven-jar-plugin/issues/510
    Test copied from https://github.com/apache/maven-jar-plugin/pull/591
---
 src/it/MJAR-510/pom.xml                            | 51 ++++++++++++++++++++++
 .../MJAR-510/src/main/java/my/org/app1/App1.java   | 21 +++++++++
 .../src/test/java/my/org/app1/App1Test.java        | 21 +++++++++
 src/it/MJAR-510/verify.groovy                      | 45 +++++++++++++++++++
 .../apache/maven/plugins/jar/AbstractJarMojo.java  |  2 +-
 .../java/org/apache/maven/plugins/jar/Archive.java | 22 +++++++++-
 .../apache/maven/plugins/jar/FileCollector.java    | 41 ++++++++++++-----
 .../org/apache/maven/plugins/jar/ToolExecutor.java |  2 +-
 8 files changed, 190 insertions(+), 15 deletions(-)

diff --git a/src/it/MJAR-510/pom.xml b/src/it/MJAR-510/pom.xml
new file mode 100644
index 0000000..8a93400
--- /dev/null
+++ b/src/it/MJAR-510/pom.xml
@@ -0,0 +1,51 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  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.
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+  <modelVersion>4.0.0</modelVersion>
+  <groupId>org.apache.maven.plugins</groupId>
+  <artifactId>maven-jar-plugin-test-mjar-510</artifactId>
+  <version>1.0</version>
+  <name>MJAR-510</name>
+  <description>skipIfEmpty should skip when includes match no files</description>
+  <build>
+    <plugins>
+      <plugin>
+        <groupId>org.apache.maven.plugins</groupId>
+        <artifactId>maven-jar-plugin</artifactId>
+        <version>@project.version@</version>
+        <executions>
+          <execution>
+            <id>junit</id>
+            <goals>
+              <goal>test-jar</goal>
+            </goals>
+            <configuration>
+              <classifier>junit</classifier>
+              <skipIfEmpty>true</skipIfEmpty>
+              <excludes>
+                <exclude>**/*Test.class</exclude>
+              </excludes>
+            </configuration>
+          </execution>
+        </executions>
+      </plugin>
+    </plugins>
+  </build>
+</project>
diff --git a/src/it/MJAR-510/src/main/java/my/org/app1/App1.java b/src/it/MJAR-510/src/main/java/my/org/app1/App1.java
new file mode 100644
index 0000000..965d451
--- /dev/null
+++ b/src/it/MJAR-510/src/main/java/my/org/app1/App1.java
@@ -0,0 +1,21 @@
+/*
+ * 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 my.org.app1;
+
+public class App1 {}
diff --git a/src/it/MJAR-510/src/test/java/my/org/app1/App1Test.java b/src/it/MJAR-510/src/test/java/my/org/app1/App1Test.java
new file mode 100644
index 0000000..a25dbff
--- /dev/null
+++ b/src/it/MJAR-510/src/test/java/my/org/app1/App1Test.java
@@ -0,0 +1,21 @@
+/*
+ * 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 my.org.app1;
+
+public class App1Test {}
diff --git a/src/it/MJAR-510/verify.groovy b/src/it/MJAR-510/verify.groovy
new file mode 100644
index 0000000..b6b63e2
--- /dev/null
+++ b/src/it/MJAR-510/verify.groovy
@@ -0,0 +1,45 @@
+
+/*
+ * 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.
+ */
+
+import java.io.*;
+
+try
+{
+    File target = new File( basedir, "target" );
+    File artifact = new File( target, "maven-jar-plugin-test-mjar-510-1.0.jar" );
+    if ( !artifact.exists() )
+    {
+        System.err.println( "main artifact is missing." );
+        return false;
+    }
+
+    File junitArtifact = new File( target, "maven-jar-plugin-test-mjar-510-1.0-junit.jar" );
+    if ( junitArtifact.exists() )
+    {
+        System.err.println( "junit classifier jar should not exist when includes match no files." );
+        return false;
+    }
+    return true;
+}
+catch( Throwable e )
+{
+    e.printStackTrace();
+}
+return false;
diff --git a/src/main/java/org/apache/maven/plugins/jar/AbstractJarMojo.java b/src/main/java/org/apache/maven/plugins/jar/AbstractJarMojo.java
index 28190e3..ea294d2 100644
--- a/src/main/java/org/apache/maven/plugins/jar/AbstractJarMojo.java
+++ b/src/main/java/org/apache/maven/plugins/jar/AbstractJarMojo.java
@@ -388,7 +388,7 @@ public abstract class AbstractJarMojo implements org.apache.maven.api.plugin.Moj
         if (!notExists) {
             Files.walkFileTree(classesDirectory, files);
         }
-        files.prune(skipIfEmpty);
+        files.prune();
         List<Path> moduleRoots = files.getModuleHierarchyRoots();
         if (!moduleRoots.isEmpty()) {
             executor.pomDerivation = new PomDerivation(this, moduleRoots);
diff --git a/src/main/java/org/apache/maven/plugins/jar/Archive.java b/src/main/java/org/apache/maven/plugins/jar/Archive.java
index 75e1001..bf0e41d 100644
--- a/src/main/java/org/apache/maven/plugins/jar/Archive.java
+++ b/src/main/java/org/apache/maven/plugins/jar/Archive.java
@@ -133,6 +133,12 @@ final class Archive {
         @Nonnull
         final List<Path> files;
 
+        /**
+         * Whether the list of files contain at least one regular file.
+         * This is read and updated by {@link FileCollector}.
+         */
+        boolean hasRegularFiles;
+
         /**
          * Creates an initially empty set of files or directories for a specific target Java release.
          *
@@ -143,6 +149,18 @@ final class Archive {
             this.files = new ArrayList<>();
         }
 
+        /**
+         * Returns whether this file set is empty.
+         * If {@code wantRegularFiles} is {@code true}, this method returns {@code true}
+         * even for a non-empty file set if all paths are directories with no regular files.
+         *
+         * @param wantRegularFiles whether the file set should contain at least one regular file
+         * @return whether this file set is empty
+         */
+        boolean isEmpty(boolean wantRegularFiles) {
+            return wantRegularFiles ? !hasRegularFiles : files.isEmpty();
+        }
+
         /**
          * Discards all files in this file set, normally because those files are not in any module.
          * This method returns a common parent directory for all the files that were discarded.
@@ -342,7 +360,7 @@ final class Archive {
         FileSet keep = (skipIfEmpty || isEmpty())
                 ? null
                 : filesetForRelease.firstEntry().getValue();
-        filesetForRelease.values().removeIf((fs) -> fs.files.isEmpty());
+        filesetForRelease.values().removeIf((fs) -> fs.isEmpty(skipIfEmpty));
         Iterator<Map.Entry<Runtime.Version, FileSet>> it =
                 filesetForRelease.entrySet().iterator();
         if (it.hasNext()) {
@@ -362,7 +380,7 @@ final class Archive {
      * {@return whether this archive has nothing to archive}
      * This method can return {@code false} even when there are no file to archive.
      * It can happen if {@link AbstractJarMojo#skipIfEmpty} is {@code false}. In this case,
-     * the "empty" <abbr>JAR</abbr> file will still contain at {@code META-INF/MANIFEST.MF} file.
+     * the "empty" <abbr>JAR</abbr> file will still contain a {@code META-INF/MANIFEST.MF} file.
      *
      * <p><b>Prerequisites:</b>
      * The {@link #prune(boolean)} method should be invoked before this method for accurate result.</p>
diff --git a/src/main/java/org/apache/maven/plugins/jar/FileCollector.java b/src/main/java/org/apache/maven/plugins/jar/FileCollector.java
index cc5e197..b26a390 100644
--- a/src/main/java/org/apache/maven/plugins/jar/FileCollector.java
+++ b/src/main/java/org/apache/maven/plugins/jar/FileCollector.java
@@ -87,6 +87,16 @@ final class FileCollector extends SimpleFileVisitor<Path> {
      */
     private final boolean detectMultiReleaseJar;
 
+    /**
+     * Whether to skip creating empty archives.
+     * If {@code true}, the {@code FileCollector} needs to check if at least one regular file exists.
+     * If {@code false} and there are no include/exclude filters, it is okay to visit only directories.
+     * The default value is {@code false}.
+     *
+     * @see AbstractJarMojo#skipIfEmpty
+     */
+    private final boolean skipIfEmpty;
+
     /**
      * The root directory to traverse. It will be used for temporarily moving excluded files.
      */
@@ -182,6 +192,7 @@ final class FileCollector extends SimpleFileVisitor<Path> {
         this.context = context;
         rootDirectory = directory;
         detectMultiReleaseJar = mojo.detectMultiReleaseJar;
+        skipIfEmpty = mojo.skipIfEmpty;
         directoryRoles = new ArrayDeque<>();
         fileMatcher = matcherFactory.createPathMatcher(directory, mojo.getIncludes(), mojo.getExcludes(), false);
         directoryMatcher = matcherFactory.deriveDirectoryMatcher(fileMatcher);
@@ -353,7 +364,7 @@ final class FileCollector extends SimpleFileVisitor<Path> {
          */
         if (role == DirectoryRole.RESOURCES) {
             currentFilesToArchive.add(directory, attributes, true);
-            if (excludedFiles == null) {
+            if (excludedFiles == null && (!skipIfEmpty || currentFilesToArchive.hasRegularFiles)) {
                 /*
                  * Since we are skipping the whole directory, `postVisitDirectory(…)` will not be invoked.
                  * We must reset `currentFilesToArchive` and `currentTargetVersion` by an explicit call.
@@ -430,6 +441,10 @@ final class FileCollector extends SimpleFileVisitor<Path> {
             if (checkForManifest && file.endsWith(MetadataFiles.MANIFEST) && currentModule.setManifest(file, false)) {
                 // Do not add `MANIFEST.MF`, it will be handled by the `--manifest` option instead.
             } else {
+                currentFilesToArchive.hasRegularFiles = true;
+                if (excludedFiles == null && directoryRoles.peekLast() == DirectoryRole.RESOURCES) {
+                    return FileVisitResult.SKIP_SIBLINGS; // We only wanted to verify whether at least one file exist.
+                }
                 currentFilesToArchive.add(file, attributes, false);
             }
         } else {
@@ -441,12 +456,10 @@ final class FileCollector extends SimpleFileVisitor<Path> {
     /**
      * Removes all empty archives and ensures that the lowest version is declared as the base version.
      * This method should be invoked after all output directories to archive have been fully scanned.
-     * If {@code skipIfEmpty} is {@code false}, this method ensures that at least one archive remains
-     * even if that archive is empty.
-     *
-     * @param skipIfEmpty value of {@link AbstractJarMojo#skipIfEmpty}
+     * If {@link AbstractJarMojo#skipIfEmpty} is {@code false}, this method ensures that at least one
+     * archive remains even if that archive is empty.
      */
-    public void prune(boolean skipIfEmpty) {
+    public void prune() {
         boolean isModuleHierarchy = !moduleHierarchy.isEmpty();
         moduleHierarchy.values().forEach((archive) -> archive.prune(skipIfEmpty));
         moduleHierarchy.values().removeIf(Archive::isEmpty);
@@ -466,7 +479,7 @@ final class FileCollector extends SimpleFileVisitor<Path> {
      * correct for a module. For now, we just log a warning and ignore.</p>
      *
      * <p><b>Prerequisites:</b>
-     * The {@link #prune(boolean)} method should have been invoked once before invoking this method.</p>
+     * The {@link #prune()} method should have been invoked once before invoking this method.</p>
      *
      * @return if this method ignored some files, the root directory of those files
      */
@@ -479,12 +492,18 @@ final class FileCollector extends SimpleFileVisitor<Path> {
         return packageHierarchy.discardAllFiles();
     }
 
+    /**
+     * Returns whether the given list is null or empty.
+     */
+    private static boolean isEmpty(final List<Path> paths) {
+        return paths == null || paths.isEmpty();
+    }
+
     /**
      * Returns the object in charge of moving excluded files to a temporary directory, or {@code null} if none.
      */
     private ExcludedFiles exclusion() throws IOException {
-        if ((excludedFiles == null || excludedFiles.isEmpty())
-                && (excludedDirectories == null || excludedDirectories.isEmpty())) {
+        if (isEmpty(excludedFiles) && isEmpty(excludedDirectories)) {
             return null;
         }
         return new ExcludedFiles(rootDirectory, excludedFiles, excludedDirectories);
@@ -495,7 +514,7 @@ final class FileCollector extends SimpleFileVisitor<Path> {
      * If the project is multi-module, this method returns the path to the generated parent <abbr>POM</abbr> file.
      *
      * <p><b>Prerequisites:</b>
-     * The {@link #prune(boolean)} method should have been invoked once before to invoke this method.</p>
+     * The {@link #prune()} method should have been invoked once before to invoke this method.</p>
      *
      * @return path to the generated parent <abbr>POM</abbr> file, or {@code null} if none
      * @throws MojoException if an error occurred during the execution of the "jar" tool
@@ -532,7 +551,7 @@ final class FileCollector extends SimpleFileVisitor<Path> {
      * we do not perform such derivation for projects organized in the Maven 3 way.
      *
      * <h4>Prerequisites</h4>
-     * The {@link #prune(boolean)} method should have been invoked once before invoking this method.
+     * The {@link #prune()} method should have been invoked once before invoking this method.
      */
     List<Path> getModuleHierarchyRoots() {
         return moduleHierarchy.values().stream()
diff --git a/src/main/java/org/apache/maven/plugins/jar/ToolExecutor.java b/src/main/java/org/apache/maven/plugins/jar/ToolExecutor.java
index 9c2f1cd..10988ef 100644
--- a/src/main/java/org/apache/maven/plugins/jar/ToolExecutor.java
+++ b/src/main/java/org/apache/maven/plugins/jar/ToolExecutor.java
@@ -307,7 +307,7 @@ final class ToolExecutor {
      * content of {@code module-info.class} files.
      *
      * <p><b>Prerequisites:</b>
-     * The {@link FileCollector#prune(boolean)} method should have been invoked once before to invoke this method.</p>
+     * The {@link FileCollector#prune()} method should have been invoked once before to invoke this method.</p>
      *
      * @param files the result of scanning the build directory for listing the files or directories to archive
      * @return the paths to the created archive files