You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@maven.apache.org by "desruisseaux (via GitHub)" <gi...@apache.org> on 2025/12/13 16:22:45 UTC

[PR] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

desruisseaux opened a new pull request, #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508

   This is a major refactoring of the Maven JAR Plugin for using the standard `jar` tool instead of Maven Archiver. The standard tool is available through the `java.util.spi.ToolProvider` interface, which was introduced in Java 9. Since Maven 4 upgraded its requirement from Java 8 to Java 17, the use of that interface is no longer problematic.
   
   # Rational
   In early Java days, the `jar` tool was equivalent to a `zip` command with a different syntax and a little bit of special processing for the `META-INF/MANIFEST.MF` file. Because of this quasi-equivalence, it was not difficult to create JAR files ourselves using any library capable to write ZIP files. This is what Maven Archiver does, together with supporting other archive formats. But today, the `jar` tool became more sophisticated. It now includes options for verifying the consistency of multi-release JAR files, options for updating `module-info.class`, provides security features specific to Java, _etc._. This evolution can be seen in the ["Modular JAR files" section of the Maven Plugin documentation](https://maven.apache.org/plugins/maven-jar-plugin/usage.html#Modular_JAR_files), which states that the plugin uses the `jar` tool for updating the JAR file in a way that the Maven Archiver can't do easily. Therefore, since Maven 4 requires Java 17 and since that Java version gives us
  an easy access to the `jar` tool through the `java.util.spi.ToolProvider` interface, it may be time to abandon our manual creation of a JAR file and rely fully on the `jar` tool instead.
   
   # Benefits
   
   ## Safer multi-release JAR files
   In a multi-release JAR file, blindingly storing the content of `META-INF/versions/` directories as if they were ordinary resources is not equivalent to using the `jar --release` option. The difference is that in the latter case, the `jar` tool performs some consistency checks. This issue was independently reported by user in #484, which is fixed by this pull request. Note that if this verification is not desired, Maven users can disable it by setting the `detectMultiReleaseJar` plugin option to `false`.
   
   ## Main class managed by the `jar` tool
   In a modular JAR file, it is no longer sufficient to declare the main class in the `Main-Class` entry of the `MANIFEST.MF` file. The main class needs to be specified by the `--main-class` option of the `jar` tool, which will update `module-info.class`. For compatibility reason the Maven JAR plugin gets the option value from that manifest entry, but internally the use of the `jar` tool is mandatory.
   
   ## Options not yet supported by the plugin
   This approach allows to add a `<jarArgs>` configuration option, similar to the `<compilerArgs>` in the Maven Compiler Plugin. Such option would allow developers to use new tool arguments before they are supported by the plugin.
   
   Examples of options not yet supported by the plugin are `--module-version` and `--hash-modules`. Explicit support for those options could be added in a future plugin version, especially since security is becoming more and more a concern.
   
   ## Easier debugging and toolchain
   This approach makes easy to generate a `target/jar.args` file when the build fails or when Maven is run in verbose mode. This is similar to the compiler plugin generating a `target/javac.args` file. This file allows the user to test easily on the command-line, which makes debugging faster. Likewise, the options can also be passed to another tool, which makes easier to resolve #439 as well.
   
   # Behavioral changes
   The plugin behaviour after the proposed refactoring is different than version 3 in the following aspects:
   
   ## Removal of default `**/package.html` excludes
   The current plugin version uses an undocumented `**/package.html` default excludes. This default seems to exist since the initial revision in March 2004, but I saw no explanation for this oddity. This default is not mentioned in the documentation. The removal of this oddity is necessary for allowing the proposed new plugin implementation to specify only some root directories to the `jar` tool, since the tool can traverse the directory tree itself.
   
   ## Automatic use of `MANIFEST.MF`
   After this refactor, the plugin automatically uses the `META-INF/MANIFEST.MF` file found in the `classes` directory. Before this refactor, the plugin used that file only if explicitly specified in the `<manifestFile>` archive configuration. The previous policy was discussed in #255. The new policy is a natural consequence of the way that the JAR plugin is reimplemented, and also more useful in the context of multi-module (in Java module sense) projects since each module could contain its own `MANIFEST.MF` file.
   
   ## Multi-module projects
   The refactoral support multi-module projects, including projects that are both multi-module and multi-release, as discussed in https://github.com/apache/maven-compiler-plugin/pull/998.
   
   # Dependencies
   This pull request depends on a Maven release which include the following pull requests:
   
   * https://github.com/apache/maven/pull/11425
   * https://github.com/apache/maven/pull/11549
   * https://github.com/apache/maven-compiler-plugin/pull/998
   


-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "elharo (via GitHub)" <gi...@apache.org>.
elharo commented on PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#issuecomment-5394490896

   I would remove "on unspecified JDK". I might add the actual JDK version since reproducible builds require the same toolchain for now. 
   
   For the record, I do not think "semantically reproducible builds" are a thing. Byte-per-byte comparison is the only thing that works. 


-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "elharo (via GitHub)" <gi...@apache.org>.
elharo commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3805339434


##########
src/main/java/org/apache/maven/plugins/jar/AbstractJarMojo.java:
##########
@@ -18,44 +18,44 @@
  */
 package org.apache.maven.plugins.jar;
 
-import java.io.File;
 import java.io.IOException;
 import java.nio.file.Files;
 import java.nio.file.Path;
+import java.time.Instant;
 import java.util.Arrays;
+import java.util.List;
 import java.util.Map;
-import java.util.Objects;
-import java.util.jar.Attributes;
-import java.util.stream.Stream;
+import java.util.spi.ToolProvider;
 
+import org.apache.maven.api.PathScope;
 import org.apache.maven.api.ProducedArtifact;
 import org.apache.maven.api.Project;
 import org.apache.maven.api.Session;
+import org.apache.maven.api.Type;
 import org.apache.maven.api.di.Inject;
 import org.apache.maven.api.plugin.Log;
 import org.apache.maven.api.plugin.MojoException;
 import org.apache.maven.api.plugin.annotations.Parameter;
+import org.apache.maven.api.services.PathMatcherFactory;
 import org.apache.maven.api.services.ProjectManager;
 import org.apache.maven.shared.archiver.MavenArchiveConfiguration;
 import org.apache.maven.shared.archiver.MavenArchiver;
-import org.apache.maven.shared.archiver.MavenArchiverException;
-import org.apache.maven.shared.model.fileset.FileSet;
-import org.apache.maven.shared.model.fileset.util.FileSetManager;
-import org.codehaus.plexus.archiver.Archiver;
-import org.codehaus.plexus.archiver.jar.JarArchiver;
 
 /**
  * Base class for creating a <abbr>JAR</abbr> file from project classes.
  *
  * @author <a href="evenisse@apache.org">Emmanuel Venisse</a>
+ * @author Martin Desruisseaux
  */
 public abstract class AbstractJarMojo implements org.apache.maven.api.plugin.Mojo {
-
-    private static final String[] DEFAULT_EXCLUDES = new String[] {"**/package.html"};
-
-    private static final String[] DEFAULT_INCLUDES = new String[] {"**/**"};
-
-    private static final String MODULE_DESCRIPTOR_FILE_NAME = "module-info.class";
+    /**
+     * Identifier of the tool to use. This identifier shall match the identifier of a tool

Review Comment:
   Yes, exactly, This is not an ISO standard and we should avoid standards language like "shall" which is very uncommon in normal English these days. Also avoid "may" and a capital "MUST". Mixing standards jargon into non-standards documents is a recipe for confusion.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3892011722


##########
src/main/java/org/apache/maven/plugins/jar/FileCollector.java:
##########
@@ -0,0 +1,496 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.PathMatcher;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayDeque;
+import java.util.Deque;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.services.PathMatcherFactory;
+
+/**
+ * Dispatch the files in the output directory into the <abbr>JAR</abbr> files to create.
+ * Instead of just archiving as-is the content of the output directory, this class separates
+ * the following subdirectories to the options listed below:
+ *
+ * <ul>
+ *   <li>The {@code META-INF/MANIFEST.MF} file will be given to the {@code --manifest} option.</li>
+ *   <li>Files in the following directories will be given to the {@code --release} option:
+ *     <ul>
+ *       <li>{@code META-INF/versions/}</li>
+ *       <li>{@code META-INF/versions-modular/<module>/}</li>
+ *       <li>{@code <module>/META-INF/versions/}</li>
+ *     </ul>
+ *   </li>
+ * </ul>
+ *
+ * The reason for using the options is that they allow the {@code jar} tool to perform additional verifications.
+ * For example, when using the {@code --release} option, {@code jar} verifies the <abbr>API</abbr> compatibility.
+ */
+final class FileCollector extends SimpleFileVisitor<Path> {
+    /**
+     * The file to check for deciding whether the <abbr>JAR</abbr> is modular.
+     */
+    static final String MODULE_DESCRIPTOR_FILE_NAME = "module-info.class";
+
+    /**
+     * The {@value} directory.
+     * This is part of <abbr>JAR</abbr> file specification.
+     */
+    private static final String VERSIONS = "versions";
+
+    /**
+     * The {@value} directory.
+     * This is Maven-specific.
+     */
+    private static final String VERSIONS_MODULAR = "versions-modular";
+
+    /**
+     * Context (logger, configuration) in which the <abbr>JAR</abbr> file are created.
+     */
+    private final ToolExecutor context;
+
+    /**
+     * Whether to detect multi-release <abbr>JAR</abbr> files.
+     * The default value is {@code true}.
+     *
+     * @see AbstractJarMojo#detectMultiReleaseJar
+     */
+    private final boolean detectMultiReleaseJar;
+
+    /**
+     * Combination of includes and excludes path matcher applied on files.
+     */
+    @Nonnull
+    private final PathMatcher fileMatcher;
+
+    /**
+     * Combination of includes and excludes path matcher applied on directories.
+     */
+    @Nonnull
+    private final PathMatcher directoryMatcher;
+
+    /**
+     * Whether the matchers accept all files and there is no need to sort the files.
+     * In such case, we can declare whole directories to the {@code jar} tool instead
+     * of scanning the directory tree ourselves.
+     */
+    private final boolean addDirectories;
+
+    /**
+     * Files found in the output directory when package hierarchy is used.
+     * At most one of {@code packageHierarchy} and {@link #moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Archive packageHierarchy;
+
+    /**
+     * Files found in the output directory when module hierarchy is used. Keys are module names.
+     * At most one of {@link #packageHierarchy} and {@code moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Map<String, Archive> moduleHierarchy;
+
+    /**
+     * The current module being archived. This field is updated every times that {@code FileCollector}
+     * enters in a new module directory.
+     */
+    @Nonnull
+    private Archive currentModule;
+
+    /**
+     * The module and target Java release currently being scanned. This field is updated every times that
+     * {@code FileCollector} enters in a new module directory or in a new target Java release for a given module.
+     */
+    @Nonnull
+    private Archive.FileSet currentFilesToArchive;
+
+    /**
+     * The current target Java release, or {@code null} if none.
+     */
+    @Nullable
+    private Runtime.Version currentTargetVersion;
+
+    /**
+     * Identification of the kinds of directories being traversed.
+     * The length of this list is the depth in the directory hierarchy.
+     * The last element identifies the type of the current directory.
+     */
+    private final Deque<DirectoryRole> directoryRoles;
+
+    /**
+     * Whether to check when a file is the {@code MANIFEST.MF} file.
+     * This is allowed only when scanning the content of a {@code META-INF} directory.
+     */
+    private boolean checkForManifest;
+
+    /**
+     * Creates a new file collector.
+     *
+     * @param mojo the <abbr>MOJO</abbr> from which to get the configuration
+     * @param context context (logger, configuration) in which the <abbr>JAR</abbr> file are created
+     * @param directory the base directory of the files to archive
+     */
+    FileCollector(AbstractJarMojo mojo, ToolExecutor context, Path directory, PathMatcherFactory matcherFactory) {
+        this.context = context;
+        detectMultiReleaseJar = mojo.detectMultiReleaseJar;
+        directoryRoles = new ArrayDeque<>();
+        fileMatcher = matcherFactory.createPathMatcher(directory, mojo.getIncludes(), mojo.getExcludes(), false);
+        directoryMatcher = matcherFactory.deriveDirectoryMatcher(fileMatcher);
+        addDirectories = !context.isReproducible()
+                && matcherFactory.isIncludesAll(fileMatcher)
+                && matcherFactory.isIncludesAll(directoryMatcher);
+        packageHierarchy = context.newArchive(null, null, directory);
+        moduleHierarchy = new LinkedHashMap<>();
+        resetToPackageHierarchy();
+    }
+
+    /**
+     * Resets this {@code FileCollector} to the state where a package hierarchy is presumed.
+     */
+    private void resetToPackageHierarchy() {
+        currentModule = packageHierarchy;
+        currentFilesToArchive = currentModule.baseRelease();
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a module.
+     * For an output generated by {@code javac} from a module source hierarchy,
+     * the directory name is guaranteed to be the module name.
+     *
+     * @param directory a {@code "<module>"} or {@code "META-INF/versions-modular/<module>"} directory
+     */
+    private void enterModuleDirectory(final Path directory) {
+        String moduleName = directory.getFileName().toString();
+        currentModule = moduleHierarchy.computeIfAbsent(
+                moduleName, (name) -> context.newArchive(name, currentTargetVersion, directory));
+        currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a target Java version.
+     * The {@code useDirectly} argument tells whether the content of this directory will be specified directly
+     * as the content to add in the <abbr>JAR</abbr> file. This argument should be {@code false} when there is
+     * another directory level (the module names) to process before to add content.
+     *
+     * @param directory a {@code "META-INF/versions/<n>"} or {@code "META-INF/versions-modular/<n>"} directory
+     * @param useDirectly whether the directory is {@code "META-INF/versions/<n>"}
+     * @return whether to skip the directory because of invalid version number
+     */
+    private boolean enterVersionDirectory(final Path directory, final boolean useDirectly) {
+        try {
+            currentTargetVersion = Runtime.Version.parse(directory.getFileName().toString());
+        } catch (IllegalArgumentException e) {
+            context.warnInvalidVersion(directory, e);
+            return true;
+        }
+        if (useDirectly) {
+            currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+        }
+        return false;
+    }
+
+    /**
+     * Determines if the given directory should be scanned for files to archive.
+     * This method may also update {@link #currentFilesToArchive} if it detects
+     * that we are entering in a new module or a new target Java release.
+     *
+     * @param directory the directory which will be traversed
+     * @param attributes the directory's basic attributes
+     */
+    @Override
+    @SuppressWarnings("checkstyle:MissingSwitchDefault")
+    public FileVisitResult preVisitDirectory(final Path directory, final BasicFileAttributes attributes)
+            throws IOException {
+        DirectoryRole role;
+        if (directoryRoles.isEmpty()) {
+            role = DirectoryRole.ROOT;
+        } else {
+            if (!directoryMatcher.matches(directory)) {
+                return FileVisitResult.SKIP_SUBTREE;
+            }
+            checkForManifest = false;
+            role = directoryRoles.getLast();
+            switch (role) {
+                case ROOT:
+                    /*
+                     * Entering in any subdirectory of `target/classes` (or other directory to archive).
+                     * We need to handle `META-INF` and modules in a special way, and archive the rest.
+                     */
+                    if (directory.endsWith(MetadataFiles.META_INF)) {
+                        role = DirectoryRole.META_INF;
+                        checkForManifest = true;
+                    } else if (Files.isRegularFile(directory.resolve(MODULE_DESCRIPTOR_FILE_NAME))) {
+                        role = DirectoryRole.NAMED_MODULE;
+                        enterModuleDirectory(directory);
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case META_INF:
+                    /*
+                     * Entering in a subdirectory of `META-INF` or `<module>/META-INF`. We will need to handle
+                     * `MANIFEST.MF`, `versions` and `versions-modular` in a special way, and archive the rest.
+                     */
+                    if (detectMultiReleaseJar && directory.endsWith(VERSIONS)) {
+                        role = DirectoryRole.VERSIONS;
+                    } else if (directory.endsWith(VERSIONS_MODULAR)) {
+                        if (!detectMultiReleaseJar) {
+                            // Used asked for no multi-release JAR.
+                            return FileVisitResult.SKIP_SUBTREE;
+                        }
+                        role = DirectoryRole.VERSIONS_MODULAR;
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case VERSIONS:
+                    /*
+                     * Entering in a `META-INF/versions/<n>/` directory for a specific target Java release.
+                     * May also be a `<module>/META-INF/versions/<n>/` directory, even if the latter is not
+                     * the layout generated by Maven Compiler Plugin.
+                     */
+                    if (enterVersionDirectory(directory, true)) {
+                        // An error occurred while parsing the version number.
+                        return FileVisitResult.SKIP_SUBTREE;
+                    }
+                    role = DirectoryRole.RESOURCES;
+                    break;
+
+                case VERSIONS_MODULAR:
+                    /*
+                     * Entering in a `META-INF/versions-modular/<n>/` directory for a specific target Java release.
+                     * That directory contains all modules for the version.
+                     */
+                    resetToPackageHierarchy(); // No module in particular yet.
+                    if (enterVersionDirectory(directory, false)) {
+                        // An error occurred while parsing the version number.
+                        return FileVisitResult.SKIP_SUBTREE;
+                    }
+                    role = DirectoryRole.MODULES;
+                    break;
+
+                case MODULES:
+                    /*
+                     * Entering in a `META-INF/versions-modular/<n>/<module>` directory.
+                     */
+                    enterModuleDirectory(directory);
+                    role = DirectoryRole.NAMED_MODULE;
+                    break;
+
+                case NAMED_MODULE:
+                    /*
+                     * Entering in a `<module>` or `META-INF/versions-modular/<n>/<module>` subdirectory.
+                     * A module could have its own `META-INF` subdirectory, so we need to check again.
+                     */
+                    if (directory.endsWith(MetadataFiles.META_INF)) {
+                        role = DirectoryRole.META_INF;
+                        checkForManifest = true;
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+            }
+        }
+        /*
+         * Do not move this condition inside the `switch` block because `role` may have been modified.
+         * The `role` value is now the role of `directory`, not anymore the role of parent directory.
+         */
+        if (addDirectories && role == DirectoryRole.RESOURCES) {
+            currentFilesToArchive.add(directory, attributes, true);
+            /*
+             * Since we are skipping the whole directory, `postVisitDirectory(…)` will not be invoked.
+             * We must reset `currentFilesToArchive` and `currentTargetVersion` by an explicit call.
+             * This is important mostly after we added a whole `META-INF/versions/<n>` directory,
+             * otherwise base files visited afterwards (directory iteration order is unspecified)
+             * would be added to this version's file set instead of the base release.
+             */
+            resetToParentDirectoryState();
+            return FileVisitResult.SKIP_SUBTREE;
+        } else {
+            directoryRoles.addLast(role);
+            return FileVisitResult.CONTINUE;
+        }
+    }
+
+    /**
+     * Updates the {@code FileCollector} state after we finished to scan the content of a directory.
+     * The fields to update depend on which directory has been visited (module, version, <i>etc.</i>).

Review Comment:
   Done



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3892033886


##########
src/main/java/org/apache/maven/plugins/jar/FileCollector.java:
##########
@@ -0,0 +1,496 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.PathMatcher;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayDeque;
+import java.util.Deque;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.services.PathMatcherFactory;
+
+/**
+ * Dispatch the files in the output directory into the <abbr>JAR</abbr> files to create.
+ * Instead of just archiving as-is the content of the output directory, this class separates
+ * the following subdirectories to the options listed below:
+ *
+ * <ul>
+ *   <li>The {@code META-INF/MANIFEST.MF} file will be given to the {@code --manifest} option.</li>
+ *   <li>Files in the following directories will be given to the {@code --release} option:
+ *     <ul>
+ *       <li>{@code META-INF/versions/}</li>
+ *       <li>{@code META-INF/versions-modular/<module>/}</li>
+ *       <li>{@code <module>/META-INF/versions/}</li>
+ *     </ul>
+ *   </li>
+ * </ul>
+ *
+ * The reason for using the options is that they allow the {@code jar} tool to perform additional verifications.
+ * For example, when using the {@code --release} option, {@code jar} verifies the <abbr>API</abbr> compatibility.
+ */
+final class FileCollector extends SimpleFileVisitor<Path> {
+    /**
+     * The file to check for deciding whether the <abbr>JAR</abbr> is modular.
+     */
+    static final String MODULE_DESCRIPTOR_FILE_NAME = "module-info.class";
+
+    /**
+     * The {@value} directory.
+     * This is part of <abbr>JAR</abbr> file specification.
+     */
+    private static final String VERSIONS = "versions";
+
+    /**
+     * The {@value} directory.
+     * This is Maven-specific.
+     */
+    private static final String VERSIONS_MODULAR = "versions-modular";
+
+    /**
+     * Context (logger, configuration) in which the <abbr>JAR</abbr> file are created.
+     */
+    private final ToolExecutor context;
+
+    /**
+     * Whether to detect multi-release <abbr>JAR</abbr> files.
+     * The default value is {@code true}.
+     *
+     * @see AbstractJarMojo#detectMultiReleaseJar
+     */
+    private final boolean detectMultiReleaseJar;
+
+    /**
+     * Combination of includes and excludes path matcher applied on files.
+     */
+    @Nonnull
+    private final PathMatcher fileMatcher;
+
+    /**
+     * Combination of includes and excludes path matcher applied on directories.
+     */
+    @Nonnull
+    private final PathMatcher directoryMatcher;
+
+    /**
+     * Whether the matchers accept all files and there is no need to sort the files.
+     * In such case, we can declare whole directories to the {@code jar} tool instead
+     * of scanning the directory tree ourselves.
+     */
+    private final boolean addDirectories;
+
+    /**
+     * Files found in the output directory when package hierarchy is used.
+     * At most one of {@code packageHierarchy} and {@link #moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Archive packageHierarchy;
+
+    /**
+     * Files found in the output directory when module hierarchy is used. Keys are module names.
+     * At most one of {@link #packageHierarchy} and {@code moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Map<String, Archive> moduleHierarchy;
+
+    /**
+     * The current module being archived. This field is updated every times that {@code FileCollector}
+     * enters in a new module directory.
+     */
+    @Nonnull
+    private Archive currentModule;
+
+    /**
+     * The module and target Java release currently being scanned. This field is updated every times that
+     * {@code FileCollector} enters in a new module directory or in a new target Java release for a given module.
+     */
+    @Nonnull
+    private Archive.FileSet currentFilesToArchive;
+
+    /**
+     * The current target Java release, or {@code null} if none.
+     */
+    @Nullable
+    private Runtime.Version currentTargetVersion;
+
+    /**
+     * Identification of the kinds of directories being traversed.
+     * The length of this list is the depth in the directory hierarchy.
+     * The last element identifies the type of the current directory.
+     */
+    private final Deque<DirectoryRole> directoryRoles;
+
+    /**
+     * Whether to check when a file is the {@code MANIFEST.MF} file.
+     * This is allowed only when scanning the content of a {@code META-INF} directory.
+     */
+    private boolean checkForManifest;
+
+    /**
+     * Creates a new file collector.
+     *
+     * @param mojo the <abbr>MOJO</abbr> from which to get the configuration
+     * @param context context (logger, configuration) in which the <abbr>JAR</abbr> file are created
+     * @param directory the base directory of the files to archive
+     */
+    FileCollector(AbstractJarMojo mojo, ToolExecutor context, Path directory, PathMatcherFactory matcherFactory) {
+        this.context = context;
+        detectMultiReleaseJar = mojo.detectMultiReleaseJar;
+        directoryRoles = new ArrayDeque<>();
+        fileMatcher = matcherFactory.createPathMatcher(directory, mojo.getIncludes(), mojo.getExcludes(), false);
+        directoryMatcher = matcherFactory.deriveDirectoryMatcher(fileMatcher);
+        addDirectories = !context.isReproducible()
+                && matcherFactory.isIncludesAll(fileMatcher)
+                && matcherFactory.isIncludesAll(directoryMatcher);
+        packageHierarchy = context.newArchive(null, null, directory);
+        moduleHierarchy = new LinkedHashMap<>();
+        resetToPackageHierarchy();
+    }
+
+    /**
+     * Resets this {@code FileCollector} to the state where a package hierarchy is presumed.
+     */
+    private void resetToPackageHierarchy() {
+        currentModule = packageHierarchy;
+        currentFilesToArchive = currentModule.baseRelease();
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a module.
+     * For an output generated by {@code javac} from a module source hierarchy,
+     * the directory name is guaranteed to be the module name.
+     *
+     * @param directory a {@code "<module>"} or {@code "META-INF/versions-modular/<module>"} directory
+     */
+    private void enterModuleDirectory(final Path directory) {
+        String moduleName = directory.getFileName().toString();
+        currentModule = moduleHierarchy.computeIfAbsent(
+                moduleName, (name) -> context.newArchive(name, currentTargetVersion, directory));
+        currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a target Java version.
+     * The {@code useDirectly} argument tells whether the content of this directory will be specified directly
+     * as the content to add in the <abbr>JAR</abbr> file. This argument should be {@code false} when there is
+     * another directory level (the module names) to process before to add content.
+     *
+     * @param directory a {@code "META-INF/versions/<n>"} or {@code "META-INF/versions-modular/<n>"} directory
+     * @param useDirectly whether the directory is {@code "META-INF/versions/<n>"}
+     * @return whether to skip the directory because of invalid version number
+     */
+    private boolean enterVersionDirectory(final Path directory, final boolean useDirectly) {
+        try {
+            currentTargetVersion = Runtime.Version.parse(directory.getFileName().toString());
+        } catch (IllegalArgumentException e) {
+            context.warnInvalidVersion(directory, e);
+            return true;
+        }
+        if (useDirectly) {
+            currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+        }
+        return false;
+    }
+
+    /**
+     * Determines if the given directory should be scanned for files to archive.
+     * This method may also update {@link #currentFilesToArchive} if it detects
+     * that we are entering in a new module or a new target Java release.
+     *
+     * @param directory the directory which will be traversed
+     * @param attributes the directory's basic attributes
+     */
+    @Override
+    @SuppressWarnings("checkstyle:MissingSwitchDefault")
+    public FileVisitResult preVisitDirectory(final Path directory, final BasicFileAttributes attributes)
+            throws IOException {
+        DirectoryRole role;
+        if (directoryRoles.isEmpty()) {
+            role = DirectoryRole.ROOT;
+        } else {
+            if (!directoryMatcher.matches(directory)) {
+                return FileVisitResult.SKIP_SUBTREE;
+            }
+            checkForManifest = false;
+            role = directoryRoles.getLast();
+            switch (role) {
+                case ROOT:
+                    /*
+                     * Entering in any subdirectory of `target/classes` (or other directory to archive).
+                     * We need to handle `META-INF` and modules in a special way, and archive the rest.
+                     */
+                    if (directory.endsWith(MetadataFiles.META_INF)) {
+                        role = DirectoryRole.META_INF;
+                        checkForManifest = true;
+                    } else if (Files.isRegularFile(directory.resolve(MODULE_DESCRIPTOR_FILE_NAME))) {
+                        role = DirectoryRole.NAMED_MODULE;
+                        enterModuleDirectory(directory);
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case META_INF:
+                    /*
+                     * Entering in a subdirectory of `META-INF` or `<module>/META-INF`. We will need to handle
+                     * `MANIFEST.MF`, `versions` and `versions-modular` in a special way, and archive the rest.
+                     */
+                    if (detectMultiReleaseJar && directory.endsWith(VERSIONS)) {
+                        role = DirectoryRole.VERSIONS;
+                    } else if (directory.endsWith(VERSIONS_MODULAR)) {
+                        if (!detectMultiReleaseJar) {
+                            // Used asked for no multi-release JAR.
+                            return FileVisitResult.SKIP_SUBTREE;
+                        }
+                        role = DirectoryRole.VERSIONS_MODULAR;
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case VERSIONS:
+                    /*
+                     * Entering in a `META-INF/versions/<n>/` directory for a specific target Java release.
+                     * May also be a `<module>/META-INF/versions/<n>/` directory, even if the latter is not
+                     * the layout generated by Maven Compiler Plugin.
+                     */
+                    if (enterVersionDirectory(directory, true)) {
+                        // An error occurred while parsing the version number.
+                        return FileVisitResult.SKIP_SUBTREE;
+                    }
+                    role = DirectoryRole.RESOURCES;
+                    break;
+
+                case VERSIONS_MODULAR:
+                    /*
+                     * Entering in a `META-INF/versions-modular/<n>/` directory for a specific target Java release.
+                     * That directory contains all modules for the version.
+                     */
+                    resetToPackageHierarchy(); // No module in particular yet.
+                    if (enterVersionDirectory(directory, false)) {
+                        // An error occurred while parsing the version number.
+                        return FileVisitResult.SKIP_SUBTREE;
+                    }
+                    role = DirectoryRole.MODULES;
+                    break;
+
+                case MODULES:
+                    /*
+                     * Entering in a `META-INF/versions-modular/<n>/<module>` directory.
+                     */
+                    enterModuleDirectory(directory);
+                    role = DirectoryRole.NAMED_MODULE;
+                    break;
+
+                case NAMED_MODULE:
+                    /*
+                     * Entering in a `<module>` or `META-INF/versions-modular/<n>/<module>` subdirectory.
+                     * A module could have its own `META-INF` subdirectory, so we need to check again.
+                     */
+                    if (directory.endsWith(MetadataFiles.META_INF)) {
+                        role = DirectoryRole.META_INF;
+                        checkForManifest = true;
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+            }
+        }
+        /*
+         * Do not move this condition inside the `switch` block because `role` may have been modified.
+         * The `role` value is now the role of `directory`, not anymore the role of parent directory.
+         */
+        if (addDirectories && role == DirectoryRole.RESOURCES) {
+            currentFilesToArchive.add(directory, attributes, true);
+            /*
+             * Since we are skipping the whole directory, `postVisitDirectory(…)` will not be invoked.
+             * We must reset `currentFilesToArchive` and `currentTargetVersion` by an explicit call.
+             * This is important mostly after we added a whole `META-INF/versions/<n>` directory,
+             * otherwise base files visited afterwards (directory iteration order is unspecified)
+             * would be added to this version's file set instead of the base release.
+             */
+            resetToParentDirectoryState();
+            return FileVisitResult.SKIP_SUBTREE;
+        } else {
+            directoryRoles.addLast(role);
+            return FileVisitResult.CONTINUE;
+        }
+    }
+
+    /**
+     * Updates the {@code FileCollector} state after we finished to scan the content of a directory.
+     * The fields to update depend on which directory has been visited (module, version, <i>etc.</i>).
+     *
+     * @param directory the directory which has been traversed
+     * @param error the error that occurred while traversing the directory, or {@code null} if none
+     */
+    @Override
+    public FileVisitResult postVisitDirectory(final Path directory, final IOException error) throws IOException {
+        if (error != null) {
+            throw error;
+        }
+        switch (directoryRoles.removeLast()) {
+            case NAMED_MODULE:
+                // Exited the directory of a single module.
+                resetToPackageHierarchy();
+                break;
+
+            case ROOT:
+                break;
+
+            default:
+                resetToParentDirectoryState();
+        }
+        return FileVisitResult.CONTINUE;
+    }
+
+    /**
+     * Updates {@code FileCollector} to a state suitable to the parent of the directory that we finished to scan.
+     * Contrarily to {@link #postVisitDirectory(Path, IOException)}, this method expects the last element of
+     * {@link #directoryRoles} to describe the parent directory, not the directory that we finished to visit.
+     */
+    @SuppressWarnings("checkstyle:MissingSwitchDefault")
+    private void resetToParentDirectoryState() {
+        switch (directoryRoles.getLast()) {
+            case VERSIONS:
+            case VERSIONS_MODULAR:
+                // Exited the directory for one target Java release.
+                currentFilesToArchive = currentModule.baseRelease();
+                currentTargetVersion = null;
+                break;
+
+            case META_INF:
+                checkForManifest = true;
+                break;
+        }
+    }
+
+    /**
+     * Archives a single file if accepted by the matcher.
+     *
+     * @param file the file
+     * @param attributes the file's basic attributes
+     */
+    @Override
+    public FileVisitResult visitFile(final Path file, final BasicFileAttributes attributes) {
+        if (fileMatcher.matches(file)) {
+            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.add(file, attributes, false);
+            }
+        }
+        return FileVisitResult.CONTINUE;
+    }
+
+    /**
+     * 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}, then this method ensures that at least one archive
+     * remains even if that archive is empty.
+     *
+     * @param skipIfEmpty value of {@link AbstractJarMojo#skipIfEmpty}
+     */
+    public void prune(boolean skipIfEmpty) {
+        boolean isModuleHierarchy = !moduleHierarchy.isEmpty();
+        moduleHierarchy.values().forEach((archive) -> archive.prune(skipIfEmpty));
+        moduleHierarchy.values().removeIf(Archive::isEmpty);
+        packageHierarchy.prune(isModuleHierarchy || skipIfEmpty);
+    }
+
+    /**
+     * Moves, copies or ignores orphan files.
+     * An orphan file is a file which is not in any module when module hierarchy is used.
+     * For example, some Maven plugins may create files such as {@code META-INF/LICENSE},
+     * {@code META-INF/NOTICE} or {@code META-INF/DEPENDENCIES}. These files are not in
+     * the correct directory (they should be in a {@code "<module>/META-INF"} directory)
+     * because the plugin may not be aware of module hierarchy.
+     *
+     * <p>A possible strategy could be to copy the {@code LICENSE} and {@code NOTICE} files
+     * in each module, and ignore the {@code DEPENDENCIES} file because its content is not
+     * correct for a module. For now, we just log a warning an ignore.</p>
+     *
+     * <h4>Prerequisites</h4>
+     * The {@link #prune(boolean)} method should have been invoked once before to invoke this method.
+     *
+     * @return if this method ignored some files, the root directory of those files
+     */
+    Path handleOrphanFiles() {
+        if (moduleHierarchy.isEmpty() || packageHierarchy.isEmpty()) {
+            // Classpath project or module-project without orphan files. Nothing to do.
+            return null;
+        }
+        // TODO: we may want to copy LICENSE and NOTICE files here.
+        return packageHierarchy.discardAllFiles();
+    }
+
+    /**
+     * Writes all <abbr>JAR</abbr> files.
+     * If the project is multi-module, then this method returns the path to the generated parent <abbr>POM</abbr> file.
+     *
+     * <h4>Prerequisites</h4>
+     * The {@link #prune(boolean)} method should have been invoked once before to invoke this method.
+     *
+     * @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
+     * @throws IOException if an error occurred while reading or writing a manifest file
+     */
+    Path writeAllJARs(final ToolExecutor executor) throws IOException {
+        for (Archive module : moduleHierarchy.values()) {
+            executor.writeSingleJAR(this, module);
+        }
+        if (executor.pomDerivation != null) {
+            return executor.pomDerivation.writeParentPOM(packageHierarchy);
+        }
+        if (!packageHierarchy.isEmpty()) {
+            executor.writeSingleJAR(this, packageHierarchy);
+        }
+        return null;
+    }
+
+    /**
+     * {@return the paths to all root directories of modules in a module hierarchy}
+     * They are usually {@code target/classes/<module>} directories, but could also
+     * be sub-directories in the {@code META-INF/modular-versions/<n>/} directory.
+     * If the project does not use module hierarchy, then this method returns an empty list.
+     *
+     * <h4>Ignored package hierarchy</h4>
+     * Note that an empty list does not necessarily means that the <abbr>JAR</abbr> is not modular,

Review Comment:
   Done



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3921916116


##########
src/main/java/org/apache/maven/plugins/jar/Archive.java:
##########
@@ -0,0 +1,655 @@
+/*
+ * 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.jar;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.TreeMap;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.Type;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.MojoException;
+
+/**
+ * Files or root directories to archive for a single module.
+ * A single instance of {@code Archive} can contain many directories for different target Java releases.
+ * Many instances of {@code Archive} can exist when archiving a multi-modules project.
+ */
+final class Archive {
+    /**
+     * Path to the <abbr>POM</abbr> file generated for this archive, or {@code null} if none.
+     * This is non-null only if module source hierarchy is used, in which case the dependencies
+     * declared in this file are the intersection of the project dependencies and the content of
+     * the {@code module-info.class} file.
+     */
+    @Nullable
+    Path pomFile;
+
+    /**
+     * The <var>JAR</var> file to create. Can be an existing file,
+     * in which case the file creation can be skipped if the file is still up-to-date.
+     */
+    @Nonnull
+    final Path jarFile;
+
+    /**
+     * A helper class for checking whether an existing <abbr>JAR</abbr> file is still up-to-date.
+     * This is null if there is no existing JAR file, or if we determined that the file is outdated.
+     */
+    private TimestampCheck existingJAR;
+
+    /**
+     * Name of the module being archived when the project is using module hierarchy.
+     * This is {@code null} if the project is using package hierarchy, either because it is a classical
+     * class-path project or because it is a single module compiled without using the module hierarchy.
+     * When using module source hierarchy, {@code javac} guarantees that the module name in the output
+     * directory is the name of the parent directory of {@code module-info.class}.
+     */
+    @Nullable
+    final String moduleName;
+
+    /**
+     * Path to {@code META-INF/MANIFEST.MF}, or {@code null} if none.
+     * If non-null, this value will be given to the {@code --manifest} option.
+     * The use of this option is preferable to adding {@code MANIFEST.MF} as an ordinary file.
+     *
+     * @see #setManifest(Path, boolean)
+     * @see #mergeManifest(Path, Manifest)
+     */
+    @Nullable
+    private Path manifest;
+
+    /**
+     * The Maven generated {@code pom.xml} and {@code pom.properties} files, or {@code null} if none.
+     * This first item must be the base directory where the files are located.
+     */
+    @Nullable
+    List<Path> mavenFiles;
+
+    /**
+     * Fully-qualified name of the main class, or {@code null} if none.
+     * This is the value to provide to the {@code --main-class} option.
+     */
+    private String mainClass;
+
+    /**
+     * Files or root directories to store in the <abbr>JAR</abbr> file for each target Java release
+     * other than the base release. Keys are the target Java release with {@code null} for the base
+     * release.
+     */
+    @Nonnull
+    private final NavigableMap<Runtime.Version, FileSet> filesetForRelease;
+
+    /**
+     * Files or root directories to archive for a single target Java release of a single module.
+     * The {@link Archive} enclosing must contain at least one instance of {@code FileSet} for
+     * the base release, and an arbitrary amount of other instances for other target releases.
+     */
+    final class FileSet {
+        /**
+         * The root directory of all files or directories to archive.
+         * This is the value to pass to the {@code -C} tool option.
+         */
+        @Nonnull
+        final Path directory;
+
+        /**
+         * The files or directories to include in the <var>JAR</var> file.
+         * Can be absolute paths or paths relative to {@link #directory}.
+         * It usually contains only the files or directories directly in
+         * the root {@linkplain #directory}, not in sub-directories.
+         */
+        @Nonnull
+        final List<Path> files;
+
+        /**
+         * Creates an initially empty set of files or directories for a specific target Java release.
+         *
+         * @param directory the base directory of the files or directories to archive
+         */
+        private FileSet(Path directory) {
+            this.directory = directory;
+            this.files = new ArrayList<>();
+        }
+
+        /**
+         * 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.
+         * The caller should use that common directory for logging a warning message.
+         *
+         * @param base base directory found by previous invocations of this method, or {@code null} if none
+         * @return common directory of discarded files
+         */
+        private Path discardAllFiles(Path base) {
+            for (Path file : files) {
+                if (base == null) {
+                    base = file.getParent();
+                } else {
+                    while (!file.startsWith(base)) {
+                        base = base.getParent();
+                        if (base == null) {
+                            break;
+                        }
+                    }
+                }
+            }
+            files.clear();
+            return base;
+        }
+
+        /**
+         * Adds the given path to the list of files or directories to archive.
+         * If the given path is a directory, then all children will be included.
+         * Children to exclude, if any, should be managed by {@link ExcludedFiles}.
+         *
+         * @param item a file or directory to archive
+         * @param attributes the file's basic attributes
+         * @param isDirectory whether the file is a directory
+         */
+        void add(Path item, BasicFileAttributes attributes, boolean isDirectory) {
+            TimestampCheck tc = existingJAR;
+            if (tc != null && tc.isUpdated(item, attributes, isDirectory)) {
+                existingJAR = null; // Signal that the existing file is outdated.
+            }
+            files.add(item);
+        }
+
+        /**
+         * Adds to the given list the arguments to provide to the "jar" tool for this version.
+         * The elements added to the list will be instances of {@link String} or {@link Path}.
+         *
+         * <h4>Note about the {@code -C} option</h4>
+         * This method repeats the {@code -C} option before each file.
+         * Our tests suggest that the first file after the directory specified by the {@code -C} option must
+         * be relative to that directory and all files after the first one must be prefixed by the directory
+         * which was specified in the {@code -C} option. This behavior is not very intuitive and replying on
+         * it can be fragile. Furthermore, it seems that the relativized file needs to be the shortest one,
+         * otherwise the {@code jar} tool rejects files after the first one with "names do not match".
+         * Which file is first depends on the unspecified directory-iteration order.
+         * Repeating the {@code -C} option for each file seems safer.
+         *
+         * @param addTo the list to add the arguments as {@link String} or {@link Path} instances to
+         * @param version the target Java release, or {@code null} for the base version of the <abbr>JAR</abbr> file
+         * @throws IllegalArgumentException if a path cannot be made relative to the base directory
+         */
+        private void arguments(List<Object> addTo, Runtime.Version version) {
+            if (files.isEmpty()) {
+                return;
+            }
+            if (version != null) {
+                addTo.add("--release");
+                addTo.add(version);
+            }
+            Path previous = null;
+            for (Path file : files) {
+                if (previous != null && file.startsWith(previous)) {
+                    // Already added a parent directory.
+                    continue;
+                }
+                previous = file;
+                file = directory.relativize(file);
+                if (file.getNameCount() <= 1 && file.toString().isEmpty()) {
+                    /*
+                     * The `-C` directory itself (e.g. a "META-INF/versions/<n>" directory added as a whole).
+                     * An empty file argument is invalid for the `jar` tool (some implementations reject it,
+                     * others silently misbehave), so archive the whole directory content with ".".
+                     */
+                    file = Path.of(".");
+                }
+                addTo.add("-C");
+                addTo.add(directory);
+                addTo.add(file);
+            }
+        }
+
+        /**
+         * {@return a string representation for debugging purposes}
+         */
+        @Override
+        public String toString() {
+            return getClass().getSimpleName() + '[' + directory.getFileName() + ": " + files.size() + " files]";
+        }
+    }
+
+    /**
+     * Creates an initially empty set of files or directories.
+     *
+     * @param jarFile path to the <abbr>JAR</abbr> file to create
+     * @param moduleName the module name if using module hierarchy, or {@code null} if using package hierarchy
+     * @param version the target Java release, or {@code null} for the base version
+     * @param directory the directory of the classes targeting the base Java release
+     * @param forceCreation whether to force a new <abbr>JAR</abbr> file even if the content seems unchanged
+     * @param logger where to send a warning if an error occurred while checking an existing <abbr>JAR</abbr> file
+     */
+    @SuppressWarnings("checkstyle:NeedBraces")
+    Archive(
+            final Path jarFile,
+            final String moduleName,
+            final Runtime.Version version,
+            final Path directory,
+            final boolean forceCreation,
+            final Log logger) {
+        this.jarFile = jarFile;
+        this.moduleName = moduleName;
+        filesetForRelease = new TreeMap<>((v1, v2) -> {
+            if (v1 == v2) return 0;
+            if (v1 == null) return -1;
+            if (v2 == null) return +1;
+            return v1.compareTo(v2);
+        });
+        filesetForRelease.put(version, new FileSet(directory));
+        if (!forceCreation && Files.isRegularFile(jarFile)) {
+            try {
+                existingJAR = new TimestampCheck(jarFile, directory, logger);
+            } catch (IOException e) {
+                // Ignore, we will regenerate the JAR file.
+                logger.warn(e);
+            }
+        }
+    }
+
+    /**
+     * {@return the files or directories to store in the <abbr>JAR</abbr> file for targeting the base Java release}
+     *
+     * @throws NoSuchElementException should not happen unless {@link #prune(boolean)} has been invoked
+     */
+    FileSet baseRelease() {
+        Map.Entry<Runtime.Version, FileSet> entry = filesetForRelease.firstEntry();
+        String message = null;
+        if (entry != null) {
+            Runtime.Version version = entry.getKey();
+            if (version == null) {
+                return entry.getValue();
+            }
+            message = "Expected base version but found version " + version;
+        }
+        throw new NoSuchElementException(message);
+    }
+
+    /**
+     * Returns the {@code module-info.class} files. Conceptually, there is at most once such file per module.
+     * However, more than one file can exist if additional files are provided for additional Java releases.
+     * This method returns only the files that exist.
+     *
+     * @return all {@code module-info.class} files found for all target Java releases
+     */
+    public List<Path> moduleInfoFiles() {
+        var files = new ArrayList<Path>();
+        filesetForRelease.values().forEach((release) -> {
+            Path file = release.directory.resolve(FileCollector.MODULE_DESCRIPTOR_FILE_NAME);
+            if (Files.isRegularFile(file)) {
+                files.add(file);
+            }
+        });
+        return files;
+    }
+
+    /**
+     * Discards all files in this archive, normally because those files are not in any module.
+     * This method returns a common parent directory for all the files that were discarded.
+     * The caller should use that common directory for logging a warning message.
+     *
+     * @return common directory of discarded files, or {@code null} if none
+     */
+    Path discardAllFiles() {
+        Path base = null;
+        for (FileSet release : filesetForRelease.values()) {
+            base = release.discardAllFiles(base);
+        }
+        filesetForRelease.clear();
+        return base;
+    }
+
+    /**
+     * Removes all empty file sets 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}, then this method ensures that at least one file set
+     * remains even if that file set is empty.
+     *
+     * @param skipIfEmpty value of {@link AbstractJarMojo#skipIfEmpty}
+     */
+    public void prune(final boolean skipIfEmpty) {
+        FileSet keep = (skipIfEmpty || isEmpty())
+                ? null
+                : filesetForRelease.firstEntry().getValue();
+        filesetForRelease.values().removeIf((fs) -> fs.files.isEmpty());
+        Iterator<Map.Entry<Runtime.Version, FileSet>> it =
+                filesetForRelease.entrySet().iterator();
+        if (it.hasNext()) {
+            Map.Entry<Runtime.Version, FileSet> first = it.next();
+            if (first.getKey() == null) {
+                return; // Already contains an entry for the base version, nothing to do.
+            }
+            keep = first.getValue();
+            it.remove();
+        }
+        if (keep != null) {
+            filesetForRelease.put(null, keep);
+        }
+    }
+
+    /**
+     * {@return whether this archive has nothing to archive}
+     * This method can return {@code false} even when there is zero file to archive.
+     * It can happen if {@link AbstractJarMojo#skipIfEmpty} is {@code false}. In such case, the
+     * "empty" <abbr>JAR</abbr> file will still contain at {@code META-INF/MANIFEST.MF} file.
+     *
+     * <h4>Prerequisites</h4>
+     * The {@link #prune(boolean)} method should be invoked before this method for accurate result.
+     */
+    public boolean isEmpty() {
+        return filesetForRelease.isEmpty();
+    }
+
+    /**
+     * Checks whether the <abbr>JAR</abbr> file already exists and can be reused.
+     * This method verifies that the <abbr>JAR</abbr> file contains all the files to archive,
+     * contains no extra file, and no file to archive is newer than the <abbr>JAR</abbr> file.
+     *
+     * <p>This method can be invoked only once.
+     * If invoked more often, it returns {@code false} on all subsequent invocations.</p>
+     *
+     * @return whether the <abbr>JAR</abbr> file already exists and can be reused
+     */
+    public boolean isUpToDateJAR() {
+        final TimestampCheck tc = existingJAR;

Review Comment:
   The `TimestampCheck` class contains the path to a JAR file (hence the `existingJAR` field name) together with a list of the entry that it contains, a list of entries that are expected, and timestamp for checking whether entries are up to date.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "seregamorph (via GitHub)" <gi...@apache.org>.
seregamorph commented on PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#issuecomment-5343943459

   1. @ascheman thanks, I've rechecked your PR and I'd like to confirm - it fixes the problem with directories, now the spring application is starting 👍 
   2. the good news is that JARs are reproducible, at least on my machine/os/jvm version, and it's binary reproducible.
   There was a comment regarding "semantically reproducible" instead of "binary reproducible" - that's not acceptable, at least because it breaks Docker layered file system optimization. It can be lenient for the timestamp of files, but if the JAR file content is different (like different order or timestamp), it will not work. At scale that's a significant factor.
   3. what I've noticed is that MANIFEST.MF are now having two entries
   ```
   Manifest-Version: 1.0
   Created-By: 25.0.3 (Amazon.com Inc.)
   ```
   while the original MANIFEST had only `Manifest-Version: 1.0` @desruisseaux , please recheck this regression.
   The configuration is
   ```xml
   <plugin>
       <groupId>org.apache.maven.plugins</groupId>
       <artifactId>maven-jar-plugin</artifactId>
       <configuration>
           <archive>
               <addMavenDescriptor>false</addMavenDescriptor>
               <manifest>
                   <addDefaultEntries>false</addDefaultEntries>
               </manifest>
           </archive>
       </configuration>
   </plugin>
   ```


-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "laeubi (via GitHub)" <gi...@apache.org>.
laeubi commented on PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#issuecomment-5337763539

   > > If that proves to be true and we can't find a workaround, that's a blocker. Reproducible builds are the more important feature.
   > 
   > I disagree that it is the most important feature. I think that they real feature you are asking for is a way to verify the integrity of a JAR (no malicious code). This is **semantic** reproducible builds, and something that we could provide.
   
   Tycho has such comparison (and can even e.g. detect different order in manifest files)
   
   - https://github.com/eclipse-tycho/tycho/tree/main/tycho-artifactcomparator
   
   but it is more used to compare if a version increment is needed to prevent deploying an artifact that (semantically) only differs in its promoted version.


-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3792756072


##########
src/main/java/org/apache/maven/plugins/jar/AbstractJarMojo.java:
##########
@@ -207,167 +205,199 @@ protected final Log getLog() {
     protected abstract String getType();
 
     /**
-     * Returns the JAR file to generate, based on an optional classifier.
+     * {@return the scope of dependencies}
+     * It should be {@link PathScope#MAIN_COMPILE} or {@link PathScope#TEST_COMPILE}.
+     * Note that we use compile scope rather than runtime scope because dependencies
+     * cannot appear in {@code requires} statement if they didn't had compile scope.
+     */
+    protected abstract PathScope getDependencyScope();
+
+    /**
+     * {@return the JAR tool to use for archiving the code}
      *
-     * @param basedir the output directory
-     * @param resultFinalName the name of the JAR file
-     * @param classifier an optional classifier
-     * @return the file to generate
+     * @throws MojoException if no JAR tool was found
+     *
+     * @since 4.0.0-beta-2
      */
-    protected Path getJarFile(Path basedir, String resultFinalName, String classifier) {
-        Objects.requireNonNull(basedir, "basedir is not allowed to be null");
-        Objects.requireNonNull(resultFinalName, "finalName is not allowed to be null");
-        String fileName = resultFinalName + (hasClassifier(classifier) ? '-' + classifier : "") + ".jar";
-        return basedir.resolve(fileName);
+    protected ToolProvider getJarTool() throws MojoException {
+        return ToolProvider.findFirst(toolId).orElseThrow(() -> new MojoException("No such \"" + toolId + "\" tool."));
     }
 
     /**
-     * Generates the JAR.
+     * Returns whether the specified Java version is supported.
      *
-     * @return the path to the created archive file
-     * @throws MojoException in case of an error
+     * @param release name of an {@link SourceVersion} enumeration constant
+     * @return whether the current environment support that version
      */
-    public Path createArchive() throws MojoException {
-        Path basedir = outputDirectory != null
-                ? outputDirectory
-                : Path.of(project.getBuild().getDirectory());
-        String resultFinalName =
-                finalName != null ? finalName : project.getBuild().getFinalName();
-        Path jarFile = getJarFile(basedir, resultFinalName, getClassifier());
-
-        FileSetManager fileSetManager = new FileSetManager();
-        FileSet jarContentFileSet = new FileSet();
-        jarContentFileSet.setDirectory(getClassesDirectory().toAbsolutePath().toString());
-        jarContentFileSet.setIncludes(Arrays.asList(getIncludes()));
-        jarContentFileSet.setExcludes(Arrays.asList(getExcludes()));
-
-        String[] includedFiles = fileSetManager.getIncludedFiles(jarContentFileSet);
-
-        if (detectMultiReleaseJar
-                && Arrays.stream(includedFiles)
-                        .anyMatch(
-                                p -> p.startsWith("META-INF" + File.separatorChar + "versions" + File.separatorChar))) {
-            getLog().debug("Adding 'Multi-Release: true' manifest entry.");
-            archive.addManifestEntry(Attributes.Name.MULTI_RELEASE.toString(), "true");
+    private static boolean isSupported(String release) {

Review Comment:
   If we are talking about the comment saying _"This property is supported only with Java Development Kit (JDK) version 19 or later"_, [the commit](https://github.com/apache/maven-jar-plugin/pull/508/changes/16ff48a99f4f078f68caf23a76ec66a9c85640f9) shows it just before the `outputTimestamp` field, as expected.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#issuecomment-5353734439

   > I wanted to note here that (binary) reproducible builds are not guaranteeing anyways between different JDK versions and vendors as they could provide different byte codes.
   
   I agree, and this is one reason why I disagree with the importance given to strict (as opposed to semantically) reproducible builds. I think that it can even deserve the real goal, which is security. If some Java tools produce vulnerable code (e.g., [Javadoc HTML frame injection vulnerability](https://www.kb.cert.org/vuls/id/225657) in 2013), it is difficult to know if a JAR file has been produced by patched tools if we don't have a useful `Created-By` entry in the `MANIFEST.MF` file. But we are throwing away this information in the name of strict reproducible builds.
   
   Regarding the split of metadata generation (`MANIFEST.MF` and Maven files) and packaging in two different phases, I agree with that. But I propose to go step by step:
   
   1. Fix the issue raised in above comments (missing directory entries, `Created-By` attribute).
   2. Get this pull request merged.
   3. In a separated pull request, copy (in modified form) in this plugin the Maven Archiver code which is still used. This is the code that generates the `MANIFEST.MF` attributes.
   4. Refactor in two separated goals.
   
   Regarding the JAR file validation, this is one of the reasons for this migration to the `jar` tool but not the only one. There is also additional options such as `--hash-modules`. The support of this option is not included in this pull request because it will be a new feature, but it would be the topic of a future pull request.


-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3949069712


##########
src/main/java/org/apache/maven/plugins/jar/ExcludedFiles.java:
##########
@@ -0,0 +1,146 @@
+/*
+ * 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.jar;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardCopyOption;
+import java.util.List;
+
+/**
+ * A list of files to temporarily move outside the directory to package in a <abbr>JAR</abbr> archive.
+ * This class is needed when the {@link AbstractJarMojo} configuration has include or exclude filters.
+ * Excluded files are temporarily moved outside the directory to archive.
+ * We move these files for making possible to specify the whole directory to the {@code jar} tool.

Review Comment:
   Done as suggested.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "laeubi (via GitHub)" <gi...@apache.org>.
laeubi commented on PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#issuecomment-5313739674

   > Preparing a `MANIFEST.MF` is the only functionality of `MavenArchiver` that the new implementation is still using. We could bring that functionality in the plugin, which would remove the dependency to Archiver. But I keep that for a separated discussion later.
   
   Btw this intermingling was always a problem. I therefore created an issue here, that suggest to split it into two phases:
   
   - https://github.com/apache/maven-jar-plugin/issues/586
   
   If we have this "breaking" change here it seems a perfect time to consider this as well maybe.


-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "hboutemy (via GitHub)" <gi...@apache.org>.
hboutemy commented on PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#issuecomment-5347824551

   I just tested building a few simple projects with misc JDKs and this PR:
   ```
   mvn -V -e -Dversion.maven-jar-plugin=4.0.0-beta-2-SNAPSHOT -DskipTests clean package artifact:3.6.1:describe-build-output ; unzip -p target/*-SNAPSHOT.jar META-INF/MANIFEST.MF
   ```
   
   first, I can see the the `META-INF/MANIFEST.MF` file remains as usual: great
   
   from my test, with JDK 19+, result is locally reproducible: I always get the same output on the same laptop
   I did not yet try to compare builds on different machines, I'll check later
   
   with JDK 17 and 18, not reproducible: no problem with order of files, but with timestamp
   and also a timestamp is injected in pom.properties
   
   To me, avoid the issue with pom.properties should be easy
   and postprocessing jar file to set timestamp should not be hard: like moditect for example https://github.com/moditect/moditect/blob/41784cb65f9a564012212ba94307ad98455d789d/core/src/main/java/org/moditect/commands/AddModuleInfo.java#L115


-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3921727642


##########
src/main/java/org/apache/maven/plugins/jar/Archive.java:
##########
@@ -0,0 +1,655 @@
+/*
+ * 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.jar;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.TreeMap;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.Type;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.MojoException;
+
+/**
+ * Files or root directories to archive for a single module.
+ * A single instance of {@code Archive} can contain many directories for different target Java releases.
+ * Many instances of {@code Archive} can exist when archiving a multi-modules project.
+ */
+final class Archive {
+    /**
+     * Path to the <abbr>POM</abbr> file generated for this archive, or {@code null} if none.
+     * This is non-null only if module source hierarchy is used, in which case the dependencies
+     * declared in this file are the intersection of the project dependencies and the content of
+     * the {@code module-info.class} file.
+     */
+    @Nullable
+    Path pomFile;
+
+    /**
+     * The <var>JAR</var> file to create. Can be an existing file,
+     * in which case the file creation can be skipped if the file is still up-to-date.
+     */
+    @Nonnull
+    final Path jarFile;
+
+    /**
+     * A helper class for checking whether an existing <abbr>JAR</abbr> file is still up-to-date.
+     * This is null if there is no existing JAR file, or if we determined that the file is outdated.
+     */
+    private TimestampCheck existingJAR;
+
+    /**
+     * Name of the module being archived when the project is using module hierarchy.
+     * This is {@code null} if the project is using package hierarchy, either because it is a classical
+     * class-path project or because it is a single module compiled without using the module hierarchy.
+     * When using module source hierarchy, {@code javac} guarantees that the module name in the output
+     * directory is the name of the parent directory of {@code module-info.class}.
+     */
+    @Nullable
+    final String moduleName;
+
+    /**
+     * Path to {@code META-INF/MANIFEST.MF}, or {@code null} if none.
+     * If non-null, this value will be given to the {@code --manifest} option.
+     * The use of this option is preferable to adding {@code MANIFEST.MF} as an ordinary file.
+     *
+     * @see #setManifest(Path, boolean)
+     * @see #mergeManifest(Path, Manifest)
+     */
+    @Nullable
+    private Path manifest;
+
+    /**
+     * The Maven generated {@code pom.xml} and {@code pom.properties} files, or {@code null} if none.
+     * This first item must be the base directory where the files are located.
+     */
+    @Nullable
+    List<Path> mavenFiles;
+
+    /**
+     * Fully-qualified name of the main class, or {@code null} if none.
+     * This is the value to provide to the {@code --main-class} option.
+     */
+    private String mainClass;
+
+    /**
+     * Files or root directories to store in the <abbr>JAR</abbr> file for each target Java release
+     * other than the base release. Keys are the target Java release with {@code null} for the base
+     * release.
+     */
+    @Nonnull
+    private final NavigableMap<Runtime.Version, FileSet> filesetForRelease;
+
+    /**
+     * Files or root directories to archive for a single target Java release of a single module.
+     * The {@link Archive} enclosing must contain at least one instance of {@code FileSet} for
+     * the base release, and an arbitrary amount of other instances for other target releases.
+     */
+    final class FileSet {
+        /**
+         * The root directory of all files or directories to archive.
+         * This is the value to pass to the {@code -C} tool option.
+         */
+        @Nonnull
+        final Path directory;
+
+        /**
+         * The files or directories to include in the <var>JAR</var> file.
+         * Can be absolute paths or paths relative to {@link #directory}.
+         * It usually contains only the files or directories directly in
+         * the root {@linkplain #directory}, not in sub-directories.
+         */
+        @Nonnull
+        final List<Path> files;
+
+        /**
+         * Creates an initially empty set of files or directories for a specific target Java release.
+         *
+         * @param directory the base directory of the files or directories to archive
+         */
+        private FileSet(Path directory) {
+            this.directory = directory;
+            this.files = new ArrayList<>();
+        }
+
+        /**
+         * 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.
+         * The caller should use that common directory for logging a warning message.
+         *
+         * @param base base directory found by previous invocations of this method, or {@code null} if none
+         * @return common directory of discarded files
+         */
+        private Path discardAllFiles(Path base) {
+            for (Path file : files) {
+                if (base == null) {
+                    base = file.getParent();
+                } else {
+                    while (!file.startsWith(base)) {
+                        base = base.getParent();
+                        if (base == null) {
+                            break;
+                        }
+                    }
+                }
+            }
+            files.clear();
+            return base;
+        }
+
+        /**
+         * Adds the given path to the list of files or directories to archive.
+         * If the given path is a directory, then all children will be included.
+         * Children to exclude, if any, should be managed by {@link ExcludedFiles}.
+         *
+         * @param item a file or directory to archive
+         * @param attributes the file's basic attributes
+         * @param isDirectory whether the file is a directory
+         */
+        void add(Path item, BasicFileAttributes attributes, boolean isDirectory) {
+            TimestampCheck tc = existingJAR;

Review Comment:
   Done (removed the variable completely).



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3923542812


##########
src/main/java/org/apache/maven/plugins/jar/FileCollector.java:
##########
@@ -0,0 +1,541 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.PathMatcher;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Deque;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.services.PathMatcherFactory;
+
+/**
+ * Dispatch the files from the output directory into the <abbr>JAR</abbr> files to create.
+ * Instead of just archiving as-is the content of the output directory, this class separates
+ * the following subdirectories to the options listed below:
+ *
+ * <ul>
+ *   <li>The {@code META-INF/MANIFEST.MF} file will be given to the {@code --manifest} option.</li>
+ *   <li>Files in the following directories will be given to the {@code --release} option:
+ *     <ul>
+ *       <li>{@code META-INF/versions/}</li>
+ *       <li>{@code META-INF/versions-modular/<module>/}</li>
+ *       <li>{@code <module>/META-INF/versions/}</li>
+ *     </ul>
+ *   </li>
+ * </ul>
+ *
+ * The reason for using the options is that they allow the {@code jar} tool to perform additional verifications.
+ * For example, when using the {@code --release} option, {@code jar} verifies the <abbr>API</abbr> compatibility.
+ */
+final class FileCollector extends SimpleFileVisitor<Path> {
+    /**
+     * The file to check for deciding whether the <abbr>JAR</abbr> is modular.
+     */
+    static final String MODULE_DESCRIPTOR_FILE_NAME = "module-info.class";
+
+    /**
+     * The {@value} directory.
+     * This is part of <abbr>JAR</abbr> file specification.
+     */
+    private static final String VERSIONS = "versions";
+
+    /**
+     * The {@value} directory.
+     * This is Maven-specific.
+     */
+    private static final String VERSIONS_MODULAR = "versions-modular";
+
+    /**
+     * Context (logger, configuration) in which the <abbr>JAR</abbr> file are created.
+     */
+    private final ToolExecutor context;
+
+    /**
+     * Whether to detect multi-release <abbr>JAR</abbr> files.
+     * The default value is {@code true}.
+     *
+     * @see AbstractJarMojo#detectMultiReleaseJar
+     */
+    private final boolean detectMultiReleaseJar;
+
+    /**
+     * The root directory to traverse. It will be used for temporarily moving excluded files.
+     */
+    private final Path rootDirectory;
+
+    /**
+     * Combination of includes and excludes path matcher applied on files.
+     */
+    @Nonnull
+    private final PathMatcher fileMatcher;
+
+    /**
+     * Combination of includes and excludes path matcher applied on directories.
+     */
+    @Nonnull
+    private final PathMatcher directoryMatcher;
+
+    /**
+     * Files to exclude. These files will be moved to a temporary location
+     * for allowing {@link ToolExecutor} to specify whole directories to the {@code jar} tool.
+     * Specifying whole directories is preferable to enumerating the files because otherwise,
+     * the generated <abbr>JAR</abbr> file contains only entries for the files and is missing
+     * entries for the directories.
+     *
+     * <p>This field is {@code null} if it is not possible to have any excluded file
+     * (because there is no include/exclude filters).</p>
+     */
+    @Nullable
+    private final List<Path> excludedFiles;
+
+    /**
+     * Directories to exclude. This field serves the same purpose as {@link #excludedFiles},
+     * but where the sources a directories instead of files.
+     */
+    @Nullable
+    private final List<Path> excludedDirectories;
+
+    /**
+     * Files found in the output directory when package hierarchy is used.
+     * At most one of {@code packageHierarchy} and {@link #moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Archive packageHierarchy;
+
+    /**
+     * Files found in the output directory when module hierarchy is used. Keys are module names.
+     * At most one of {@link #packageHierarchy} and {@code moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Map<String, Archive> moduleHierarchy;
+
+    /**
+     * The current module being archived. This field is updated every times that {@code FileCollector}
+     * visits a new module directory.
+     */
+    @Nonnull
+    private Archive currentModule;
+
+    /**
+     * The module and target Java release currently being scanned. This field is updated every times that
+     * {@code FileCollector} visits a new module directory or in a new target Java release for a given module.
+     */
+    @Nonnull
+    private Archive.FileSet currentFilesToArchive;
+
+    /**
+     * The current target Java release, or {@code null} if none.
+     */
+    @Nullable
+    private Runtime.Version currentTargetVersion;
+
+    /**
+     * Identification of the kinds of directories being traversed.
+     * The length of this list is the depth in the directory hierarchy.
+     * The last element identifies the type of the current directory.
+     */
+    private final Deque<DirectoryRole> directoryRoles;
+
+    /**
+     * Whether to check when a file is the {@code MANIFEST.MF} file.
+     * This is allowed only when scanning the content of a {@code META-INF} directory.
+     */
+    private boolean checkForManifest;
+
+    /**
+     * Creates a new file collector.
+     *
+     * @param mojo the <abbr>MOJO</abbr> from which to get the configuration
+     * @param context context (logger, configuration) in which the <abbr>JAR</abbr> file are created
+     * @param directory the base directory of the files to archive
+     */
+    FileCollector(AbstractJarMojo mojo, ToolExecutor context, Path directory, PathMatcherFactory matcherFactory) {
+        this.context = context;
+        rootDirectory = directory;
+        detectMultiReleaseJar = mojo.detectMultiReleaseJar;
+        directoryRoles = new ArrayDeque<>();
+        fileMatcher = matcherFactory.createPathMatcher(directory, mojo.getIncludes(), mojo.getExcludes(), false);
+        directoryMatcher = matcherFactory.deriveDirectoryMatcher(fileMatcher);
+        if (matcherFactory.isIncludesAll(fileMatcher) && matcherFactory.isIncludesAll(directoryMatcher)) {
+            excludedFiles = null;
+            excludedDirectories = null;
+        } else {
+            excludedFiles = new ArrayList<>();
+            excludedDirectories = new ArrayList<>();
+        }
+        packageHierarchy = context.newArchive(null, null, directory);
+        moduleHierarchy = new LinkedHashMap<>();
+        resetToPackageHierarchy();
+    }
+
+    /**
+     * Resets this {@code FileCollector} to the state where a package hierarchy is presumed.
+     */
+    private void resetToPackageHierarchy() {
+        currentModule = packageHierarchy;
+        currentFilesToArchive = currentModule.baseRelease();
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a module.
+     * For an output generated by {@code javac} from a module source hierarchy,
+     * the directory name is guaranteed to be the module name.
+     *
+     * @param directory a {@code "<module>"} or {@code "META-INF/versions-modular/<module>"} directory
+     */
+    private void preVisitVersionDirectory(final Path directory) {
+        String moduleName = directory.getFileName().toString();
+        currentModule = moduleHierarchy.computeIfAbsent(
+                moduleName, (name) -> context.newArchive(name, currentTargetVersion, directory));
+        currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a target Java version.
+     * The {@code useDirectly} argument tells whether the content of this directory will be specified directly
+     * as the content to add in the <abbr>JAR</abbr> file. This argument should be {@code false} when there is
+     * another directory level (the module names) to process before to add content.
+     *
+     * @param directory a {@code "META-INF/versions/<n>"} or {@code "META-INF/versions-modular/<n>"} directory
+     * @param useDirectly whether the directory is {@code "META-INF/versions/<n>"}
+     * @return whether to skip the directory because of invalid version number
+     */
+    private boolean preVisitVersionDirectory(final Path directory, final boolean useDirectly) {
+        try {
+            currentTargetVersion = Runtime.Version.parse(directory.getFileName().toString());
+        } catch (IllegalArgumentException e) {
+            context.warnInvalidVersion(directory, e);
+            return true;
+        }
+        if (useDirectly) {
+            currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+        }
+        return false;
+    }
+
+    /**
+     * Determines if the given directory should be scanned for files to archive.
+     * This method may also update {@link #currentFilesToArchive} if it detects
+     * that we are visiting the content of a new module or a new target Java release.
+     *
+     * @param directory the directory which will be traversed
+     * @param attributes the directory's basic attributes
+     */
+    @Override
+    @SuppressWarnings("checkstyle:MissingSwitchDefault")
+    public FileVisitResult preVisitDirectory(final Path directory, final BasicFileAttributes attributes)
+            throws IOException {
+        DirectoryRole role;
+        if (directoryRoles.isEmpty()) {
+            role = DirectoryRole.ROOT;
+        } else {
+            if (!directoryMatcher.matches(directory)) {
+                excludedDirectories.add(directory); // Cannot be null if excluded directories may exist.
+                return FileVisitResult.SKIP_SUBTREE;
+            }
+            checkForManifest = false;
+            role = directoryRoles.getLast();
+            switch (role) {
+                case ROOT:
+                    /*
+                     * Visiting any subdirectory of `target/classes` (or other directory to archive).
+                     * We need to handle `META-INF` and modules in a special way, and archive the rest.
+                     */
+                    if (directory.endsWith(MetadataFiles.META_INF)) {
+                        role = DirectoryRole.META_INF;
+                        checkForManifest = true;
+                    } else if (Files.isRegularFile(directory.resolve(MODULE_DESCRIPTOR_FILE_NAME))) {
+                        role = DirectoryRole.NAMED_MODULE;
+                        preVisitVersionDirectory(directory);
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case META_INF:
+                    /*
+                     * Visiting a subdirectory of `META-INF` or `<module>/META-INF`. We will need to handle
+                     * `MANIFEST.MF`, `versions` and `versions-modular` in a special way, and archive the rest.
+                     */
+                    if (detectMultiReleaseJar && directory.endsWith(VERSIONS)) {
+                        role = DirectoryRole.VERSIONS;
+                    } else if (directory.endsWith(VERSIONS_MODULAR)) {
+                        if (!detectMultiReleaseJar) {
+                            // Used asked for no multi-release JAR.
+                            return FileVisitResult.SKIP_SUBTREE;
+                        }
+                        role = DirectoryRole.VERSIONS_MODULAR;
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case VERSIONS:
+                    /*
+                     * Visiting a `META-INF/versions/<n>/` directory for a specific target Java release.
+                     * Can also be a `<module>/META-INF/versions/<n>/` directory, even if the latter is not
+                     * the layout generated by Maven Compiler Plugin.
+                     */
+                    if (preVisitVersionDirectory(directory, true)) {
+                        // An error occurred while parsing the version number.
+                        return FileVisitResult.SKIP_SUBTREE;
+                    }
+                    role = DirectoryRole.RESOURCES;
+                    break;
+
+                case VERSIONS_MODULAR:
+                    /*
+                     * Visiting a `META-INF/versions-modular/<n>/` directory for a specific target Java release.
+                     * That directory contains all modules for the version.
+                     */
+                    resetToPackageHierarchy(); // No module in particular yet.
+                    if (preVisitVersionDirectory(directory, false)) {
+                        // An error occurred while parsing the version number.
+                        return FileVisitResult.SKIP_SUBTREE;
+                    }
+                    role = DirectoryRole.MODULES;
+                    break;
+
+                case MODULES:
+                    /*
+                     * Visiting a `META-INF/versions-modular/<n>/<module>` directory.
+                     */
+                    preVisitVersionDirectory(directory);
+                    role = DirectoryRole.NAMED_MODULE;
+                    break;
+
+                case NAMED_MODULE:
+                    /*
+                     * Visiting a `<module>` or `META-INF/versions-modular/<n>/<module>` subdirectory.
+                     * A module could have its own `META-INF` subdirectory, so we need to check again.
+                     */
+                    if (directory.endsWith(MetadataFiles.META_INF)) {
+                        role = DirectoryRole.META_INF;
+                        checkForManifest = true;
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+            }
+        }
+        /*
+         * Do not move this condition inside the `switch` block because `role` may have been modified.
+         * The `role` value is now the role of `directory`, not the role of parent directory.
+         */
+        if (role == DirectoryRole.RESOURCES) {
+            currentFilesToArchive.add(directory, attributes, true);
+            if (excludedFiles == null) {
+                /*
+                 * Since we are skipping the whole directory, `postVisitDirectory(…)` will not be invoked.
+                 * We must reset `currentFilesToArchive` and `currentTargetVersion` by an explicit call.
+                 * This is important mostly after we added a whole `META-INF/versions/<n>` directory.
+                 * Otherwise, since directory iteration order is unspecified, base files visited afterwards
+                 * would be added to this version's file set instead of the base release.
+                 */
+                resetToParentDirectoryState();
+                return FileVisitResult.SKIP_SUBTREE;
+            }
+        }
+        directoryRoles.addLast(role);
+        return FileVisitResult.CONTINUE;
+    }
+
+    /**
+     * Updates the {@code FileCollector} state after we finished scanning the contents of a directory.
+     * The fields to update depend on which directory has been visited (module, version, etc.).
+     *
+     * @param directory the directory which has been traversed
+     * @param error the error that occurred while traversing the directory, or {@code null} if none
+     */
+    @Override
+    public FileVisitResult postVisitDirectory(final Path directory, final IOException error) throws IOException {
+        if (error != null) {
+            throw error;
+        }
+        switch (directoryRoles.removeLast()) {
+            case ROOT:
+                break;
+
+            case NAMED_MODULE:
+                // Exited the directory of a single module.
+                resetToPackageHierarchy();
+                break;
+
+            default:
+                resetToParentDirectoryState();
+                break;
+        }
+        return FileVisitResult.CONTINUE;
+    }
+
+    /**
+     * Updates {@code FileCollector} to a state suitable for the parent of the directory that we finished to scan.
+     * Contrary to {@link #postVisitDirectory(Path, IOException)}, this method expects the last element of
+     * {@link #directoryRoles} to describe the parent directory, not the directory that we finished to visit.
+     */
+    @SuppressWarnings("checkstyle:MissingSwitchDefault")
+    private void resetToParentDirectoryState() {
+        switch (directoryRoles.getLast()) {
+            case VERSIONS:
+            case VERSIONS_MODULAR:
+                // Exited the directory for one target Java release.
+                currentFilesToArchive = currentModule.baseRelease();
+                currentTargetVersion = null;
+                break;
+
+            case META_INF:
+                checkForManifest = true;
+                break;
+        }
+    }
+
+    /**
+     * Archives a single file if accepted by the matcher.
+     *
+     * @param file the file
+     * @param attributes the file's basic attributes
+     */
+    @Override
+    public FileVisitResult visitFile(final Path file, final BasicFileAttributes attributes) {
+        if (fileMatcher.matches(file)) {
+            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.add(file, attributes, false);
+            }
+        } else {
+            excludedFiles.add(file); // Cannot be null if excluded files may exist.
+        }
+        return FileVisitResult.CONTINUE;
+    }
+
+    /**
+     * 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}
+     */
+    public void prune(boolean skipIfEmpty) {
+        boolean isModuleHierarchy = !moduleHierarchy.isEmpty();
+        moduleHierarchy.values().forEach((archive) -> archive.prune(skipIfEmpty));
+        moduleHierarchy.values().removeIf(Archive::isEmpty);
+        packageHierarchy.prune(isModuleHierarchy || skipIfEmpty);
+    }
+
+    /**
+     * Moves, copies, or ignores orphan files.
+     * An orphan file is a file which is not in any module when module hierarchy is used.
+     * For example, some Maven plugins may create files such as {@code META-INF/LICENSE},
+     * {@code META-INF/NOTICE} or {@code META-INF/DEPENDENCIES}. These files are not in
+     * the correct directory (they should be in a {@code "<module>/META-INF"} directory)
+     * because the plugin may not be aware of module hierarchy.
+     *
+     * <p>A possible strategy could be to copy the {@code LICENSE} and {@code NOTICE} files
+     * in each module, and ignore the {@code DEPENDENCIES} file because its content is not
+     * correct for a module. For now, we just log a warning and ignore.</p>
+     *
+     * <h4>Prerequisites</h4>
+     * The {@link #prune(boolean)} method should have been invoked once before invoking this method.
+     *
+     * @return if this method ignored some files, the root directory of those files
+     */
+    Path handleOrphanFiles() {
+        if (moduleHierarchy.isEmpty() || packageHierarchy.isEmpty()) {
+            // Classpath project or module-project without orphan files. Nothing to do.
+            return null;
+        }
+        // TODO: we may want to copy LICENSE and NOTICE files here.
+        return packageHierarchy.discardAllFiles();
+    }
+
+    /**
+     * 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())) {
+            return null;
+        }
+        return new ExcludedFiles(rootDirectory, excludedFiles, excludedDirectories);
+    }
+
+    /**
+     * Writes all <abbr>JAR</abbr> files.
+     * If the project is multi-module, this method returns the path to the generated parent <abbr>POM</abbr> file.
+     *
+     * <h4>Prerequisites</h4>
+     * The {@link #prune(boolean)} method should have been invoked once before to invoke this method.
+     *
+     * @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
+     * @throws IOException if an error occurred while reading or writing a manifest file
+     */
+    Path writeAllJARs(final ToolExecutor executor) throws IOException {
+        try (ExcludedFiles exclusion = exclusion()) {
+            if (exclusion != null) {
+                exclusion.move();
+            }
+            for (Archive module : moduleHierarchy.values()) {
+                executor.writeSingleJAR(this, module);
+            }
+            if (executor.pomDerivation != null) {
+                return executor.pomDerivation.writeParentPOM(packageHierarchy);
+            }
+            if (!packageHierarchy.isEmpty()) {
+                executor.writeSingleJAR(this, packageHierarchy);
+            }
+        }
+        return null;
+    }
+
+    /**
+     * {@return the paths to all root directories of modules in a module hierarchy}
+     * They are usually {@code target/classes/<module>} directories, but could also
+     * be sub-directories in the {@code META-INF/modular-versions/<n>/} directory.
+     * If the project does not use module hierarchy, this method returns an empty list.
+     *
+     * <h4>Ignored package hierarchy</h4>
+     * Note that an empty list does not mean that the <abbr>JAR</abbr> is not modular,
+     * as a modular <abbr>JAR</abbr> can also be built from package hierarchy. But we intentionally
+     * ignore the latter case because this method is used for deriving <abbr>POM</abbr> files, and
+     * we do not perform such derivation for projects organized in the Maven 3 way.
+     *
+     * <h4>Prerequisites</h4>

Review Comment:
   Replaced `<h4>` by the same paragraph as other occurrences of this comment. For the reason why not invoking prune, same as previous comment.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3949359135


##########
src/test/java/org/apache/maven/plugins/jar/ArchiveTest.java:
##########
@@ -0,0 +1,257 @@
+/*
+ * 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.jar;
+
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Unit tests for {@link Archive}, focused on the two behaviours that are otherwise only
+ * exercised by integration tests whose outcome depends on the (unspecified) filesystem
+ * directory-iteration order, and therefore pass on some platforms while failing on others.
+ */
+class ArchiveTest {
+
+    /**
+     * Creates an {@code Archive} suitable for a unit test. {@code forceCreation = true} skips the
+     * existing-JAR timestamp check, so the (here {@code null}) logger is never dereferenced.
+     */
+    private static Archive archive(String moduleName, Runtime.Version version, Path directory) {
+        return new Archive(directory.resolve("out.jar"), moduleName, version, directory, true, null);
+    }
+
+    /**
+     * Creates a manifest with the main class attribute set to the given value.
+     *
+     * @param value value of the main class attribute
+     * @return a new manifest with the given attribute value
+     */
+    private static Manifest manifestWithMainClass(String value) {
+        Manifest m = new Manifest();
+        Attributes attributes = m.getMainAttributes();
+        attributes.put(Attributes.Name.MANIFEST_VERSION, "1.0");
+        attributes.put(Attributes.Name.MAIN_CLASS, value);
+        return m;
+    }
+
+    /**
+     * Returns the value of the main class attribute.
+     *
+     * @param m the manifest from which to get the value
+     * @return the main class attribute value, or {@code null} if none
+     */
+    private static Object mainClassOf(Manifest m) {
+        return m.getMainAttributes().get(Attributes.Name.MAIN_CLASS);
+    }
+
+    /**
+     * Verifies that {@link Archive#setMainClass(Manifest)} takes ownership for a module-qualified
+     * {@code "module/Class"} main class.
+     *
+     * The {@code "foo.bar/"} prefix in this test (the module name) is a Maven extension.
+     * The standard <abbr>JAR</abbr> specification accepts only the {@code "foo.MainFile"} class name.
+     */
+    @Test
+    void owningModuleClaimsMainClassAndRemovesItFromManifest() {
+        Archive owner = archive("foo.bar", null, Path.of("."));
+        Manifest m = manifestWithMainClass("foo.bar/foo.MainFile");
+        // The owner keeps the main class (emitted via --main-class) ...
+        assertTrue(owner.setMainClass(m));
+        // ... and the raw `module/Class` value is removed from the written manifest.
+        assertNull(mainClassOf(m));
+    }
+
+    /**
+     * Verifies that {@link Archive#setMainClass(Manifest)} does <em>not</em> take ownership of
+     * a module-qualified {@code "module/Class"} main class when the module name does not match.
+     * The {@code "foo.bar/"} prefix in this test (the module name) is a Maven extension.
+     * The standard <abbr>JAR</abbr> specification accepts only the {@code "foo.MainFile"} class name.
+     */
+    @Test
+    void nonOwningModuleRejectsMainClass() {
+        Archive nonOwner = archive("foo.bar.more", null, Path.of("."));
+        Manifest m = manifestWithMainClass("foo.bar/foo.MainFile");
+        assertFalse(nonOwner.setMainClass(m));
+        assertNull(mainClassOf(m));
+    }
+
+    /**
+     * Tests that which module keeps the main class does not depend on processing order.
+     * {@link ToolExecutor} gives each module a <em>copy</em> of the shared plugin manifest;
+     * this pins that the owning module (and only it) keeps the main class in either order,
+     * and that the shared manifest is never consumed.
+     */
+    @Test
+    void mainClassAssignmentIsIndependentOfModuleOrder() {
+        assertOwnership("foo.bar", "foo.bar.more", true); // owner processed first
+        assertOwnership("foo.bar.more", "foo.bar", false); // non-owner processed first
+    }
+
+    /**
+     * Helper method for {@link #mainClassAssignmentIsIndependentOfModuleOrder()}.
+     * Asserts that {@link Archive#setMainClass(Manifest)} returns {@code true}
+     * for the owner and {@code false} for the other module.
+     *
+     * <p>The {@code "foo.bar/"} prefix in this test (the module name) is a Maven extension.
+     * The standard <abbr>JAR</abbr> specification accepts only the {@code "foo.MainFile"} class name.
+     * This extension is used by the plugin for identifying in which <abbr>JAR</abbr> file to add this

Review Comment:
   Done.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3949849347


##########
src/main/java/org/apache/maven/plugins/jar/ExcludedFiles.java:
##########
@@ -0,0 +1,146 @@
+/*
+ * 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.jar;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardCopyOption;
+import java.util.List;
+
+/**
+ * A list of files to temporarily move outside the directory to package in a <abbr>JAR</abbr> archive.
+ * This class is needed when the {@link AbstractJarMojo} configuration has include or exclude filters.
+ * Excluded files are temporarily moved outside the directory to archive.
+ * We move these files for making possible to specify the whole directory to the {@code jar} tool.
+ * This approach is used instead of enumerating files in arguments given to the {@code jar} tool because
+ * such enumeration cannot contain directory entries (otherwise the whole directory would be included).
+ * Some software such as Spring applications component scan relies on the presence of directory entries.
+ */
+final class ExcludedFiles implements Closeable {
+    /**
+     * The paths of files or directories to temporarily move in another directory.
+     */
+    private final Path[] original;
+
+    /**
+     * The paths where files or directories were moved.
+     * For each index <var>i</var>, the original path of {@code moved[i]} was {@code original[i]}.
+     */
+    private final Path[] moved;
+
+    /**
+     * Temporary directory which will contain the {@code moved} files.
+     * It should be a parent directory of {@link #original} files for
+     * increasing the chances that it is on the same file system.
+     */
+    private final Path temporaryDirectory;
+
+    /**
+     * Index of the first path which is a directory instead of a file.
+     * All paths before this index in the {@link #original} and {@link #moved} arrays are files.
+     * All paths at this index and after this index are directories.
+     */
+    private final int indexOfFirstDirectory;
+
+    /**
+     * Creates a new list of files to move in a temporary directory.
+     *
+     * @param directory the directory which was scanned for files to include in the <abbr>JAR</abbr>
+     * @param excludedFiles paths of files to temporarily move in another directory

Review Comment:
   Yes, the push was done after I finished to go through all the issues. I mark them as resolved in advance because otherwise, it is difficult to remember which discussions were resolved and which ones to keep 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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "ascheman (via GitHub)" <gi...@apache.org>.
ascheman commented on PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#issuecomment-5573636290

   Great work, @desruisseaux, happy to have contributed, the reworked directory-entries handling and IT look right to me, CI is green - looking forward to a merge soon. I hope @elharo will finally approve, now that you have fixed all the remaining issues, as far as I can see.


-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#issuecomment-5269543805

   Thanks! I cherry-picked the commits with modifications:
   
   1. Rearranged the `if` and `else` blocks for avoiding duplicated tests and calls of `Runtime.version().feature()`. Omitted the part of the log message saying that the JAR was created successfully on JDK 17/18 for consistency with the JDK 19+ branch which emitted no message. Edited the comments and commit message with minor clarifications (the validation issue was not only in the context of module source hierarchy projects) and omission of details about JDK internal in commit (kept in commit message), replaced by links to JDK issue tracker.
   2. The commit repairs the problem after it happened (directory handled as the base version when actually it was another version). I think that the root cause of the problem is that the `Archive` constructor had no `version` argument. I tried a correction of that root cause instead. We will see with GitHub action if it works.
   
   Will continue with other commits tonight or tomorrow.


-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "rmannibucau (via GitHub)" <gi...@apache.org>.
rmannibucau commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3777282237


##########
src/main/java/org/apache/maven/plugins/jar/AbstractJarMojo.java:
##########
@@ -207,167 +205,199 @@ protected final Log getLog() {
     protected abstract String getType();
 
     /**
-     * Returns the JAR file to generate, based on an optional classifier.
+     * {@return the scope of dependencies}
+     * It should be {@link PathScope#MAIN_COMPILE} or {@link PathScope#TEST_COMPILE}.
+     * Note that we use compile scope rather than runtime scope because dependencies
+     * cannot appear in {@code requires} statement if they didn't had compile scope.
+     */
+    protected abstract PathScope getDependencyScope();
+
+    /**
+     * {@return the JAR tool to use for archiving the code}
      *
-     * @param basedir the output directory
-     * @param resultFinalName the name of the JAR file
-     * @param classifier an optional classifier
-     * @return the file to generate
+     * @throws MojoException if no JAR tool was found
+     *
+     * @since 4.0.0-beta-2
      */
-    protected Path getJarFile(Path basedir, String resultFinalName, String classifier) {
-        Objects.requireNonNull(basedir, "basedir is not allowed to be null");
-        Objects.requireNonNull(resultFinalName, "finalName is not allowed to be null");
-        String fileName = resultFinalName + (hasClassifier(classifier) ? '-' + classifier : "") + ".jar";
-        return basedir.resolve(fileName);
+    protected ToolProvider getJarTool() throws MojoException {
+        return ToolProvider.findFirst(toolId).orElseThrow(() -> new MojoException("No such \"" + toolId + "\" tool."));
     }
 
     /**
-     * Generates the JAR.
+     * Returns whether the specified Java version is supported.
      *
-     * @return the path to the created archive file
-     * @throws MojoException in case of an error
+     * @param release name of an {@link SourceVersion} enumeration constant
+     * @return whether the current environment support that version
      */
-    public Path createArchive() throws MojoException {
-        Path basedir = outputDirectory != null
-                ? outputDirectory
-                : Path.of(project.getBuild().getDirectory());
-        String resultFinalName =
-                finalName != null ? finalName : project.getBuild().getFinalName();
-        Path jarFile = getJarFile(basedir, resultFinalName, getClassifier());
-
-        FileSetManager fileSetManager = new FileSetManager();
-        FileSet jarContentFileSet = new FileSet();
-        jarContentFileSet.setDirectory(getClassesDirectory().toAbsolutePath().toString());
-        jarContentFileSet.setIncludes(Arrays.asList(getIncludes()));
-        jarContentFileSet.setExcludes(Arrays.asList(getExcludes()));
-
-        String[] includedFiles = fileSetManager.getIncludedFiles(jarContentFileSet);
-
-        if (detectMultiReleaseJar
-                && Arrays.stream(includedFiles)
-                        .anyMatch(
-                                p -> p.startsWith("META-INF" + File.separatorChar + "versions" + File.separatorChar))) {
-            getLog().debug("Adding 'Multi-Release: true' manifest entry.");
-            archive.addManifestEntry(Attributes.Name.MULTI_RELEASE.toString(), "true");
+    private static boolean isSupported(String release) {

Review Comment:
   how does it work if using a fork (potentially behind toolprovider API)?



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#issuecomment-5327160643

   Correction, the `<project.build.outputTimestamp/>` workaround cause an `IndexOutOfBoundsException` in the compiler plugin 3.15.0.


-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#issuecomment-5326485916

   @hboutemy: since reproducible build is supported only partially on Java 17 and 18, we were wondering if it should be a hard build failure if reproducible build is requested on Java 17 or 18. Currently, it is only a warning. If we make it a hard failure, since the `project.build.outputTimestamp` property has a default value in the super POM of all Maven 4 projects, the JAR plugin would fail by default for everyone using Java 17 or 18. A workaround is to opt-out reproducible build in the `pom.xml`:
   
   ```xml
     <properties>
       <project.build.outputTimestamp/> <!-- For compatibility with Java 17 and 18. -->
     </properties>`
   ```
   
   At first, we though that silently producing a non-fully reproducible build on Java 17/18 would be damageable. On a second though, I now think that having all Maven 4 projects failing by default on Java 17/18 is worst. Do you have any opinion on this matter?


-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "ascheman (via GitHub)" <gi...@apache.org>.
ascheman commented on PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#issuecomment-5338275086

   Thanks for creating the [OpenJDK documentation issue](https://bugs.openjdk.org/browse/JDK-8390615) about `jar -C` usage, @jaikiran. We should perhaps mention it in the comments about the respective workarounds, @desruisseaux.


-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3891809210


##########
src/main/java/org/apache/maven/plugins/jar/AbstractJarMojo.java:
##########
@@ -207,167 +205,208 @@ protected final Log getLog() {
     protected abstract String getType();
 
     /**
-     * Returns the JAR file to generate, based on an optional classifier.
+     * {@return the scope of dependencies}
+     * It should be {@link PathScope#MAIN_COMPILE} or {@link PathScope#TEST_COMPILE}.
+     * Note that we use compile scope rather than runtime scope because dependencies
+     * cannot appear in {@code requires} statement if they didn't had compile scope.
+     */
+    protected abstract PathScope getDependencyScope();
+
+    /**
+     * {@return the JAR tool to use for archiving the code}
      *
-     * @param basedir the output directory
-     * @param resultFinalName the name of the JAR file
-     * @param classifier an optional classifier
-     * @return the file to generate
+     * @throws MojoException if no JAR tool was found
+     *
+     * @since 4.0.0-beta-2
      */
-    protected Path getJarFile(Path basedir, String resultFinalName, String classifier) {
-        Objects.requireNonNull(basedir, "basedir is not allowed to be null");
-        Objects.requireNonNull(resultFinalName, "finalName is not allowed to be null");
-        String fileName = resultFinalName + (hasClassifier(classifier) ? '-' + classifier : "") + ".jar";
-        return basedir.resolve(fileName);
+    protected ToolProvider getJarTool() throws MojoException {

Review Comment:
   Yes package access would suffice. Some method are protected because they were already protected in the previous version. Some other methods are protected for consistency. In this case, it is because it is a powerful overriding point. By overriding this method, a subclass can change completely the tool used for generating the JAR file.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3891866900


##########
src/main/java/org/apache/maven/plugins/jar/AbstractJarMojo.java:
##########
@@ -207,167 +205,208 @@ protected final Log getLog() {
     protected abstract String getType();
 
     /**
-     * Returns the JAR file to generate, based on an optional classifier.
+     * {@return the scope of dependencies}
+     * It should be {@link PathScope#MAIN_COMPILE} or {@link PathScope#TEST_COMPILE}.
+     * Note that we use compile scope rather than runtime scope because dependencies
+     * cannot appear in {@code requires} statement if they didn't had compile scope.
+     */
+    protected abstract PathScope getDependencyScope();
+
+    /**
+     * {@return the JAR tool to use for archiving the code}
      *
-     * @param basedir the output directory
-     * @param resultFinalName the name of the JAR file
-     * @param classifier an optional classifier
-     * @return the file to generate
+     * @throws MojoException if no JAR tool was found
+     *
+     * @since 4.0.0-beta-2
      */
-    protected Path getJarFile(Path basedir, String resultFinalName, String classifier) {
-        Objects.requireNonNull(basedir, "basedir is not allowed to be null");
-        Objects.requireNonNull(resultFinalName, "finalName is not allowed to be null");
-        String fileName = resultFinalName + (hasClassifier(classifier) ? '-' + classifier : "") + ".jar";
-        return basedir.resolve(fileName);
+    protected ToolProvider getJarTool() throws MojoException {
+        return ToolProvider.findFirst(toolId).orElseThrow(() -> new MojoException("No such \"" + toolId + "\" tool."));
     }
 
     /**
-     * Generates the JAR.
+     * Returns the output time stamp or, as a fallback, the {@code SOURCE_DATE_EPOCH} environment variable.
+     * If the time stamp is expressed in seconds, it is converted to ISO 8601 format. Otherwise it is returned as-is.
      *
-     * @return the path to the created archive file
-     * @throws MojoException in case of an error
+     * @return the time stamp in presumed ISO 8601 format, or {@code null} if none
+     *
+     * @since 4.0.0-beta-2
      */
-    public Path createArchive() throws MojoException {
-        Path basedir = outputDirectory != null
-                ? outputDirectory
-                : Path.of(project.getBuild().getDirectory());
-        String resultFinalName =
-                finalName != null ? finalName : project.getBuild().getFinalName();
-        Path jarFile = getJarFile(basedir, resultFinalName, getClassifier());
-
-        FileSetManager fileSetManager = new FileSetManager();
-        FileSet jarContentFileSet = new FileSet();
-        jarContentFileSet.setDirectory(getClassesDirectory().toAbsolutePath().toString());
-        jarContentFileSet.setIncludes(Arrays.asList(getIncludes()));
-        jarContentFileSet.setExcludes(Arrays.asList(getExcludes()));
-
-        String[] includedFiles = fileSetManager.getIncludedFiles(jarContentFileSet);
-
-        if (detectMultiReleaseJar
-                && Arrays.stream(includedFiles)
-                        .anyMatch(
-                                p -> p.startsWith("META-INF" + File.separatorChar + "versions" + File.separatorChar))) {
-            getLog().debug("Adding 'Multi-Release: true' manifest entry.");
-            archive.addManifestEntry(Attributes.Name.MULTI_RELEASE.toString(), "true");
+    protected String getOutputTimestamp() {
+        String time = nullIfAbsent(outputTimestamp);
+        if (time == null) {
+            time = nullIfAbsent(System.getenv("SOURCE_DATE_EPOCH"));
+            if (time == null) {
+                return null;
+            }
         }
+        if (Runtime.version().feature() < ToolExecutor.JDK_SUPPORT_DATE) {
+            log.warn("Reproducible build requires Java " + ToolExecutor.JDK_SUPPORT_DATE + " or later.");
+            return null;
+        }
+        for (int i = time.length(); --i >= 0; ) {
+            char c = time.charAt(i);
+            if ((c < '0' || c > '9') && (i != 0 || c != '-')) {
+                return time;
+            }
+        }
+        return Instant.ofEpochSecond(Long.parseLong(time)).toString();
+    }
 
-        // May give false positives if the files is named as module descriptor
-        // but is not in the root of the archive or in the versioned area
-        // (and hence not actually a module descriptor).
-        // That is fine since the modular Jar archiver will gracefully
-        // handle such case.
-        // And also such case is unlikely to happen as file ending
-        // with "module-info.class" is unlikely to be included in Jar file
-        // unless it is a module descriptor.
-        boolean containsModuleDescriptor =
-                Arrays.stream(includedFiles).anyMatch(p -> p.endsWith(MODULE_DESCRIPTOR_FILE_NAME));
-
-        String archiverName = containsModuleDescriptor ? "mjar" : "jar";
+    /**
+     * {@return the patterns of files to include, or an empty list if no include pattern was specified}
+     */
+    protected List<String> getIncludes() {
+        return asList(includes);
+    }
 
-        MavenArchiver archiver = new MavenArchiver();
-        archiver.setCreatedBy("Maven JAR Plugin", "org.apache.maven.plugins", "maven-jar-plugin");
-        archiver.setBuildJdkSpecDefaultEntry(archive.getManifest().isAddBuildEnvironmentEntries());
-        archiver.setArchiver((JarArchiver) archivers.get(archiverName));
-        archiver.setOutputFile(jarFile.toFile());
+    /**
+     * {@return the patterns of files to exclude, or an empty list if no exclude pattern was specified}
+     */
+    protected List<String> getExcludes() {
+        return asList(excludes);
+    }
 
-        // configure for Reproducible Builds based on outputTimestamp value
-        archiver.configureReproducibleBuild(outputTimestamp);
+    /**
+     * Returns the output directory and ensures that the directory exists.
+     * The returned directory will be either {@link #outputDirectory} if non-null,
+     * or {@link org.apache.maven.api.model.Build#getDirectory()} otherwise.
+     *
+     * <p>The directory is usually {@code target} and should always exist since it is usually the output
+     * of the compiler plugin. If nevertheless the directory does not exist, then this method creates it.
+     * However, this method does not try to create the parent directory, which should be the Maven sub-project.</p>
+     *
+     * @return the directory containing the generated <abbr>JAR</abbr> files.
+     * @throws IOException if the output directory did not existed and could not be created
+     */
+    protected Path getOutputDirectory() throws IOException {
+        Path dir = outputDirectory;
+        if (dir == null) {
+            dir = Path.of(project.getBuild().getDirectory());
+        }
+        if (Files.notExists(dir)) {
+            dir = Files.createDirectory(dir);
+        }
+        return dir;
+    }
 
-        archive.setForced(forceCreation);
+    /**
+     * Returns the given elements as a list if non-null.
+     *
+     * @param elements the elements, or {@code null}
+     * @return the elements as a list, or {@code null} if the given array was null
+     */
+    private static List<String> asList(String[] elements) {
+        return (elements == null) ? List.of() : Arrays.asList(elements);
+    }
 
-        try {
-            Path contentDirectory = getClassesDirectory();
-            if (!Files.exists(contentDirectory)) {
-                if (!forceCreation) {
-                    getLog().warn("JAR will be empty - no content was marked for inclusion!");
-                }
-            } else {
-                archiver.getArchiver().addDirectory(contentDirectory.toFile(), getIncludes(), getExcludes());
+    /**
+     * Generates the <abbr>JAR</abbr> files.
+     * Map keys are module names or {@code null} if the project does not use module hierarchy.
+     * Values are (<var>type</var>, <var>path</var>) pairs associated with each module where
+     * <var>type</var> is {@code "pom"}, {@code "jar"} or {@code "test-jar"} and <var>path</var>
+     * is the path to the <abbr>POM</abbr> or <abbr>JAR</abbr> file.
+     *
+     * <p>Note that a null key does not necessarily means that the <abbr>JAR</abbr> is not modular.
+     * It only means that the project was not compiled with module hierarchy,
+     * i.e. {@code target/classes/} subdirectories having module names.

Review Comment:
   Done.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3844160633


##########
src/main/java/org/apache/maven/plugins/jar/PomDerivation.java:
##########
@@ -0,0 +1,525 @@
+/*
+ * 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.jar;
+
+import javax.xml.stream.XMLStreamException;
+
+import java.io.BufferedInputStream;
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.UncheckedIOException;
+import java.lang.module.ModuleDescriptor;
+import java.lang.module.ModuleFinder;
+import java.lang.module.ModuleReference;
+import java.net.URI;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.DependencyCoordinates;
+import org.apache.maven.api.JavaPathType;
+import org.apache.maven.api.Session;
+import org.apache.maven.api.Type;
+import org.apache.maven.api.model.Dependency;
+import org.apache.maven.api.model.Model;
+import org.apache.maven.api.model.Parent;
+import org.apache.maven.api.plugin.MojoException;
+import org.apache.maven.api.services.DependencyCoordinatesFactory;
+import org.apache.maven.api.services.DependencyCoordinatesFactoryRequest;
+import org.apache.maven.api.services.DependencyResolver;
+import org.apache.maven.api.services.DependencyResolverRequest;
+import org.apache.maven.api.services.DependencyResolverResult;
+import org.apache.maven.api.services.ModelBuilderException;
+import org.apache.maven.model.v4.MavenStaxWriter;
+
+/**
+ * A mapper from Maven model dependencies to Java module names.
+ * A single instance of this class is created for a Maven project,
+ * then shared by all {@link ForModule} instances (one per module to archive).
+ */
+final class PomDerivation {
+    /**
+     * Whether to expand the list of transitive dependencies in the generated <abbr>POM</abbr>.
+     */
+    private static final boolean EXPAND_TRANSITIVE = false;
+
+    /**
+     * Copy of {@link AbstractJarMojo#session}.
+     */
+    private final Session session;
+
+    /**
+     * The project model, which includes dependencies of all modules.
+     */
+    private final Model projectModel;
+
+    /**
+     * The factory to use for creating temporary {@link DependencyCoordinates} instances.
+     */
+    private final DependencyCoordinatesFactory coordinateFactory;
+
+    /**
+     * Provide module descriptors from module names.
+     * May be {@code null} if no {@code module-info} was found.
+     */
+    private final ModuleFinder moduleFinder;
+
+    /**
+     * Module references from paths to the <abbr>JAR</abbr> file or root directory.
+     */
+    private final Map<URI, ModuleReference> fromURI;
+
+    /**
+     * Module names associated to Maven dependencies.
+     * This map contains {@link DependencyCoordinates#getId()} as keys and module references as values.
+     * This is used for detecting which dependencies are really used according {@code module-info.class}.
+     *
+     * @todo The keys should be instances of {@link DependencyCoordinates}. Unfortunately, as of Maven 4.0.0-rc-5
+     *       that interface does not define the {@code equals} and {@code hashCode} contracts.
+     */
+    private final Map<String, ModuleReference> fromDependency;
+
+    /**
+     * Modules that are built by the project. Keys are module names.
+     */
+    private final Map<String, Dependency> builtModules;
+
+    /**
+     * Creates a new mapper from Maven dependency to module name.
+     *
+     * @param mojo the enclosing <abbr>MOJO</abbr>
+     * @param moduleRoots paths to root directories of each module to archive in a module hierarchy
+     * @throws IOException if an I/O error occurred while fetching dependencies
+     * @throws MavenException if an error occurred while fetching dependencies for a reason other than I/O.
+     */
+    PomDerivation(final AbstractJarMojo mojo, final List<Path> moduleRoots) throws IOException {
+        this.session = mojo.session;
+        projectModel = mojo.project.getModel();
+        coordinateFactory = session.getService(DependencyCoordinatesFactory.class);
+        DependencyResolver resolver = session.getService(DependencyResolver.class);
+        DependencyResolverResult result = resolver.resolve(DependencyResolverRequest.builder()
+                .session(session)
+                .project(mojo.project)
+                .requestType(DependencyResolverRequest.RequestType.RESOLVE)
+                .pathScope(mojo.getDependencyScope())
+                .pathTypeFilter(Set.of(JavaPathType.MODULES, JavaPathType.CLASSES))
+                .build());
+
+        rethrow(result);
+        final Map<org.apache.maven.api.Dependency, Path> dependencies = result.getDependencies();
+        final Path[] allModulePaths = toRealPaths(moduleRoots, dependencies.values());
+        fromURI = new HashMap<>(allModulePaths.length); // TODO: use newHashMap with JDK19.
+        moduleFinder = ModuleFinder.of(allModulePaths);
+        if (moduleFinder != null) {
+            for (ModuleReference reference : moduleFinder.findAll()) {
+                reference.location().ifPresent((location) -> fromURI.put(location, reference));
+            }
+        }
+        fromDependency = new HashMap<>(dependencies.size()); // TODO: use newHashMap with JDK19.
+        for (Map.Entry<org.apache.maven.api.Dependency, Path> entry : dependencies.entrySet()) {
+            Path modulePath = entry.getValue().toRealPath();
+            ModuleReference reference = fromURI.get(modulePath.toUri());
+            if (reference != null) {
+                DependencyCoordinates coordinates = entry.getKey().toCoordinates();
+                String id = coordinates.getId();
+                ModuleReference old = fromDependency.putIfAbsent(id, reference);
+                if (old == null) {
+                    coordinates = withoutVersion(coordinates);
+                    id = coordinates.getId();
+                    old = fromDependency.putIfAbsent(id, reference);
+                }
+                if (old != null && !old.equals(reference)) {
+                    mojo.log.warn("The \"" + id + "\" dependency is declared twice with different module names: \""
+                            + old.descriptor().name() + "\" and \""
+                            + reference.descriptor().name() + "\".");
+                }
+            }
+        }
+        builtModules = new HashMap<>(moduleRoots.size()); // TODO: use newHashMap with JDK19.
+        for (Path root : moduleRoots) {
+            ModuleDescriptor descriptor = fromURI.get(root.toUri()).descriptor();

Review Comment:
   Indeed. Will apply.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#issuecomment-5561180671

   Checking again: are we okay for a merge?


-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3891816647


##########
src/main/java/org/apache/maven/plugins/jar/AbstractJarMojo.java:
##########
@@ -207,167 +205,208 @@ protected final Log getLog() {
     protected abstract String getType();
 
     /**
-     * Returns the JAR file to generate, based on an optional classifier.
+     * {@return the scope of dependencies}
+     * It should be {@link PathScope#MAIN_COMPILE} or {@link PathScope#TEST_COMPILE}.
+     * Note that we use compile scope rather than runtime scope because dependencies
+     * cannot appear in {@code requires} statement if they didn't had compile scope.
+     */
+    protected abstract PathScope getDependencyScope();

Review Comment:
   Since this method is `abstract`, the `AbstractMojo` class become impossible to subclass outside its package if this method is not protected. We may argue that this class is not intended to be subclassed outside its package and I would tend to agree. But the previous version was sub-classeable.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3892044549


##########
src/main/java/org/apache/maven/plugins/jar/MetadataFiles.java:
##########
@@ -0,0 +1,250 @@
+/*
+ * 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.jar;
+
+import java.io.BufferedWriter;
+import java.io.Closeable;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Properties;
+import java.util.jar.Manifest;
+import java.util.stream.Collectors;
+
+import org.apache.maven.api.ProducedArtifact;
+import org.apache.maven.api.Project;
+import org.apache.maven.shared.archiver.MavenArchiveConfiguration;
+
+/**
+ * Temporary metadata files generated by Maven before inclusion in the archive.
+ * Those files are created in a temporary {@code META-INF} directory when first needed.
+ * Those files are deleted after the build, unless the build failed or Maven was run in verbose mode.
+ */
+final class MetadataFiles implements Closeable {
+    /**
+     * The {@value} directory.
+     * This is part of <abbr>JAR</abbr> file specification.
+     */
+    static final String META_INF = "META-INF";
+
+    /**
+     * The {@value} file.
+     * This is part of <abbr>JAR</abbr> file specification.
+     */
+    static final String MANIFEST = "MANIFEST.MF";
+
+    /**
+     * The subdirectory where to add Maven-specific files.
+     */
+    static final String MAVEN_DIR = "maven";
+
+    /**
+     * The project for which to write metadata files.
+     */
+    private final Project project;
+
+    /**
+     * The output directory (usually {@code ${baseDir}/target/}).
+     */
+    private final Path buildDir;
+
+    /**
+     * All files and directories in the order that they were created.
+     * The first element of this list shall be the root temporary directory created by this class.
+     */
+    private final List<Path> filesToDelete;
+
+    /**
+     * The <abbr>POM</abbr> file to attach to the artifact. This is initially the project <abbr>POM</abbr>,
+     * but will be replaced by a new file generated by {@link ForModule} if module hierarchy is used.
+     * That file may be copied verbatim in the {@code META-INF/maven/} directory of the <abbr>JAR</abbr>.
+     */
+    private Path attachedPOM;
+
+    /**
+     * Creates an initially empty set of temporary metadata files.
+     *
+     * @param project the project for which to write metadata files
+     * @param buildDir the (usually) {@code ${baseDir}/target/} directory
+     */
+    MetadataFiles(Project project, Path buildDir) {
+        this.project = project;
+        this.buildDir = buildDir;
+        filesToDelete = new ArrayList<>();
+        attachedPOM = project.getPomPath();
+    }
+
+    /**
+     * Derives a <abbr>POM</abbr> as the intersection of the given {@code model} and {@code archive}.
+     *
+     * @param context the tool executor which is generating all archives
+     * @param archive the archive for which to generate a <abbr>POM</abbr>
+     * @param manifest manifest to use for deriving project name, or {@code null} if none
+     * @throws IOException if an error occurred while reading the {@code module-info.class} file
+     *         or while writing the <abbr>POM</abbr> file
+     */
+    void deriveModulePOM(ToolExecutor context, Archive archive, Manifest manifest) throws IOException {
+        var pom = context.pomDerivation.new ForModule(archive, manifest);
+        pom.writeModulePOM();
+        attachedPOM = pom.pomFile;
+        archive.pomFile = pom.pomFile;
+    }
+
+    /**
+     * Adds the given manifest in a temporary file.
+     * The file will be deleted when {@link #close()} is invoked.
+     *
+     * @param manifest the manifest to write
+     * @return the temporary manifest file
+     * @throws IOException if an error occurred while writing the file
+     */
+    public Path addManifest(final Manifest manifest) throws IOException {
+        Path file = baseDirectory().resolve(MANIFEST);
+        try (OutputStream out = Files.newOutputStream(file)) {
+            filesToDelete.add(file);
+            manifest.write(out);
+        }
+        return file;
+    }
+
+    /**
+     * {@return the root temporary directory for the files created by this class}
+     * The directory is created the first time that this method is invoked.
+     *
+     * @throws IOException if an error occurred while creating the temporary directory
+     */
+    private Path baseDirectory() throws IOException {
+        if (filesToDelete.isEmpty()) {
+            filesToDelete.add(Files.createTempDirectory(buildDir, "classes-"));
+        }
+        return filesToDelete.get(0);
+    }
+
+    /**
+     * Creates a new directory and adds it to the list of files to delete after the build.
+     *
+     * @param dir the existing directory where to create a sub-directory
+     * @param path path to the subdirectory to create
+     * @return the new directory
+     * @throws IOException if an error occurred while creating the subdirectory
+     */
+    private Path createDirectories(Path dir, String... path) throws IOException {
+        for (String subdir : path) {
+            dir = Files.createDirectory(dir.resolve(subdir));
+            filesToDelete.add(dir);
+        }
+        return dir;
+    }
+
+    /**
+     * Writes the {@code pom.xml} and {@code pom.properties} files.
+     * This method returns the base temporary directory followed by files that the "jar" tool will need to add
+     *
+     * @param archive archive configuration
+     * @param reproducible whether to enforce reproducible build
+     * @return arguments for the "jar" tool
+     * @throws IOException if an error occurred while writing the files
+     */
+    public List<Path> addPOM(final MavenArchiveConfiguration archive, final boolean reproducible) throws IOException {
+        final String groupId = project.getGroupId();
+        final String artifactId = project.getArtifactId();
+        final String version;
+        final ProducedArtifact pom = project.getPomArtifact();
+        if (pom.isSnapshot()) {
+            version = pom.getVersion().toString();
+        } else {
+            version = project.getVersion();
+        }
+        final Path baseDir = baseDirectory();
+        final Path mavenDir = createDirectories(baseDir, META_INF, MAVEN_DIR, groupId, artifactId);
+        final Path pomFile = linkOrCopy(attachedPOM, mavenDir.resolve("pom.xml"));
+        filesToDelete.add(pomFile); // Add soon for deleting this file even if an exception is thrown below.

Review Comment:
   Replaced "Add soon" by "Register now".



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3891607447


##########
src/main/java/org/apache/maven/plugins/jar/AbstractJarMojo.java:
##########
@@ -108,13 +105,22 @@ public abstract class AbstractJarMojo implements org.apache.maven.api.plugin.Moj
     @Parameter
     protected MavenArchiveConfiguration archive = new MavenArchiveConfiguration();
 
+    /**
+     * The service to use for attaching the artifacts produced by this plugin.
+     */
     @Inject
     protected ProjectManager projectManager;
 
     /**
-     * Require the jar plugin to build a new JAR even if none of the contents appear to have changed.
-     * By default, this plugin looks to see if the output JAR exists and inputs have not changed.
-     * If these conditions are true, the plugin skips creation of the JAR file.
+     * The service to use for creating include and exclude filters.

Review Comment:
   `PathMatcherFactory` is an interface from the `org.apache.maven.api.services` package and extends the `Service` interface. It can be obtained by `Session.getService(PathMatcherFactory.class)`.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3892037110


##########
src/main/java/org/apache/maven/plugins/jar/FileCollector.java:
##########
@@ -0,0 +1,496 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.PathMatcher;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayDeque;
+import java.util.Deque;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.services.PathMatcherFactory;
+
+/**
+ * Dispatch the files in the output directory into the <abbr>JAR</abbr> files to create.
+ * Instead of just archiving as-is the content of the output directory, this class separates
+ * the following subdirectories to the options listed below:
+ *
+ * <ul>
+ *   <li>The {@code META-INF/MANIFEST.MF} file will be given to the {@code --manifest} option.</li>
+ *   <li>Files in the following directories will be given to the {@code --release} option:
+ *     <ul>
+ *       <li>{@code META-INF/versions/}</li>
+ *       <li>{@code META-INF/versions-modular/<module>/}</li>
+ *       <li>{@code <module>/META-INF/versions/}</li>
+ *     </ul>
+ *   </li>
+ * </ul>
+ *
+ * The reason for using the options is that they allow the {@code jar} tool to perform additional verifications.
+ * For example, when using the {@code --release} option, {@code jar} verifies the <abbr>API</abbr> compatibility.
+ */
+final class FileCollector extends SimpleFileVisitor<Path> {
+    /**
+     * The file to check for deciding whether the <abbr>JAR</abbr> is modular.
+     */
+    static final String MODULE_DESCRIPTOR_FILE_NAME = "module-info.class";
+
+    /**
+     * The {@value} directory.
+     * This is part of <abbr>JAR</abbr> file specification.
+     */
+    private static final String VERSIONS = "versions";
+
+    /**
+     * The {@value} directory.
+     * This is Maven-specific.
+     */
+    private static final String VERSIONS_MODULAR = "versions-modular";
+
+    /**
+     * Context (logger, configuration) in which the <abbr>JAR</abbr> file are created.
+     */
+    private final ToolExecutor context;
+
+    /**
+     * Whether to detect multi-release <abbr>JAR</abbr> files.
+     * The default value is {@code true}.
+     *
+     * @see AbstractJarMojo#detectMultiReleaseJar
+     */
+    private final boolean detectMultiReleaseJar;
+
+    /**
+     * Combination of includes and excludes path matcher applied on files.
+     */
+    @Nonnull
+    private final PathMatcher fileMatcher;
+
+    /**
+     * Combination of includes and excludes path matcher applied on directories.
+     */
+    @Nonnull
+    private final PathMatcher directoryMatcher;
+
+    /**
+     * Whether the matchers accept all files and there is no need to sort the files.
+     * In such case, we can declare whole directories to the {@code jar} tool instead
+     * of scanning the directory tree ourselves.
+     */
+    private final boolean addDirectories;
+
+    /**
+     * Files found in the output directory when package hierarchy is used.
+     * At most one of {@code packageHierarchy} and {@link #moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Archive packageHierarchy;
+
+    /**
+     * Files found in the output directory when module hierarchy is used. Keys are module names.
+     * At most one of {@link #packageHierarchy} and {@code moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Map<String, Archive> moduleHierarchy;
+
+    /**
+     * The current module being archived. This field is updated every times that {@code FileCollector}
+     * enters in a new module directory.
+     */
+    @Nonnull
+    private Archive currentModule;
+
+    /**
+     * The module and target Java release currently being scanned. This field is updated every times that
+     * {@code FileCollector} enters in a new module directory or in a new target Java release for a given module.
+     */
+    @Nonnull
+    private Archive.FileSet currentFilesToArchive;
+
+    /**
+     * The current target Java release, or {@code null} if none.
+     */
+    @Nullable
+    private Runtime.Version currentTargetVersion;
+
+    /**
+     * Identification of the kinds of directories being traversed.
+     * The length of this list is the depth in the directory hierarchy.
+     * The last element identifies the type of the current directory.
+     */
+    private final Deque<DirectoryRole> directoryRoles;
+
+    /**
+     * Whether to check when a file is the {@code MANIFEST.MF} file.
+     * This is allowed only when scanning the content of a {@code META-INF} directory.
+     */
+    private boolean checkForManifest;
+
+    /**
+     * Creates a new file collector.
+     *
+     * @param mojo the <abbr>MOJO</abbr> from which to get the configuration
+     * @param context context (logger, configuration) in which the <abbr>JAR</abbr> file are created
+     * @param directory the base directory of the files to archive
+     */
+    FileCollector(AbstractJarMojo mojo, ToolExecutor context, Path directory, PathMatcherFactory matcherFactory) {
+        this.context = context;
+        detectMultiReleaseJar = mojo.detectMultiReleaseJar;
+        directoryRoles = new ArrayDeque<>();
+        fileMatcher = matcherFactory.createPathMatcher(directory, mojo.getIncludes(), mojo.getExcludes(), false);
+        directoryMatcher = matcherFactory.deriveDirectoryMatcher(fileMatcher);
+        addDirectories = !context.isReproducible()
+                && matcherFactory.isIncludesAll(fileMatcher)
+                && matcherFactory.isIncludesAll(directoryMatcher);
+        packageHierarchy = context.newArchive(null, null, directory);
+        moduleHierarchy = new LinkedHashMap<>();
+        resetToPackageHierarchy();
+    }
+
+    /**
+     * Resets this {@code FileCollector} to the state where a package hierarchy is presumed.
+     */
+    private void resetToPackageHierarchy() {
+        currentModule = packageHierarchy;
+        currentFilesToArchive = currentModule.baseRelease();
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a module.
+     * For an output generated by {@code javac} from a module source hierarchy,
+     * the directory name is guaranteed to be the module name.
+     *
+     * @param directory a {@code "<module>"} or {@code "META-INF/versions-modular/<module>"} directory
+     */
+    private void enterModuleDirectory(final Path directory) {
+        String moduleName = directory.getFileName().toString();
+        currentModule = moduleHierarchy.computeIfAbsent(
+                moduleName, (name) -> context.newArchive(name, currentTargetVersion, directory));
+        currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a target Java version.
+     * The {@code useDirectly} argument tells whether the content of this directory will be specified directly
+     * as the content to add in the <abbr>JAR</abbr> file. This argument should be {@code false} when there is
+     * another directory level (the module names) to process before to add content.
+     *
+     * @param directory a {@code "META-INF/versions/<n>"} or {@code "META-INF/versions-modular/<n>"} directory
+     * @param useDirectly whether the directory is {@code "META-INF/versions/<n>"}
+     * @return whether to skip the directory because of invalid version number
+     */
+    private boolean enterVersionDirectory(final Path directory, final boolean useDirectly) {
+        try {
+            currentTargetVersion = Runtime.Version.parse(directory.getFileName().toString());
+        } catch (IllegalArgumentException e) {
+            context.warnInvalidVersion(directory, e);
+            return true;
+        }
+        if (useDirectly) {
+            currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+        }
+        return false;
+    }
+
+    /**
+     * Determines if the given directory should be scanned for files to archive.
+     * This method may also update {@link #currentFilesToArchive} if it detects
+     * that we are entering in a new module or a new target Java release.
+     *
+     * @param directory the directory which will be traversed
+     * @param attributes the directory's basic attributes
+     */
+    @Override
+    @SuppressWarnings("checkstyle:MissingSwitchDefault")
+    public FileVisitResult preVisitDirectory(final Path directory, final BasicFileAttributes attributes)
+            throws IOException {
+        DirectoryRole role;
+        if (directoryRoles.isEmpty()) {
+            role = DirectoryRole.ROOT;
+        } else {
+            if (!directoryMatcher.matches(directory)) {
+                return FileVisitResult.SKIP_SUBTREE;
+            }
+            checkForManifest = false;
+            role = directoryRoles.getLast();
+            switch (role) {
+                case ROOT:
+                    /*
+                     * Entering in any subdirectory of `target/classes` (or other directory to archive).
+                     * We need to handle `META-INF` and modules in a special way, and archive the rest.
+                     */
+                    if (directory.endsWith(MetadataFiles.META_INF)) {
+                        role = DirectoryRole.META_INF;
+                        checkForManifest = true;
+                    } else if (Files.isRegularFile(directory.resolve(MODULE_DESCRIPTOR_FILE_NAME))) {
+                        role = DirectoryRole.NAMED_MODULE;
+                        enterModuleDirectory(directory);
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case META_INF:
+                    /*
+                     * Entering in a subdirectory of `META-INF` or `<module>/META-INF`. We will need to handle
+                     * `MANIFEST.MF`, `versions` and `versions-modular` in a special way, and archive the rest.
+                     */
+                    if (detectMultiReleaseJar && directory.endsWith(VERSIONS)) {
+                        role = DirectoryRole.VERSIONS;
+                    } else if (directory.endsWith(VERSIONS_MODULAR)) {
+                        if (!detectMultiReleaseJar) {
+                            // Used asked for no multi-release JAR.
+                            return FileVisitResult.SKIP_SUBTREE;
+                        }
+                        role = DirectoryRole.VERSIONS_MODULAR;
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case VERSIONS:
+                    /*
+                     * Entering in a `META-INF/versions/<n>/` directory for a specific target Java release.
+                     * May also be a `<module>/META-INF/versions/<n>/` directory, even if the latter is not
+                     * the layout generated by Maven Compiler Plugin.
+                     */
+                    if (enterVersionDirectory(directory, true)) {
+                        // An error occurred while parsing the version number.
+                        return FileVisitResult.SKIP_SUBTREE;
+                    }
+                    role = DirectoryRole.RESOURCES;
+                    break;
+
+                case VERSIONS_MODULAR:
+                    /*
+                     * Entering in a `META-INF/versions-modular/<n>/` directory for a specific target Java release.
+                     * That directory contains all modules for the version.
+                     */
+                    resetToPackageHierarchy(); // No module in particular yet.
+                    if (enterVersionDirectory(directory, false)) {
+                        // An error occurred while parsing the version number.
+                        return FileVisitResult.SKIP_SUBTREE;
+                    }
+                    role = DirectoryRole.MODULES;
+                    break;
+
+                case MODULES:
+                    /*
+                     * Entering in a `META-INF/versions-modular/<n>/<module>` directory.
+                     */
+                    enterModuleDirectory(directory);
+                    role = DirectoryRole.NAMED_MODULE;
+                    break;
+
+                case NAMED_MODULE:
+                    /*
+                     * Entering in a `<module>` or `META-INF/versions-modular/<n>/<module>` subdirectory.
+                     * A module could have its own `META-INF` subdirectory, so we need to check again.
+                     */
+                    if (directory.endsWith(MetadataFiles.META_INF)) {
+                        role = DirectoryRole.META_INF;
+                        checkForManifest = true;
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+            }
+        }
+        /*
+         * Do not move this condition inside the `switch` block because `role` may have been modified.
+         * The `role` value is now the role of `directory`, not anymore the role of parent directory.
+         */
+        if (addDirectories && role == DirectoryRole.RESOURCES) {
+            currentFilesToArchive.add(directory, attributes, true);
+            /*
+             * Since we are skipping the whole directory, `postVisitDirectory(…)` will not be invoked.
+             * We must reset `currentFilesToArchive` and `currentTargetVersion` by an explicit call.
+             * This is important mostly after we added a whole `META-INF/versions/<n>` directory,
+             * otherwise base files visited afterwards (directory iteration order is unspecified)
+             * would be added to this version's file set instead of the base release.
+             */
+            resetToParentDirectoryState();
+            return FileVisitResult.SKIP_SUBTREE;
+        } else {
+            directoryRoles.addLast(role);
+            return FileVisitResult.CONTINUE;
+        }
+    }
+
+    /**
+     * Updates the {@code FileCollector} state after we finished to scan the content of a directory.
+     * The fields to update depend on which directory has been visited (module, version, <i>etc.</i>).
+     *
+     * @param directory the directory which has been traversed
+     * @param error the error that occurred while traversing the directory, or {@code null} if none
+     */
+    @Override
+    public FileVisitResult postVisitDirectory(final Path directory, final IOException error) throws IOException {
+        if (error != null) {
+            throw error;
+        }
+        switch (directoryRoles.removeLast()) {
+            case NAMED_MODULE:
+                // Exited the directory of a single module.
+                resetToPackageHierarchy();
+                break;
+
+            case ROOT:
+                break;
+
+            default:
+                resetToParentDirectoryState();
+        }
+        return FileVisitResult.CONTINUE;
+    }
+
+    /**
+     * Updates {@code FileCollector} to a state suitable to the parent of the directory that we finished to scan.
+     * Contrarily to {@link #postVisitDirectory(Path, IOException)}, this method expects the last element of
+     * {@link #directoryRoles} to describe the parent directory, not the directory that we finished to visit.
+     */
+    @SuppressWarnings("checkstyle:MissingSwitchDefault")
+    private void resetToParentDirectoryState() {
+        switch (directoryRoles.getLast()) {
+            case VERSIONS:
+            case VERSIONS_MODULAR:
+                // Exited the directory for one target Java release.
+                currentFilesToArchive = currentModule.baseRelease();
+                currentTargetVersion = null;
+                break;
+
+            case META_INF:
+                checkForManifest = true;
+                break;
+        }
+    }
+
+    /**
+     * Archives a single file if accepted by the matcher.
+     *
+     * @param file the file
+     * @param attributes the file's basic attributes
+     */
+    @Override
+    public FileVisitResult visitFile(final Path file, final BasicFileAttributes attributes) {
+        if (fileMatcher.matches(file)) {
+            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.add(file, attributes, false);
+            }
+        }
+        return FileVisitResult.CONTINUE;
+    }
+
+    /**
+     * 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}, then this method ensures that at least one archive
+     * remains even if that archive is empty.
+     *
+     * @param skipIfEmpty value of {@link AbstractJarMojo#skipIfEmpty}
+     */
+    public void prune(boolean skipIfEmpty) {
+        boolean isModuleHierarchy = !moduleHierarchy.isEmpty();
+        moduleHierarchy.values().forEach((archive) -> archive.prune(skipIfEmpty));
+        moduleHierarchy.values().removeIf(Archive::isEmpty);
+        packageHierarchy.prune(isModuleHierarchy || skipIfEmpty);
+    }
+
+    /**
+     * Moves, copies or ignores orphan files.
+     * An orphan file is a file which is not in any module when module hierarchy is used.
+     * For example, some Maven plugins may create files such as {@code META-INF/LICENSE},
+     * {@code META-INF/NOTICE} or {@code META-INF/DEPENDENCIES}. These files are not in
+     * the correct directory (they should be in a {@code "<module>/META-INF"} directory)
+     * because the plugin may not be aware of module hierarchy.
+     *
+     * <p>A possible strategy could be to copy the {@code LICENSE} and {@code NOTICE} files
+     * in each module, and ignore the {@code DEPENDENCIES} file because its content is not
+     * correct for a module. For now, we just log a warning an ignore.</p>
+     *
+     * <h4>Prerequisites</h4>
+     * The {@link #prune(boolean)} method should have been invoked once before to invoke this method.
+     *
+     * @return if this method ignored some files, the root directory of those files
+     */
+    Path handleOrphanFiles() {
+        if (moduleHierarchy.isEmpty() || packageHierarchy.isEmpty()) {
+            // Classpath project or module-project without orphan files. Nothing to do.
+            return null;
+        }
+        // TODO: we may want to copy LICENSE and NOTICE files here.
+        return packageHierarchy.discardAllFiles();
+    }
+
+    /**
+     * Writes all <abbr>JAR</abbr> files.
+     * If the project is multi-module, then this method returns the path to the generated parent <abbr>POM</abbr> file.
+     *
+     * <h4>Prerequisites</h4>
+     * The {@link #prune(boolean)} method should have been invoked once before to invoke this method.
+     *
+     * @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
+     * @throws IOException if an error occurred while reading or writing a manifest file
+     */
+    Path writeAllJARs(final ToolExecutor executor) throws IOException {
+        for (Archive module : moduleHierarchy.values()) {
+            executor.writeSingleJAR(this, module);
+        }
+        if (executor.pomDerivation != null) {
+            return executor.pomDerivation.writeParentPOM(packageHierarchy);
+        }
+        if (!packageHierarchy.isEmpty()) {
+            executor.writeSingleJAR(this, packageHierarchy);
+        }
+        return null;
+    }
+
+    /**
+     * {@return the paths to all root directories of modules in a module hierarchy}
+     * They are usually {@code target/classes/<module>} directories, but could also
+     * be sub-directories in the {@code META-INF/modular-versions/<n>/} directory.
+     * If the project does not use module hierarchy, then this method returns an empty list.
+     *
+     * <h4>Ignored package hierarchy</h4>
+     * Note that an empty list does not necessarily means that the <abbr>JAR</abbr> is not modular,
+     * as a modular <abbr>JAR</abbr> can also be built from package hierarchy. But we intentionally
+     * ignore the latter case because this method is used for deriving <abbr>POM</abbr> files, and
+     * we do not perform such derivation for projects organized in the classical Maven 3 way.
+     *
+     * <h4>Prerequisites</h4>
+     * The {@link #prune(boolean)} method should have been invoked once before to invoke this method.

Review Comment:
   Done.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3892024035


##########
src/main/java/org/apache/maven/plugins/jar/FileCollector.java:
##########
@@ -0,0 +1,496 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.PathMatcher;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayDeque;
+import java.util.Deque;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.services.PathMatcherFactory;
+
+/**
+ * Dispatch the files in the output directory into the <abbr>JAR</abbr> files to create.
+ * Instead of just archiving as-is the content of the output directory, this class separates
+ * the following subdirectories to the options listed below:
+ *
+ * <ul>
+ *   <li>The {@code META-INF/MANIFEST.MF} file will be given to the {@code --manifest} option.</li>
+ *   <li>Files in the following directories will be given to the {@code --release} option:
+ *     <ul>
+ *       <li>{@code META-INF/versions/}</li>
+ *       <li>{@code META-INF/versions-modular/<module>/}</li>
+ *       <li>{@code <module>/META-INF/versions/}</li>
+ *     </ul>
+ *   </li>
+ * </ul>
+ *
+ * The reason for using the options is that they allow the {@code jar} tool to perform additional verifications.
+ * For example, when using the {@code --release} option, {@code jar} verifies the <abbr>API</abbr> compatibility.
+ */
+final class FileCollector extends SimpleFileVisitor<Path> {
+    /**
+     * The file to check for deciding whether the <abbr>JAR</abbr> is modular.
+     */
+    static final String MODULE_DESCRIPTOR_FILE_NAME = "module-info.class";
+
+    /**
+     * The {@value} directory.
+     * This is part of <abbr>JAR</abbr> file specification.
+     */
+    private static final String VERSIONS = "versions";
+
+    /**
+     * The {@value} directory.
+     * This is Maven-specific.
+     */
+    private static final String VERSIONS_MODULAR = "versions-modular";
+
+    /**
+     * Context (logger, configuration) in which the <abbr>JAR</abbr> file are created.
+     */
+    private final ToolExecutor context;
+
+    /**
+     * Whether to detect multi-release <abbr>JAR</abbr> files.
+     * The default value is {@code true}.
+     *
+     * @see AbstractJarMojo#detectMultiReleaseJar
+     */
+    private final boolean detectMultiReleaseJar;
+
+    /**
+     * Combination of includes and excludes path matcher applied on files.
+     */
+    @Nonnull
+    private final PathMatcher fileMatcher;
+
+    /**
+     * Combination of includes and excludes path matcher applied on directories.
+     */
+    @Nonnull
+    private final PathMatcher directoryMatcher;
+
+    /**
+     * Whether the matchers accept all files and there is no need to sort the files.
+     * In such case, we can declare whole directories to the {@code jar} tool instead
+     * of scanning the directory tree ourselves.
+     */
+    private final boolean addDirectories;
+
+    /**
+     * Files found in the output directory when package hierarchy is used.
+     * At most one of {@code packageHierarchy} and {@link #moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Archive packageHierarchy;
+
+    /**
+     * Files found in the output directory when module hierarchy is used. Keys are module names.
+     * At most one of {@link #packageHierarchy} and {@code moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Map<String, Archive> moduleHierarchy;
+
+    /**
+     * The current module being archived. This field is updated every times that {@code FileCollector}
+     * enters in a new module directory.
+     */
+    @Nonnull
+    private Archive currentModule;
+
+    /**
+     * The module and target Java release currently being scanned. This field is updated every times that
+     * {@code FileCollector} enters in a new module directory or in a new target Java release for a given module.
+     */
+    @Nonnull
+    private Archive.FileSet currentFilesToArchive;
+
+    /**
+     * The current target Java release, or {@code null} if none.
+     */
+    @Nullable
+    private Runtime.Version currentTargetVersion;
+
+    /**
+     * Identification of the kinds of directories being traversed.
+     * The length of this list is the depth in the directory hierarchy.
+     * The last element identifies the type of the current directory.
+     */
+    private final Deque<DirectoryRole> directoryRoles;
+
+    /**
+     * Whether to check when a file is the {@code MANIFEST.MF} file.
+     * This is allowed only when scanning the content of a {@code META-INF} directory.
+     */
+    private boolean checkForManifest;
+
+    /**
+     * Creates a new file collector.
+     *
+     * @param mojo the <abbr>MOJO</abbr> from which to get the configuration
+     * @param context context (logger, configuration) in which the <abbr>JAR</abbr> file are created
+     * @param directory the base directory of the files to archive
+     */
+    FileCollector(AbstractJarMojo mojo, ToolExecutor context, Path directory, PathMatcherFactory matcherFactory) {
+        this.context = context;
+        detectMultiReleaseJar = mojo.detectMultiReleaseJar;
+        directoryRoles = new ArrayDeque<>();
+        fileMatcher = matcherFactory.createPathMatcher(directory, mojo.getIncludes(), mojo.getExcludes(), false);
+        directoryMatcher = matcherFactory.deriveDirectoryMatcher(fileMatcher);
+        addDirectories = !context.isReproducible()
+                && matcherFactory.isIncludesAll(fileMatcher)
+                && matcherFactory.isIncludesAll(directoryMatcher);
+        packageHierarchy = context.newArchive(null, null, directory);
+        moduleHierarchy = new LinkedHashMap<>();
+        resetToPackageHierarchy();
+    }
+
+    /**
+     * Resets this {@code FileCollector} to the state where a package hierarchy is presumed.
+     */
+    private void resetToPackageHierarchy() {
+        currentModule = packageHierarchy;
+        currentFilesToArchive = currentModule.baseRelease();
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a module.
+     * For an output generated by {@code javac} from a module source hierarchy,
+     * the directory name is guaranteed to be the module name.
+     *
+     * @param directory a {@code "<module>"} or {@code "META-INF/versions-modular/<module>"} directory
+     */
+    private void enterModuleDirectory(final Path directory) {
+        String moduleName = directory.getFileName().toString();
+        currentModule = moduleHierarchy.computeIfAbsent(
+                moduleName, (name) -> context.newArchive(name, currentTargetVersion, directory));
+        currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a target Java version.
+     * The {@code useDirectly} argument tells whether the content of this directory will be specified directly
+     * as the content to add in the <abbr>JAR</abbr> file. This argument should be {@code false} when there is
+     * another directory level (the module names) to process before to add content.
+     *
+     * @param directory a {@code "META-INF/versions/<n>"} or {@code "META-INF/versions-modular/<n>"} directory
+     * @param useDirectly whether the directory is {@code "META-INF/versions/<n>"}
+     * @return whether to skip the directory because of invalid version number
+     */
+    private boolean enterVersionDirectory(final Path directory, final boolean useDirectly) {
+        try {
+            currentTargetVersion = Runtime.Version.parse(directory.getFileName().toString());
+        } catch (IllegalArgumentException e) {
+            context.warnInvalidVersion(directory, e);
+            return true;
+        }
+        if (useDirectly) {
+            currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+        }
+        return false;
+    }
+
+    /**
+     * Determines if the given directory should be scanned for files to archive.
+     * This method may also update {@link #currentFilesToArchive} if it detects
+     * that we are entering in a new module or a new target Java release.
+     *
+     * @param directory the directory which will be traversed
+     * @param attributes the directory's basic attributes
+     */
+    @Override
+    @SuppressWarnings("checkstyle:MissingSwitchDefault")
+    public FileVisitResult preVisitDirectory(final Path directory, final BasicFileAttributes attributes)
+            throws IOException {
+        DirectoryRole role;
+        if (directoryRoles.isEmpty()) {
+            role = DirectoryRole.ROOT;
+        } else {
+            if (!directoryMatcher.matches(directory)) {
+                return FileVisitResult.SKIP_SUBTREE;
+            }
+            checkForManifest = false;
+            role = directoryRoles.getLast();
+            switch (role) {
+                case ROOT:
+                    /*
+                     * Entering in any subdirectory of `target/classes` (or other directory to archive).
+                     * We need to handle `META-INF` and modules in a special way, and archive the rest.
+                     */
+                    if (directory.endsWith(MetadataFiles.META_INF)) {
+                        role = DirectoryRole.META_INF;
+                        checkForManifest = true;
+                    } else if (Files.isRegularFile(directory.resolve(MODULE_DESCRIPTOR_FILE_NAME))) {
+                        role = DirectoryRole.NAMED_MODULE;
+                        enterModuleDirectory(directory);
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case META_INF:
+                    /*
+                     * Entering in a subdirectory of `META-INF` or `<module>/META-INF`. We will need to handle
+                     * `MANIFEST.MF`, `versions` and `versions-modular` in a special way, and archive the rest.
+                     */
+                    if (detectMultiReleaseJar && directory.endsWith(VERSIONS)) {
+                        role = DirectoryRole.VERSIONS;
+                    } else if (directory.endsWith(VERSIONS_MODULAR)) {
+                        if (!detectMultiReleaseJar) {
+                            // Used asked for no multi-release JAR.
+                            return FileVisitResult.SKIP_SUBTREE;
+                        }
+                        role = DirectoryRole.VERSIONS_MODULAR;
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case VERSIONS:
+                    /*
+                     * Entering in a `META-INF/versions/<n>/` directory for a specific target Java release.
+                     * May also be a `<module>/META-INF/versions/<n>/` directory, even if the latter is not
+                     * the layout generated by Maven Compiler Plugin.
+                     */
+                    if (enterVersionDirectory(directory, true)) {
+                        // An error occurred while parsing the version number.
+                        return FileVisitResult.SKIP_SUBTREE;
+                    }
+                    role = DirectoryRole.RESOURCES;
+                    break;
+
+                case VERSIONS_MODULAR:
+                    /*
+                     * Entering in a `META-INF/versions-modular/<n>/` directory for a specific target Java release.
+                     * That directory contains all modules for the version.
+                     */
+                    resetToPackageHierarchy(); // No module in particular yet.
+                    if (enterVersionDirectory(directory, false)) {
+                        // An error occurred while parsing the version number.
+                        return FileVisitResult.SKIP_SUBTREE;
+                    }
+                    role = DirectoryRole.MODULES;
+                    break;
+
+                case MODULES:
+                    /*
+                     * Entering in a `META-INF/versions-modular/<n>/<module>` directory.
+                     */
+                    enterModuleDirectory(directory);
+                    role = DirectoryRole.NAMED_MODULE;
+                    break;
+
+                case NAMED_MODULE:
+                    /*
+                     * Entering in a `<module>` or `META-INF/versions-modular/<n>/<module>` subdirectory.
+                     * A module could have its own `META-INF` subdirectory, so we need to check again.
+                     */
+                    if (directory.endsWith(MetadataFiles.META_INF)) {
+                        role = DirectoryRole.META_INF;
+                        checkForManifest = true;
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+            }
+        }
+        /*
+         * Do not move this condition inside the `switch` block because `role` may have been modified.
+         * The `role` value is now the role of `directory`, not anymore the role of parent directory.
+         */
+        if (addDirectories && role == DirectoryRole.RESOURCES) {
+            currentFilesToArchive.add(directory, attributes, true);
+            /*
+             * Since we are skipping the whole directory, `postVisitDirectory(…)` will not be invoked.
+             * We must reset `currentFilesToArchive` and `currentTargetVersion` by an explicit call.
+             * This is important mostly after we added a whole `META-INF/versions/<n>` directory,
+             * otherwise base files visited afterwards (directory iteration order is unspecified)
+             * would be added to this version's file set instead of the base release.
+             */
+            resetToParentDirectoryState();
+            return FileVisitResult.SKIP_SUBTREE;
+        } else {
+            directoryRoles.addLast(role);
+            return FileVisitResult.CONTINUE;
+        }
+    }
+
+    /**
+     * Updates the {@code FileCollector} state after we finished to scan the content of a directory.
+     * The fields to update depend on which directory has been visited (module, version, <i>etc.</i>).
+     *
+     * @param directory the directory which has been traversed
+     * @param error the error that occurred while traversing the directory, or {@code null} if none
+     */
+    @Override
+    public FileVisitResult postVisitDirectory(final Path directory, final IOException error) throws IOException {
+        if (error != null) {
+            throw error;
+        }
+        switch (directoryRoles.removeLast()) {
+            case NAMED_MODULE:
+                // Exited the directory of a single module.
+                resetToPackageHierarchy();
+                break;
+
+            case ROOT:
+                break;
+
+            default:
+                resetToParentDirectoryState();
+        }
+        return FileVisitResult.CONTINUE;
+    }
+
+    /**
+     * Updates {@code FileCollector} to a state suitable to the parent of the directory that we finished to scan.
+     * Contrarily to {@link #postVisitDirectory(Path, IOException)}, this method expects the last element of
+     * {@link #directoryRoles} to describe the parent directory, not the directory that we finished to visit.
+     */
+    @SuppressWarnings("checkstyle:MissingSwitchDefault")
+    private void resetToParentDirectoryState() {
+        switch (directoryRoles.getLast()) {
+            case VERSIONS:
+            case VERSIONS_MODULAR:
+                // Exited the directory for one target Java release.
+                currentFilesToArchive = currentModule.baseRelease();
+                currentTargetVersion = null;
+                break;
+
+            case META_INF:
+                checkForManifest = true;
+                break;
+        }
+    }
+
+    /**
+     * Archives a single file if accepted by the matcher.
+     *
+     * @param file the file
+     * @param attributes the file's basic attributes
+     */
+    @Override
+    public FileVisitResult visitFile(final Path file, final BasicFileAttributes attributes) {
+        if (fileMatcher.matches(file)) {
+            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.add(file, attributes, false);
+            }
+        }
+        return FileVisitResult.CONTINUE;
+    }
+
+    /**
+     * 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}, then this method ensures that at least one archive

Review Comment:
   Done



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3892013615


##########
src/main/java/org/apache/maven/plugins/jar/FileCollector.java:
##########
@@ -0,0 +1,496 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.PathMatcher;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayDeque;
+import java.util.Deque;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.services.PathMatcherFactory;
+
+/**
+ * Dispatch the files in the output directory into the <abbr>JAR</abbr> files to create.
+ * Instead of just archiving as-is the content of the output directory, this class separates
+ * the following subdirectories to the options listed below:
+ *
+ * <ul>
+ *   <li>The {@code META-INF/MANIFEST.MF} file will be given to the {@code --manifest} option.</li>
+ *   <li>Files in the following directories will be given to the {@code --release} option:
+ *     <ul>
+ *       <li>{@code META-INF/versions/}</li>
+ *       <li>{@code META-INF/versions-modular/<module>/}</li>
+ *       <li>{@code <module>/META-INF/versions/}</li>
+ *     </ul>
+ *   </li>
+ * </ul>
+ *
+ * The reason for using the options is that they allow the {@code jar} tool to perform additional verifications.
+ * For example, when using the {@code --release} option, {@code jar} verifies the <abbr>API</abbr> compatibility.
+ */
+final class FileCollector extends SimpleFileVisitor<Path> {
+    /**
+     * The file to check for deciding whether the <abbr>JAR</abbr> is modular.
+     */
+    static final String MODULE_DESCRIPTOR_FILE_NAME = "module-info.class";
+
+    /**
+     * The {@value} directory.
+     * This is part of <abbr>JAR</abbr> file specification.
+     */
+    private static final String VERSIONS = "versions";
+
+    /**
+     * The {@value} directory.
+     * This is Maven-specific.
+     */
+    private static final String VERSIONS_MODULAR = "versions-modular";
+
+    /**
+     * Context (logger, configuration) in which the <abbr>JAR</abbr> file are created.
+     */
+    private final ToolExecutor context;
+
+    /**
+     * Whether to detect multi-release <abbr>JAR</abbr> files.
+     * The default value is {@code true}.
+     *
+     * @see AbstractJarMojo#detectMultiReleaseJar
+     */
+    private final boolean detectMultiReleaseJar;
+
+    /**
+     * Combination of includes and excludes path matcher applied on files.
+     */
+    @Nonnull
+    private final PathMatcher fileMatcher;
+
+    /**
+     * Combination of includes and excludes path matcher applied on directories.
+     */
+    @Nonnull
+    private final PathMatcher directoryMatcher;
+
+    /**
+     * Whether the matchers accept all files and there is no need to sort the files.
+     * In such case, we can declare whole directories to the {@code jar} tool instead
+     * of scanning the directory tree ourselves.
+     */
+    private final boolean addDirectories;
+
+    /**
+     * Files found in the output directory when package hierarchy is used.
+     * At most one of {@code packageHierarchy} and {@link #moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Archive packageHierarchy;
+
+    /**
+     * Files found in the output directory when module hierarchy is used. Keys are module names.
+     * At most one of {@link #packageHierarchy} and {@code moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Map<String, Archive> moduleHierarchy;
+
+    /**
+     * The current module being archived. This field is updated every times that {@code FileCollector}
+     * enters in a new module directory.
+     */
+    @Nonnull
+    private Archive currentModule;
+
+    /**
+     * The module and target Java release currently being scanned. This field is updated every times that
+     * {@code FileCollector} enters in a new module directory or in a new target Java release for a given module.
+     */
+    @Nonnull
+    private Archive.FileSet currentFilesToArchive;
+
+    /**
+     * The current target Java release, or {@code null} if none.
+     */
+    @Nullable
+    private Runtime.Version currentTargetVersion;
+
+    /**
+     * Identification of the kinds of directories being traversed.
+     * The length of this list is the depth in the directory hierarchy.
+     * The last element identifies the type of the current directory.
+     */
+    private final Deque<DirectoryRole> directoryRoles;
+
+    /**
+     * Whether to check when a file is the {@code MANIFEST.MF} file.
+     * This is allowed only when scanning the content of a {@code META-INF} directory.
+     */
+    private boolean checkForManifest;
+
+    /**
+     * Creates a new file collector.
+     *
+     * @param mojo the <abbr>MOJO</abbr> from which to get the configuration
+     * @param context context (logger, configuration) in which the <abbr>JAR</abbr> file are created
+     * @param directory the base directory of the files to archive
+     */
+    FileCollector(AbstractJarMojo mojo, ToolExecutor context, Path directory, PathMatcherFactory matcherFactory) {
+        this.context = context;
+        detectMultiReleaseJar = mojo.detectMultiReleaseJar;
+        directoryRoles = new ArrayDeque<>();
+        fileMatcher = matcherFactory.createPathMatcher(directory, mojo.getIncludes(), mojo.getExcludes(), false);
+        directoryMatcher = matcherFactory.deriveDirectoryMatcher(fileMatcher);
+        addDirectories = !context.isReproducible()
+                && matcherFactory.isIncludesAll(fileMatcher)
+                && matcherFactory.isIncludesAll(directoryMatcher);
+        packageHierarchy = context.newArchive(null, null, directory);
+        moduleHierarchy = new LinkedHashMap<>();
+        resetToPackageHierarchy();
+    }
+
+    /**
+     * Resets this {@code FileCollector} to the state where a package hierarchy is presumed.
+     */
+    private void resetToPackageHierarchy() {
+        currentModule = packageHierarchy;
+        currentFilesToArchive = currentModule.baseRelease();
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a module.
+     * For an output generated by {@code javac} from a module source hierarchy,
+     * the directory name is guaranteed to be the module name.
+     *
+     * @param directory a {@code "<module>"} or {@code "META-INF/versions-modular/<module>"} directory
+     */
+    private void enterModuleDirectory(final Path directory) {
+        String moduleName = directory.getFileName().toString();
+        currentModule = moduleHierarchy.computeIfAbsent(
+                moduleName, (name) -> context.newArchive(name, currentTargetVersion, directory));
+        currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a target Java version.
+     * The {@code useDirectly} argument tells whether the content of this directory will be specified directly
+     * as the content to add in the <abbr>JAR</abbr> file. This argument should be {@code false} when there is
+     * another directory level (the module names) to process before to add content.
+     *
+     * @param directory a {@code "META-INF/versions/<n>"} or {@code "META-INF/versions-modular/<n>"} directory
+     * @param useDirectly whether the directory is {@code "META-INF/versions/<n>"}
+     * @return whether to skip the directory because of invalid version number
+     */
+    private boolean enterVersionDirectory(final Path directory, final boolean useDirectly) {
+        try {
+            currentTargetVersion = Runtime.Version.parse(directory.getFileName().toString());
+        } catch (IllegalArgumentException e) {
+            context.warnInvalidVersion(directory, e);
+            return true;
+        }
+        if (useDirectly) {
+            currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+        }
+        return false;
+    }
+
+    /**
+     * Determines if the given directory should be scanned for files to archive.
+     * This method may also update {@link #currentFilesToArchive} if it detects
+     * that we are entering in a new module or a new target Java release.
+     *
+     * @param directory the directory which will be traversed
+     * @param attributes the directory's basic attributes
+     */
+    @Override
+    @SuppressWarnings("checkstyle:MissingSwitchDefault")
+    public FileVisitResult preVisitDirectory(final Path directory, final BasicFileAttributes attributes)
+            throws IOException {
+        DirectoryRole role;
+        if (directoryRoles.isEmpty()) {
+            role = DirectoryRole.ROOT;
+        } else {
+            if (!directoryMatcher.matches(directory)) {
+                return FileVisitResult.SKIP_SUBTREE;
+            }
+            checkForManifest = false;
+            role = directoryRoles.getLast();
+            switch (role) {
+                case ROOT:
+                    /*
+                     * Entering in any subdirectory of `target/classes` (or other directory to archive).
+                     * We need to handle `META-INF` and modules in a special way, and archive the rest.
+                     */
+                    if (directory.endsWith(MetadataFiles.META_INF)) {
+                        role = DirectoryRole.META_INF;
+                        checkForManifest = true;
+                    } else if (Files.isRegularFile(directory.resolve(MODULE_DESCRIPTOR_FILE_NAME))) {
+                        role = DirectoryRole.NAMED_MODULE;
+                        enterModuleDirectory(directory);
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case META_INF:
+                    /*
+                     * Entering in a subdirectory of `META-INF` or `<module>/META-INF`. We will need to handle
+                     * `MANIFEST.MF`, `versions` and `versions-modular` in a special way, and archive the rest.
+                     */
+                    if (detectMultiReleaseJar && directory.endsWith(VERSIONS)) {
+                        role = DirectoryRole.VERSIONS;
+                    } else if (directory.endsWith(VERSIONS_MODULAR)) {
+                        if (!detectMultiReleaseJar) {
+                            // Used asked for no multi-release JAR.
+                            return FileVisitResult.SKIP_SUBTREE;
+                        }
+                        role = DirectoryRole.VERSIONS_MODULAR;
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case VERSIONS:
+                    /*
+                     * Entering in a `META-INF/versions/<n>/` directory for a specific target Java release.
+                     * May also be a `<module>/META-INF/versions/<n>/` directory, even if the latter is not
+                     * the layout generated by Maven Compiler Plugin.
+                     */
+                    if (enterVersionDirectory(directory, true)) {
+                        // An error occurred while parsing the version number.
+                        return FileVisitResult.SKIP_SUBTREE;
+                    }
+                    role = DirectoryRole.RESOURCES;
+                    break;
+
+                case VERSIONS_MODULAR:
+                    /*
+                     * Entering in a `META-INF/versions-modular/<n>/` directory for a specific target Java release.
+                     * That directory contains all modules for the version.
+                     */
+                    resetToPackageHierarchy(); // No module in particular yet.
+                    if (enterVersionDirectory(directory, false)) {
+                        // An error occurred while parsing the version number.
+                        return FileVisitResult.SKIP_SUBTREE;
+                    }
+                    role = DirectoryRole.MODULES;
+                    break;
+
+                case MODULES:
+                    /*
+                     * Entering in a `META-INF/versions-modular/<n>/<module>` directory.
+                     */
+                    enterModuleDirectory(directory);
+                    role = DirectoryRole.NAMED_MODULE;
+                    break;
+
+                case NAMED_MODULE:
+                    /*
+                     * Entering in a `<module>` or `META-INF/versions-modular/<n>/<module>` subdirectory.
+                     * A module could have its own `META-INF` subdirectory, so we need to check again.
+                     */
+                    if (directory.endsWith(MetadataFiles.META_INF)) {
+                        role = DirectoryRole.META_INF;
+                        checkForManifest = true;
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+            }
+        }
+        /*
+         * Do not move this condition inside the `switch` block because `role` may have been modified.
+         * The `role` value is now the role of `directory`, not anymore the role of parent directory.
+         */
+        if (addDirectories && role == DirectoryRole.RESOURCES) {
+            currentFilesToArchive.add(directory, attributes, true);
+            /*
+             * Since we are skipping the whole directory, `postVisitDirectory(…)` will not be invoked.
+             * We must reset `currentFilesToArchive` and `currentTargetVersion` by an explicit call.
+             * This is important mostly after we added a whole `META-INF/versions/<n>` directory,
+             * otherwise base files visited afterwards (directory iteration order is unspecified)
+             * would be added to this version's file set instead of the base release.
+             */
+            resetToParentDirectoryState();
+            return FileVisitResult.SKIP_SUBTREE;
+        } else {
+            directoryRoles.addLast(role);
+            return FileVisitResult.CONTINUE;
+        }
+    }
+
+    /**
+     * Updates the {@code FileCollector} state after we finished to scan the content of a directory.
+     * The fields to update depend on which directory has been visited (module, version, <i>etc.</i>).
+     *
+     * @param directory the directory which has been traversed
+     * @param error the error that occurred while traversing the directory, or {@code null} if none
+     */
+    @Override
+    public FileVisitResult postVisitDirectory(final Path directory, final IOException error) throws IOException {
+        if (error != null) {
+            throw error;
+        }
+        switch (directoryRoles.removeLast()) {
+            case NAMED_MODULE:
+                // Exited the directory of a single module.
+                resetToPackageHierarchy();
+                break;
+
+            case ROOT:
+                break;
+
+            default:
+                resetToParentDirectoryState();
+        }
+        return FileVisitResult.CONTINUE;
+    }
+
+    /**
+     * Updates {@code FileCollector} to a state suitable to the parent of the directory that we finished to scan.

Review Comment:
   Done



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3921799245


##########
src/main/java/org/apache/maven/plugins/jar/Archive.java:
##########
@@ -0,0 +1,655 @@
+/*
+ * 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.jar;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.TreeMap;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.Type;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.MojoException;
+
+/**
+ * Files or root directories to archive for a single module.
+ * A single instance of {@code Archive} can contain many directories for different target Java releases.
+ * Many instances of {@code Archive} can exist when archiving a multi-modules project.
+ */
+final class Archive {
+    /**
+     * Path to the <abbr>POM</abbr> file generated for this archive, or {@code null} if none.
+     * This is non-null only if module source hierarchy is used, in which case the dependencies
+     * declared in this file are the intersection of the project dependencies and the content of
+     * the {@code module-info.class} file.
+     */
+    @Nullable
+    Path pomFile;
+
+    /**
+     * The <var>JAR</var> file to create. Can be an existing file,
+     * in which case the file creation can be skipped if the file is still up-to-date.
+     */
+    @Nonnull
+    final Path jarFile;
+
+    /**
+     * A helper class for checking whether an existing <abbr>JAR</abbr> file is still up-to-date.
+     * This is null if there is no existing JAR file, or if we determined that the file is outdated.
+     */
+    private TimestampCheck existingJAR;
+
+    /**
+     * Name of the module being archived when the project is using module hierarchy.
+     * This is {@code null} if the project is using package hierarchy, either because it is a classical
+     * class-path project or because it is a single module compiled without using the module hierarchy.
+     * When using module source hierarchy, {@code javac} guarantees that the module name in the output
+     * directory is the name of the parent directory of {@code module-info.class}.
+     */
+    @Nullable
+    final String moduleName;
+
+    /**
+     * Path to {@code META-INF/MANIFEST.MF}, or {@code null} if none.
+     * If non-null, this value will be given to the {@code --manifest} option.
+     * The use of this option is preferable to adding {@code MANIFEST.MF} as an ordinary file.
+     *
+     * @see #setManifest(Path, boolean)
+     * @see #mergeManifest(Path, Manifest)
+     */
+    @Nullable
+    private Path manifest;
+
+    /**
+     * The Maven generated {@code pom.xml} and {@code pom.properties} files, or {@code null} if none.
+     * This first item must be the base directory where the files are located.
+     */
+    @Nullable
+    List<Path> mavenFiles;
+
+    /**
+     * Fully-qualified name of the main class, or {@code null} if none.
+     * This is the value to provide to the {@code --main-class} option.
+     */
+    private String mainClass;
+
+    /**
+     * Files or root directories to store in the <abbr>JAR</abbr> file for each target Java release
+     * other than the base release. Keys are the target Java release with {@code null} for the base
+     * release.
+     */
+    @Nonnull
+    private final NavigableMap<Runtime.Version, FileSet> filesetForRelease;
+
+    /**
+     * Files or root directories to archive for a single target Java release of a single module.
+     * The {@link Archive} enclosing must contain at least one instance of {@code FileSet} for
+     * the base release, and an arbitrary amount of other instances for other target releases.
+     */
+    final class FileSet {
+        /**
+         * The root directory of all files or directories to archive.
+         * This is the value to pass to the {@code -C} tool option.
+         */
+        @Nonnull
+        final Path directory;
+
+        /**
+         * The files or directories to include in the <var>JAR</var> file.
+         * Can be absolute paths or paths relative to {@link #directory}.
+         * It usually contains only the files or directories directly in
+         * the root {@linkplain #directory}, not in sub-directories.
+         */
+        @Nonnull
+        final List<Path> files;
+
+        /**
+         * Creates an initially empty set of files or directories for a specific target Java release.
+         *
+         * @param directory the base directory of the files or directories to archive
+         */
+        private FileSet(Path directory) {
+            this.directory = directory;
+            this.files = new ArrayList<>();
+        }
+
+        /**
+         * 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.
+         * The caller should use that common directory for logging a warning message.
+         *
+         * @param base base directory found by previous invocations of this method, or {@code null} if none
+         * @return common directory of discarded files
+         */
+        private Path discardAllFiles(Path base) {
+            for (Path file : files) {
+                if (base == null) {
+                    base = file.getParent();
+                } else {
+                    while (!file.startsWith(base)) {
+                        base = base.getParent();
+                        if (base == null) {
+                            break;
+                        }
+                    }
+                }
+            }
+            files.clear();
+            return base;
+        }
+
+        /**
+         * Adds the given path to the list of files or directories to archive.
+         * If the given path is a directory, then all children will be included.
+         * Children to exclude, if any, should be managed by {@link ExcludedFiles}.
+         *
+         * @param item a file or directory to archive
+         * @param attributes the file's basic attributes
+         * @param isDirectory whether the file is a directory
+         */
+        void add(Path item, BasicFileAttributes attributes, boolean isDirectory) {
+            TimestampCheck tc = existingJAR;
+            if (tc != null && tc.isUpdated(item, attributes, isDirectory)) {
+                existingJAR = null; // Signal that the existing file is outdated.
+            }
+            files.add(item);
+        }
+
+        /**
+         * Adds to the given list the arguments to provide to the "jar" tool for this version.
+         * The elements added to the list will be instances of {@link String} or {@link Path}.
+         *
+         * <h4>Note about the {@code -C} option</h4>
+         * This method repeats the {@code -C} option before each file.
+         * Our tests suggest that the first file after the directory specified by the {@code -C} option must
+         * be relative to that directory and all files after the first one must be prefixed by the directory
+         * which was specified in the {@code -C} option. This behavior is not very intuitive and replying on
+         * it can be fragile. Furthermore, it seems that the relativized file needs to be the shortest one,
+         * otherwise the {@code jar} tool rejects files after the first one with "names do not match".
+         * Which file is first depends on the unspecified directory-iteration order.
+         * Repeating the {@code -C} option for each file seems safer.
+         *
+         * @param addTo the list to add the arguments as {@link String} or {@link Path} instances to
+         * @param version the target Java release, or {@code null} for the base version of the <abbr>JAR</abbr> file
+         * @throws IllegalArgumentException if a path cannot be made relative to the base directory
+         */
+        private void arguments(List<Object> addTo, Runtime.Version version) {
+            if (files.isEmpty()) {
+                return;
+            }
+            if (version != null) {
+                addTo.add("--release");
+                addTo.add(version);
+            }
+            Path previous = null;
+            for (Path file : files) {
+                if (previous != null && file.startsWith(previous)) {
+                    // Already added a parent directory.
+                    continue;
+                }
+                previous = file;
+                file = directory.relativize(file);
+                if (file.getNameCount() <= 1 && file.toString().isEmpty()) {
+                    /*
+                     * The `-C` directory itself (e.g. a "META-INF/versions/<n>" directory added as a whole).
+                     * An empty file argument is invalid for the `jar` tool (some implementations reject it,
+                     * others silently misbehave), so archive the whole directory content with ".".
+                     */
+                    file = Path.of(".");
+                }
+                addTo.add("-C");
+                addTo.add(directory);
+                addTo.add(file);
+            }
+        }
+
+        /**
+         * {@return a string representation for debugging purposes}
+         */
+        @Override
+        public String toString() {
+            return getClass().getSimpleName() + '[' + directory.getFileName() + ": " + files.size() + " files]";
+        }
+    }
+
+    /**
+     * Creates an initially empty set of files or directories.
+     *
+     * @param jarFile path to the <abbr>JAR</abbr> file to create
+     * @param moduleName the module name if using module hierarchy, or {@code null} if using package hierarchy
+     * @param version the target Java release, or {@code null} for the base version
+     * @param directory the directory of the classes targeting the base Java release
+     * @param forceCreation whether to force a new <abbr>JAR</abbr> file even if the content seems unchanged
+     * @param logger where to send a warning if an error occurred while checking an existing <abbr>JAR</abbr> file
+     */
+    @SuppressWarnings("checkstyle:NeedBraces")
+    Archive(
+            final Path jarFile,
+            final String moduleName,
+            final Runtime.Version version,
+            final Path directory,
+            final boolean forceCreation,
+            final Log logger) {
+        this.jarFile = jarFile;
+        this.moduleName = moduleName;
+        filesetForRelease = new TreeMap<>((v1, v2) -> {
+            if (v1 == v2) return 0;
+            if (v1 == null) return -1;
+            if (v2 == null) return +1;
+            return v1.compareTo(v2);
+        });
+        filesetForRelease.put(version, new FileSet(directory));
+        if (!forceCreation && Files.isRegularFile(jarFile)) {
+            try {
+                existingJAR = new TimestampCheck(jarFile, directory, logger);
+            } catch (IOException e) {
+                // Ignore, we will regenerate the JAR file.
+                logger.warn(e);
+            }
+        }
+    }
+
+    /**
+     * {@return the files or directories to store in the <abbr>JAR</abbr> file for targeting the base Java release}
+     *
+     * @throws NoSuchElementException should not happen unless {@link #prune(boolean)} has been invoked
+     */
+    FileSet baseRelease() {
+        Map.Entry<Runtime.Version, FileSet> entry = filesetForRelease.firstEntry();
+        String message = null;
+        if (entry != null) {
+            Runtime.Version version = entry.getKey();
+            if (version == null) {
+                return entry.getValue();
+            }
+            message = "Expected base version but found version " + version;
+        }
+        throw new NoSuchElementException(message);
+    }
+
+    /**
+     * Returns the {@code module-info.class} files. Conceptually, there is at most once such file per module.

Review Comment:
   > It's arguable that this is easier to read.
   
   It emphases the symmetry. With code formatted as a table like below, we spot immediately if we have two -1 or two +1.
   
   ```java
   if (v1 == v2)   return  0;
   if (v1 == null) return -1;
   if (v2 == null) return +1;
   ```
   
   We brackets, the symmetry is easier to spot. Above table is admittedly small, but with larger tables it really help a lot in spotting bugs (from by personal experience). Furthermore, since the only instruction is `return`, there is no risk that we accidentally mix code that should have been inside with code that should have been outside the bracket.
   
   In Maven case, since checkstyle does not let me put more than one space, I cannot align the first line as in above example, which defeat a little bit the "tabular view" goal.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3921746873


##########
src/main/java/org/apache/maven/plugins/jar/Archive.java:
##########
@@ -0,0 +1,655 @@
+/*
+ * 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.jar;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.TreeMap;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.Type;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.MojoException;
+
+/**
+ * Files or root directories to archive for a single module.
+ * A single instance of {@code Archive} can contain many directories for different target Java releases.
+ * Many instances of {@code Archive} can exist when archiving a multi-modules project.
+ */
+final class Archive {
+    /**
+     * Path to the <abbr>POM</abbr> file generated for this archive, or {@code null} if none.
+     * This is non-null only if module source hierarchy is used, in which case the dependencies
+     * declared in this file are the intersection of the project dependencies and the content of
+     * the {@code module-info.class} file.
+     */
+    @Nullable
+    Path pomFile;
+
+    /**
+     * The <var>JAR</var> file to create. Can be an existing file,
+     * in which case the file creation can be skipped if the file is still up-to-date.
+     */
+    @Nonnull
+    final Path jarFile;
+
+    /**
+     * A helper class for checking whether an existing <abbr>JAR</abbr> file is still up-to-date.
+     * This is null if there is no existing JAR file, or if we determined that the file is outdated.
+     */
+    private TimestampCheck existingJAR;
+
+    /**
+     * Name of the module being archived when the project is using module hierarchy.
+     * This is {@code null} if the project is using package hierarchy, either because it is a classical
+     * class-path project or because it is a single module compiled without using the module hierarchy.
+     * When using module source hierarchy, {@code javac} guarantees that the module name in the output
+     * directory is the name of the parent directory of {@code module-info.class}.
+     */
+    @Nullable
+    final String moduleName;
+
+    /**
+     * Path to {@code META-INF/MANIFEST.MF}, or {@code null} if none.
+     * If non-null, this value will be given to the {@code --manifest} option.
+     * The use of this option is preferable to adding {@code MANIFEST.MF} as an ordinary file.
+     *
+     * @see #setManifest(Path, boolean)
+     * @see #mergeManifest(Path, Manifest)
+     */
+    @Nullable
+    private Path manifest;
+
+    /**
+     * The Maven generated {@code pom.xml} and {@code pom.properties} files, or {@code null} if none.
+     * This first item must be the base directory where the files are located.
+     */
+    @Nullable
+    List<Path> mavenFiles;
+
+    /**
+     * Fully-qualified name of the main class, or {@code null} if none.
+     * This is the value to provide to the {@code --main-class} option.
+     */
+    private String mainClass;
+
+    /**
+     * Files or root directories to store in the <abbr>JAR</abbr> file for each target Java release
+     * other than the base release. Keys are the target Java release with {@code null} for the base
+     * release.
+     */
+    @Nonnull
+    private final NavigableMap<Runtime.Version, FileSet> filesetForRelease;
+
+    /**
+     * Files or root directories to archive for a single target Java release of a single module.
+     * The {@link Archive} enclosing must contain at least one instance of {@code FileSet} for
+     * the base release, and an arbitrary amount of other instances for other target releases.
+     */
+    final class FileSet {
+        /**
+         * The root directory of all files or directories to archive.
+         * This is the value to pass to the {@code -C} tool option.
+         */
+        @Nonnull
+        final Path directory;
+
+        /**
+         * The files or directories to include in the <var>JAR</var> file.
+         * Can be absolute paths or paths relative to {@link #directory}.
+         * It usually contains only the files or directories directly in
+         * the root {@linkplain #directory}, not in sub-directories.
+         */
+        @Nonnull
+        final List<Path> files;
+
+        /**
+         * Creates an initially empty set of files or directories for a specific target Java release.
+         *
+         * @param directory the base directory of the files or directories to archive
+         */
+        private FileSet(Path directory) {
+            this.directory = directory;
+            this.files = new ArrayList<>();
+        }
+
+        /**
+         * 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.
+         * The caller should use that common directory for logging a warning message.
+         *
+         * @param base base directory found by previous invocations of this method, or {@code null} if none
+         * @return common directory of discarded files
+         */
+        private Path discardAllFiles(Path base) {
+            for (Path file : files) {
+                if (base == null) {
+                    base = file.getParent();
+                } else {
+                    while (!file.startsWith(base)) {
+                        base = base.getParent();
+                        if (base == null) {
+                            break;
+                        }
+                    }
+                }
+            }
+            files.clear();
+            return base;
+        }
+
+        /**
+         * Adds the given path to the list of files or directories to archive.
+         * If the given path is a directory, then all children will be included.
+         * Children to exclude, if any, should be managed by {@link ExcludedFiles}.
+         *
+         * @param item a file or directory to archive
+         * @param attributes the file's basic attributes
+         * @param isDirectory whether the file is a directory
+         */
+        void add(Path item, BasicFileAttributes attributes, boolean isDirectory) {
+            TimestampCheck tc = existingJAR;
+            if (tc != null && tc.isUpdated(item, attributes, isDirectory)) {
+                existingJAR = null; // Signal that the existing file is outdated.
+            }
+            files.add(item);
+        }
+
+        /**
+         * Adds to the given list the arguments to provide to the "jar" tool for this version.
+         * The elements added to the list will be instances of {@link String} or {@link Path}.
+         *
+         * <h4>Note about the {@code -C} option</h4>

Review Comment:
   They do. They are checked by `javadoc` which raise an error if the numbering is not correct. For example if you replace `<h4>` by `<h3>` or `<h5>`, javadoc will raise an error saying that `<h4>` was expected there. Furthermore, the text between `<h4>` and `</h4>` are added to the search bar in the top-right corner: the search will contain a _"Note about the -C option"_ item. Javadoc is clearly designed for working with header, even if it is not advised a lot.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#issuecomment-5526621799

   Last time I tried, using HTML markup not recognized by Javadoc really break the build. Not `mvn install` because it does not generate Javadoc (I we didn't enabled Javadoc check by `javac` - this option exists), but it breaks when using a Maven goals that generate HTML.


-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#issuecomment-5339574577

   @hboutemy, @elharo: about the issue of adding the missing directories while preserving deterministic file order, a workaround may be to add in the pull request a post-generation step where the JAR file is read and rewritten with entries added using `java.util.zip`. That step would be executed only when files were enumerated (as opposed to specifying the directory to the `jar` tool). I will try to do that during the weekend. I will also check for the other issue raised by @seregamorph (too many `target` directories created).
   
   Above proposal should preserve strict reproducible builds in the JAR plugin. For longer term, I still believe that bit-for-bit reproducible builds is too much and that we need _semantically_ reproducible builds, but this is another story for maybe a separated plugin. Thanks @laeubi for the link to Tycho. artifact comparator.
   
   Thanks @jaikiran for stepping in. The issue is that for creating a reproducible build with the `jar` tool, we need to enumerate explicitly all the `*.class` files and resources in order to enforce an order that does not depend on the file system. But the problems with enumerating files are:
   
   * We have to repeat the `-C` option for every file (not a blocking issue).
   * When specifying `foo/bar/X.class`,  the `jar` tool does not generate `foo/` and `foo/bar/` entries. It does if we specify the whole directory, but then the entry order is back to unspecified even if we are still enumerating the files in addition to the directories. While the absence of directory entries is legal according @pzygielo (thanks for the tip), it seems to be an issue with Spring.
   
   A possible `jar` tool evolution could be to specify a new option in replacement of `-C`. It could be, for example, `--change-dir`. The new option would behave in the same way as `-C` with two differences:
   
   * All files after `--change-dir` would be relative to the specified directory instead of only the first file.
   * Adding `foo/bar/X.class` implies adding `foo/` and `foo/bar/`.
   


-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#issuecomment-5314065644

   Thanks for the report. It seems to be caused by the following directory which does not exist:
   
   ```
   /Users/username/dev/acme/server2/server/data-migration/data-migration-impl-e2e-test/target
   ```
   
   We could create the `target` directory by the plugin. But can we assume that the `data-migration-impl-e2e-test` directory exists? I'm a little bit nervous in creating an arbitrarily depth chain of sub-directories because of higher risk of unintended writing on the user's machine.


-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#issuecomment-5570170185

   Hello @elharo. I applied the changes.


-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "rmannibucau (via GitHub)" <gi...@apache.org>.
rmannibucau commented on PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#issuecomment-5331656447

   > In my opinion, we should rather break the build than only issue a warning. However, that would hit many people hard when switching to M4/m-jar-p 4.x while still using JDK 17/18.
   
   +1, I'm in this case for a project and letting a not reproducible build go out hurts more than requesting a dev to do a "sdk install java whatever" in terms of impact


-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "laeubi (via GitHub)" <gi...@apache.org>.
laeubi commented on PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#issuecomment-5340417400

   I just wanted to note that directory entries are optional, so if spring relies on them to be present it would be better fixed there to work without it.


-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3891892392


##########
src/main/java/org/apache/maven/plugins/jar/AbstractJarMojo.java:
##########
@@ -207,167 +205,208 @@ protected final Log getLog() {
     protected abstract String getType();
 
     /**
-     * Returns the JAR file to generate, based on an optional classifier.
+     * {@return the scope of dependencies}
+     * It should be {@link PathScope#MAIN_COMPILE} or {@link PathScope#TEST_COMPILE}.
+     * Note that we use compile scope rather than runtime scope because dependencies
+     * cannot appear in {@code requires} statement if they didn't had compile scope.
+     */
+    protected abstract PathScope getDependencyScope();
+
+    /**
+     * {@return the JAR tool to use for archiving the code}
      *
-     * @param basedir the output directory
-     * @param resultFinalName the name of the JAR file
-     * @param classifier an optional classifier
-     * @return the file to generate
+     * @throws MojoException if no JAR tool was found
+     *
+     * @since 4.0.0-beta-2
      */
-    protected Path getJarFile(Path basedir, String resultFinalName, String classifier) {
-        Objects.requireNonNull(basedir, "basedir is not allowed to be null");
-        Objects.requireNonNull(resultFinalName, "finalName is not allowed to be null");
-        String fileName = resultFinalName + (hasClassifier(classifier) ? '-' + classifier : "") + ".jar";
-        return basedir.resolve(fileName);
+    protected ToolProvider getJarTool() throws MojoException {
+        return ToolProvider.findFirst(toolId).orElseThrow(() -> new MojoException("No such \"" + toolId + "\" tool."));
     }
 
     /**
-     * Generates the JAR.
+     * Returns the output time stamp or, as a fallback, the {@code SOURCE_DATE_EPOCH} environment variable.
+     * If the time stamp is expressed in seconds, it is converted to ISO 8601 format. Otherwise it is returned as-is.
      *
-     * @return the path to the created archive file
-     * @throws MojoException in case of an error
+     * @return the time stamp in presumed ISO 8601 format, or {@code null} if none
+     *
+     * @since 4.0.0-beta-2
      */
-    public Path createArchive() throws MojoException {
-        Path basedir = outputDirectory != null
-                ? outputDirectory
-                : Path.of(project.getBuild().getDirectory());
-        String resultFinalName =
-                finalName != null ? finalName : project.getBuild().getFinalName();
-        Path jarFile = getJarFile(basedir, resultFinalName, getClassifier());
-
-        FileSetManager fileSetManager = new FileSetManager();
-        FileSet jarContentFileSet = new FileSet();
-        jarContentFileSet.setDirectory(getClassesDirectory().toAbsolutePath().toString());
-        jarContentFileSet.setIncludes(Arrays.asList(getIncludes()));
-        jarContentFileSet.setExcludes(Arrays.asList(getExcludes()));
-
-        String[] includedFiles = fileSetManager.getIncludedFiles(jarContentFileSet);
-
-        if (detectMultiReleaseJar
-                && Arrays.stream(includedFiles)
-                        .anyMatch(
-                                p -> p.startsWith("META-INF" + File.separatorChar + "versions" + File.separatorChar))) {
-            getLog().debug("Adding 'Multi-Release: true' manifest entry.");
-            archive.addManifestEntry(Attributes.Name.MULTI_RELEASE.toString(), "true");
+    protected String getOutputTimestamp() {
+        String time = nullIfAbsent(outputTimestamp);
+        if (time == null) {
+            time = nullIfAbsent(System.getenv("SOURCE_DATE_EPOCH"));
+            if (time == null) {
+                return null;
+            }
         }
+        if (Runtime.version().feature() < ToolExecutor.JDK_SUPPORT_DATE) {
+            log.warn("Reproducible build requires Java " + ToolExecutor.JDK_SUPPORT_DATE + " or later.");
+            return null;
+        }
+        for (int i = time.length(); --i >= 0; ) {
+            char c = time.charAt(i);
+            if ((c < '0' || c > '9') && (i != 0 || c != '-')) {
+                return time;
+            }
+        }
+        return Instant.ofEpochSecond(Long.parseLong(time)).toString();
+    }
 
-        // May give false positives if the files is named as module descriptor
-        // but is not in the root of the archive or in the versioned area
-        // (and hence not actually a module descriptor).
-        // That is fine since the modular Jar archiver will gracefully
-        // handle such case.
-        // And also such case is unlikely to happen as file ending
-        // with "module-info.class" is unlikely to be included in Jar file
-        // unless it is a module descriptor.
-        boolean containsModuleDescriptor =
-                Arrays.stream(includedFiles).anyMatch(p -> p.endsWith(MODULE_DESCRIPTOR_FILE_NAME));
-
-        String archiverName = containsModuleDescriptor ? "mjar" : "jar";
+    /**
+     * {@return the patterns of files to include, or an empty list if no include pattern was specified}
+     */
+    protected List<String> getIncludes() {
+        return asList(includes);
+    }
 
-        MavenArchiver archiver = new MavenArchiver();
-        archiver.setCreatedBy("Maven JAR Plugin", "org.apache.maven.plugins", "maven-jar-plugin");
-        archiver.setBuildJdkSpecDefaultEntry(archive.getManifest().isAddBuildEnvironmentEntries());
-        archiver.setArchiver((JarArchiver) archivers.get(archiverName));
-        archiver.setOutputFile(jarFile.toFile());
+    /**
+     * {@return the patterns of files to exclude, or an empty list if no exclude pattern was specified}
+     */
+    protected List<String> getExcludes() {
+        return asList(excludes);
+    }
 
-        // configure for Reproducible Builds based on outputTimestamp value
-        archiver.configureReproducibleBuild(outputTimestamp);
+    /**
+     * Returns the output directory and ensures that the directory exists.
+     * The returned directory will be either {@link #outputDirectory} if non-null,
+     * or {@link org.apache.maven.api.model.Build#getDirectory()} otherwise.
+     *
+     * <p>The directory is usually {@code target} and should always exist since it is usually the output
+     * of the compiler plugin. If nevertheless the directory does not exist, then this method creates it.
+     * However, this method does not try to create the parent directory, which should be the Maven sub-project.</p>
+     *
+     * @return the directory containing the generated <abbr>JAR</abbr> files.
+     * @throws IOException if the output directory did not existed and could not be created
+     */
+    protected Path getOutputDirectory() throws IOException {
+        Path dir = outputDirectory;
+        if (dir == null) {
+            dir = Path.of(project.getBuild().getDirectory());
+        }
+        if (Files.notExists(dir)) {
+            dir = Files.createDirectory(dir);
+        }
+        return dir;
+    }
 
-        archive.setForced(forceCreation);
+    /**
+     * Returns the given elements as a list if non-null.
+     *
+     * @param elements the elements, or {@code null}
+     * @return the elements as a list, or {@code null} if the given array was null
+     */
+    private static List<String> asList(String[] elements) {
+        return (elements == null) ? List.of() : Arrays.asList(elements);
+    }
 
-        try {
-            Path contentDirectory = getClassesDirectory();
-            if (!Files.exists(contentDirectory)) {
-                if (!forceCreation) {
-                    getLog().warn("JAR will be empty - no content was marked for inclusion!");
-                }
-            } else {
-                archiver.getArchiver().addDirectory(contentDirectory.toFile(), getIncludes(), getExcludes());
+    /**
+     * Generates the <abbr>JAR</abbr> files.
+     * Map keys are module names or {@code null} if the project does not use module hierarchy.
+     * Values are (<var>type</var>, <var>path</var>) pairs associated with each module where
+     * <var>type</var> is {@code "pom"}, {@code "jar"} or {@code "test-jar"} and <var>path</var>
+     * is the path to the <abbr>POM</abbr> or <abbr>JAR</abbr> file.
+     *
+     * <p>Note that a null key does not necessarily means that the <abbr>JAR</abbr> is not modular.
+     * It only means that the project was not compiled with module hierarchy,
+     * i.e. {@code target/classes/} subdirectories having module names.
+     * A project can be compiled with package hierarchy and still be modular.</p>
+     *
+     * @return the paths to the created archive files
+     * @throws IOException if an error occurred while walking the file tree
+     * @throws MojoException if an error occurred while writing a <abbr>JAR</abbr> file
+     */
+    public Map<String, Map<String, Path>> createArchives() throws IOException, MojoException {
+        final Path classesDirectory = getClassesDirectory();
+        final boolean notExists = Files.notExists(classesDirectory);
+        if (notExists) {
+            if (forceCreation) {
+                log.warn("No JAR created because no content was marked for inclusion.");
+            }
+            if (skipIfEmpty) {
+                log.info(String.format("Skipping packaging of the %s.", getType()));
+                return Map.of();
             }
-
-            archiver.createArchive(session, project, archive);
-
-            return jarFile;
-        } catch (Exception e) {
-            // TODO: improve error handling
-            throw new MojoException("Error assembling JAR", e);
         }
+        archive.setForced(forceCreation);
+        // TODO: we want a null manifest if there is no <archive> configuration.
+        final var archiver = new MavenArchiver();
+        archiver.setCreatedBy("Maven JAR Plugin", "org.apache.maven.plugins", "maven-jar-plugin");
+        archiver.setBuildJdkSpecDefaultEntry(archive.getManifest().isAddBuildEnvironmentEntries());
+        var executor = new ToolExecutor(this, archiver.getManifest(session, project, archive), archive);
+        var files = new FileCollector(this, executor, classesDirectory, matcherFactory);
+        if (!notExists) {
+            Files.walkFileTree(classesDirectory, files);
+        }
+        files.prune(skipIfEmpty);
+        List<Path> moduleRoots = files.getModuleHierarchyRoots();
+        if (!moduleRoots.isEmpty()) {
+            executor.pomDerivation = new PomDerivation(this, moduleRoots);
+        }
+        return executor.writeAllJARs(files);
     }
 
     /**
-     * Generates the JAR.
+     * Generates the <abbr>JAR</abbr> file, then attaches the artifact.
      *
      * @throws MojoException in case of an error
      */
     @Override
+    @SuppressWarnings("UseSpecificCatch")
     public void execute() throws MojoException {
-        if (skipIfEmpty && isEmpty(getClassesDirectory())) {
-            getLog().info(String.format("Skipping packaging of the %s.", getType()));
-        } else {
-            Path jarFile = createArchive();
-
-            if (attach) {
-                ProducedArtifact artifact;
-                String classifier = getClassifier();
-                if (hasClassifier(classifier)) {
-                    artifact = session.createProducedArtifact(
-                            project.getGroupId(),
-                            project.getArtifactId(),
-                            project.getVersion(),
-                            classifier,
-                            null,
-                            getType());
-                } else {
-                    if (projectHasAlreadySetAnArtifact()) {
-                        throw new MojoException("You have to use a classifier "
-                                + "to attach supplemental artifacts to the project instead of replacing them.");
+        final Map<String, Map<String, Path>> artifactFiles;
+        try {
+            artifactFiles = createArchives();
+        } catch (MojoException e) {
+            throw e;
+        } catch (Exception e) {

Review Comment:
   True. In this case, the code was already doing a `catch (Exception)` before. I do not have a strong feeling on this one. And the alternative (enumerating exceptions, at the risk of missing one) is not so appealing neither.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3891966002


##########
src/main/java/org/apache/maven/plugins/jar/FileCollector.java:
##########
@@ -0,0 +1,496 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.PathMatcher;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayDeque;
+import java.util.Deque;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.services.PathMatcherFactory;
+
+/**
+ * Dispatch the files in the output directory into the <abbr>JAR</abbr> files to create.
+ * Instead of just archiving as-is the content of the output directory, this class separates
+ * the following subdirectories to the options listed below:
+ *
+ * <ul>
+ *   <li>The {@code META-INF/MANIFEST.MF} file will be given to the {@code --manifest} option.</li>
+ *   <li>Files in the following directories will be given to the {@code --release} option:
+ *     <ul>
+ *       <li>{@code META-INF/versions/}</li>
+ *       <li>{@code META-INF/versions-modular/<module>/}</li>
+ *       <li>{@code <module>/META-INF/versions/}</li>
+ *     </ul>
+ *   </li>
+ * </ul>
+ *
+ * The reason for using the options is that they allow the {@code jar} tool to perform additional verifications.
+ * For example, when using the {@code --release} option, {@code jar} verifies the <abbr>API</abbr> compatibility.
+ */
+final class FileCollector extends SimpleFileVisitor<Path> {
+    /**
+     * The file to check for deciding whether the <abbr>JAR</abbr> is modular.
+     */
+    static final String MODULE_DESCRIPTOR_FILE_NAME = "module-info.class";
+
+    /**
+     * The {@value} directory.
+     * This is part of <abbr>JAR</abbr> file specification.
+     */
+    private static final String VERSIONS = "versions";
+
+    /**
+     * The {@value} directory.
+     * This is Maven-specific.
+     */
+    private static final String VERSIONS_MODULAR = "versions-modular";
+
+    /**
+     * Context (logger, configuration) in which the <abbr>JAR</abbr> file are created.
+     */
+    private final ToolExecutor context;
+
+    /**
+     * Whether to detect multi-release <abbr>JAR</abbr> files.
+     * The default value is {@code true}.
+     *
+     * @see AbstractJarMojo#detectMultiReleaseJar
+     */
+    private final boolean detectMultiReleaseJar;
+
+    /**
+     * Combination of includes and excludes path matcher applied on files.
+     */
+    @Nonnull
+    private final PathMatcher fileMatcher;
+
+    /**
+     * Combination of includes and excludes path matcher applied on directories.
+     */
+    @Nonnull
+    private final PathMatcher directoryMatcher;
+
+    /**
+     * Whether the matchers accept all files and there is no need to sort the files.
+     * In such case, we can declare whole directories to the {@code jar} tool instead
+     * of scanning the directory tree ourselves.
+     */
+    private final boolean addDirectories;
+
+    /**
+     * Files found in the output directory when package hierarchy is used.
+     * At most one of {@code packageHierarchy} and {@link #moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Archive packageHierarchy;
+
+    /**
+     * Files found in the output directory when module hierarchy is used. Keys are module names.
+     * At most one of {@link #packageHierarchy} and {@code moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Map<String, Archive> moduleHierarchy;
+
+    /**
+     * The current module being archived. This field is updated every times that {@code FileCollector}
+     * enters in a new module directory.
+     */
+    @Nonnull
+    private Archive currentModule;
+
+    /**
+     * The module and target Java release currently being scanned. This field is updated every times that
+     * {@code FileCollector} enters in a new module directory or in a new target Java release for a given module.
+     */
+    @Nonnull
+    private Archive.FileSet currentFilesToArchive;
+
+    /**
+     * The current target Java release, or {@code null} if none.
+     */
+    @Nullable
+    private Runtime.Version currentTargetVersion;
+
+    /**
+     * Identification of the kinds of directories being traversed.
+     * The length of this list is the depth in the directory hierarchy.
+     * The last element identifies the type of the current directory.
+     */
+    private final Deque<DirectoryRole> directoryRoles;
+
+    /**
+     * Whether to check when a file is the {@code MANIFEST.MF} file.
+     * This is allowed only when scanning the content of a {@code META-INF} directory.
+     */
+    private boolean checkForManifest;
+
+    /**
+     * Creates a new file collector.
+     *
+     * @param mojo the <abbr>MOJO</abbr> from which to get the configuration
+     * @param context context (logger, configuration) in which the <abbr>JAR</abbr> file are created
+     * @param directory the base directory of the files to archive
+     */
+    FileCollector(AbstractJarMojo mojo, ToolExecutor context, Path directory, PathMatcherFactory matcherFactory) {
+        this.context = context;
+        detectMultiReleaseJar = mojo.detectMultiReleaseJar;
+        directoryRoles = new ArrayDeque<>();
+        fileMatcher = matcherFactory.createPathMatcher(directory, mojo.getIncludes(), mojo.getExcludes(), false);
+        directoryMatcher = matcherFactory.deriveDirectoryMatcher(fileMatcher);
+        addDirectories = !context.isReproducible()
+                && matcherFactory.isIncludesAll(fileMatcher)
+                && matcherFactory.isIncludesAll(directoryMatcher);
+        packageHierarchy = context.newArchive(null, null, directory);
+        moduleHierarchy = new LinkedHashMap<>();
+        resetToPackageHierarchy();
+    }
+
+    /**
+     * Resets this {@code FileCollector} to the state where a package hierarchy is presumed.
+     */
+    private void resetToPackageHierarchy() {
+        currentModule = packageHierarchy;
+        currentFilesToArchive = currentModule.baseRelease();
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a module.
+     * For an output generated by {@code javac} from a module source hierarchy,
+     * the directory name is guaranteed to be the module name.
+     *
+     * @param directory a {@code "<module>"} or {@code "META-INF/versions-modular/<module>"} directory
+     */
+    private void enterModuleDirectory(final Path directory) {
+        String moduleName = directory.getFileName().toString();
+        currentModule = moduleHierarchy.computeIfAbsent(
+                moduleName, (name) -> context.newArchive(name, currentTargetVersion, directory));
+        currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a target Java version.
+     * The {@code useDirectly} argument tells whether the content of this directory will be specified directly
+     * as the content to add in the <abbr>JAR</abbr> file. This argument should be {@code false} when there is
+     * another directory level (the module names) to process before to add content.
+     *
+     * @param directory a {@code "META-INF/versions/<n>"} or {@code "META-INF/versions-modular/<n>"} directory
+     * @param useDirectly whether the directory is {@code "META-INF/versions/<n>"}
+     * @return whether to skip the directory because of invalid version number
+     */
+    private boolean enterVersionDirectory(final Path directory, final boolean useDirectly) {
+        try {
+            currentTargetVersion = Runtime.Version.parse(directory.getFileName().toString());
+        } catch (IllegalArgumentException e) {
+            context.warnInvalidVersion(directory, e);
+            return true;
+        }
+        if (useDirectly) {
+            currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+        }
+        return false;
+    }
+
+    /**
+     * Determines if the given directory should be scanned for files to archive.
+     * This method may also update {@link #currentFilesToArchive} if it detects
+     * that we are entering in a new module or a new target Java release.
+     *
+     * @param directory the directory which will be traversed
+     * @param attributes the directory's basic attributes
+     */
+    @Override
+    @SuppressWarnings("checkstyle:MissingSwitchDefault")
+    public FileVisitResult preVisitDirectory(final Path directory, final BasicFileAttributes attributes)
+            throws IOException {
+        DirectoryRole role;
+        if (directoryRoles.isEmpty()) {
+            role = DirectoryRole.ROOT;
+        } else {
+            if (!directoryMatcher.matches(directory)) {
+                return FileVisitResult.SKIP_SUBTREE;
+            }
+            checkForManifest = false;
+            role = directoryRoles.getLast();
+            switch (role) {
+                case ROOT:
+                    /*
+                     * Entering in any subdirectory of `target/classes` (or other directory to archive).
+                     * We need to handle `META-INF` and modules in a special way, and archive the rest.
+                     */
+                    if (directory.endsWith(MetadataFiles.META_INF)) {
+                        role = DirectoryRole.META_INF;
+                        checkForManifest = true;
+                    } else if (Files.isRegularFile(directory.resolve(MODULE_DESCRIPTOR_FILE_NAME))) {
+                        role = DirectoryRole.NAMED_MODULE;
+                        enterModuleDirectory(directory);
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case META_INF:
+                    /*
+                     * Entering in a subdirectory of `META-INF` or `<module>/META-INF`. We will need to handle
+                     * `MANIFEST.MF`, `versions` and `versions-modular` in a special way, and archive the rest.
+                     */
+                    if (detectMultiReleaseJar && directory.endsWith(VERSIONS)) {
+                        role = DirectoryRole.VERSIONS;
+                    } else if (directory.endsWith(VERSIONS_MODULAR)) {
+                        if (!detectMultiReleaseJar) {
+                            // Used asked for no multi-release JAR.
+                            return FileVisitResult.SKIP_SUBTREE;
+                        }
+                        role = DirectoryRole.VERSIONS_MODULAR;
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case VERSIONS:
+                    /*
+                     * Entering in a `META-INF/versions/<n>/` directory for a specific target Java release.
+                     * May also be a `<module>/META-INF/versions/<n>/` directory, even if the latter is not

Review Comment:
   Done



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3891959393


##########
src/main/java/org/apache/maven/plugins/jar/DirectoryRole.java:
##########
@@ -0,0 +1,73 @@
+/*
+ * 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.jar;
+
+/**
+ * Directories that the archiver needs to handle in a special way.
+ */
+enum DirectoryRole {
+    /**
+     * The root directory. This is usually {@code "target/classes"}.
+     * The next locations can be {@link #META_INF}, {@link #NAMED_MODULE} or {@link #RESOURCES}.
+     */
+    ROOT,
+
+    /**
+     * The {@code "META-INF"} or {@code "<module>/META-INF"} directory.
+     * This is part of the <abbr>JAR</abbr> specification.
+     * The next locations can be {@link #VERSIONS} or {@link #VERSIONS_MODULAR}.
+     */
+    META_INF,
+
+    /**
+     * The {@code "META-INF/versions"} or {@code "<module>/META-INF/versions"} directory.
+     * This is part of the <abbr>JAR</abbr> specification, except the {@code <module>} prefix.
+     * The sub-directories are named according Java releases such as "21".
+     * The next location can only be {@link #RESOURCES}.
+     */
+    VERSIONS,
+
+    /**
+     * The Maven-specific {@code "META-INF/versions-modular"} directory.
+     * Note that {@code "<module>/META-INF/versions-modular"} is not forbidden, but does not make sense.
+     * The sub-directories are named according Java releases such as "21".
+     * The next location can only be {@link #MODULES}.
+     */
+    VERSIONS_MODULAR,
+
+    /**
+     * The Maven-specific {@code "META-INF/versions-modular"} directory.
+     * All sub-directories shall have the name of a Java module.
+     * The next location can only be {@link #NAMED_MODULE}.
+     */
+    MODULES,
+
+    /**
+     * The root of a single Java module in a module hierarchy.
+     * The name of this directory is the Java module name.
+     * The next location can only be {@link #RESOURCES}.
+     */
+    NAMED_MODULE,
+
+    /**
+     * The classes or other types of resources to include in a single archive.
+     * May also be other files in the {@code META-INF} directory.

Review Comment:
   Done



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3892027416


##########
src/main/java/org/apache/maven/plugins/jar/FileCollector.java:
##########
@@ -0,0 +1,496 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.PathMatcher;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayDeque;
+import java.util.Deque;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.services.PathMatcherFactory;
+
+/**
+ * Dispatch the files in the output directory into the <abbr>JAR</abbr> files to create.
+ * Instead of just archiving as-is the content of the output directory, this class separates
+ * the following subdirectories to the options listed below:
+ *
+ * <ul>
+ *   <li>The {@code META-INF/MANIFEST.MF} file will be given to the {@code --manifest} option.</li>
+ *   <li>Files in the following directories will be given to the {@code --release} option:
+ *     <ul>
+ *       <li>{@code META-INF/versions/}</li>
+ *       <li>{@code META-INF/versions-modular/<module>/}</li>
+ *       <li>{@code <module>/META-INF/versions/}</li>
+ *     </ul>
+ *   </li>
+ * </ul>
+ *
+ * The reason for using the options is that they allow the {@code jar} tool to perform additional verifications.
+ * For example, when using the {@code --release} option, {@code jar} verifies the <abbr>API</abbr> compatibility.
+ */
+final class FileCollector extends SimpleFileVisitor<Path> {
+    /**
+     * The file to check for deciding whether the <abbr>JAR</abbr> is modular.
+     */
+    static final String MODULE_DESCRIPTOR_FILE_NAME = "module-info.class";
+
+    /**
+     * The {@value} directory.
+     * This is part of <abbr>JAR</abbr> file specification.
+     */
+    private static final String VERSIONS = "versions";
+
+    /**
+     * The {@value} directory.
+     * This is Maven-specific.
+     */
+    private static final String VERSIONS_MODULAR = "versions-modular";
+
+    /**
+     * Context (logger, configuration) in which the <abbr>JAR</abbr> file are created.
+     */
+    private final ToolExecutor context;
+
+    /**
+     * Whether to detect multi-release <abbr>JAR</abbr> files.
+     * The default value is {@code true}.
+     *
+     * @see AbstractJarMojo#detectMultiReleaseJar
+     */
+    private final boolean detectMultiReleaseJar;
+
+    /**
+     * Combination of includes and excludes path matcher applied on files.
+     */
+    @Nonnull
+    private final PathMatcher fileMatcher;
+
+    /**
+     * Combination of includes and excludes path matcher applied on directories.
+     */
+    @Nonnull
+    private final PathMatcher directoryMatcher;
+
+    /**
+     * Whether the matchers accept all files and there is no need to sort the files.
+     * In such case, we can declare whole directories to the {@code jar} tool instead
+     * of scanning the directory tree ourselves.
+     */
+    private final boolean addDirectories;
+
+    /**
+     * Files found in the output directory when package hierarchy is used.
+     * At most one of {@code packageHierarchy} and {@link #moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Archive packageHierarchy;
+
+    /**
+     * Files found in the output directory when module hierarchy is used. Keys are module names.
+     * At most one of {@link #packageHierarchy} and {@code moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Map<String, Archive> moduleHierarchy;
+
+    /**
+     * The current module being archived. This field is updated every times that {@code FileCollector}
+     * enters in a new module directory.
+     */
+    @Nonnull
+    private Archive currentModule;
+
+    /**
+     * The module and target Java release currently being scanned. This field is updated every times that
+     * {@code FileCollector} enters in a new module directory or in a new target Java release for a given module.
+     */
+    @Nonnull
+    private Archive.FileSet currentFilesToArchive;
+
+    /**
+     * The current target Java release, or {@code null} if none.
+     */
+    @Nullable
+    private Runtime.Version currentTargetVersion;
+
+    /**
+     * Identification of the kinds of directories being traversed.
+     * The length of this list is the depth in the directory hierarchy.
+     * The last element identifies the type of the current directory.
+     */
+    private final Deque<DirectoryRole> directoryRoles;
+
+    /**
+     * Whether to check when a file is the {@code MANIFEST.MF} file.
+     * This is allowed only when scanning the content of a {@code META-INF} directory.
+     */
+    private boolean checkForManifest;
+
+    /**
+     * Creates a new file collector.
+     *
+     * @param mojo the <abbr>MOJO</abbr> from which to get the configuration
+     * @param context context (logger, configuration) in which the <abbr>JAR</abbr> file are created
+     * @param directory the base directory of the files to archive
+     */
+    FileCollector(AbstractJarMojo mojo, ToolExecutor context, Path directory, PathMatcherFactory matcherFactory) {
+        this.context = context;
+        detectMultiReleaseJar = mojo.detectMultiReleaseJar;
+        directoryRoles = new ArrayDeque<>();
+        fileMatcher = matcherFactory.createPathMatcher(directory, mojo.getIncludes(), mojo.getExcludes(), false);
+        directoryMatcher = matcherFactory.deriveDirectoryMatcher(fileMatcher);
+        addDirectories = !context.isReproducible()
+                && matcherFactory.isIncludesAll(fileMatcher)
+                && matcherFactory.isIncludesAll(directoryMatcher);
+        packageHierarchy = context.newArchive(null, null, directory);
+        moduleHierarchy = new LinkedHashMap<>();
+        resetToPackageHierarchy();
+    }
+
+    /**
+     * Resets this {@code FileCollector} to the state where a package hierarchy is presumed.
+     */
+    private void resetToPackageHierarchy() {
+        currentModule = packageHierarchy;
+        currentFilesToArchive = currentModule.baseRelease();
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a module.
+     * For an output generated by {@code javac} from a module source hierarchy,
+     * the directory name is guaranteed to be the module name.
+     *
+     * @param directory a {@code "<module>"} or {@code "META-INF/versions-modular/<module>"} directory
+     */
+    private void enterModuleDirectory(final Path directory) {
+        String moduleName = directory.getFileName().toString();
+        currentModule = moduleHierarchy.computeIfAbsent(
+                moduleName, (name) -> context.newArchive(name, currentTargetVersion, directory));
+        currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a target Java version.
+     * The {@code useDirectly} argument tells whether the content of this directory will be specified directly
+     * as the content to add in the <abbr>JAR</abbr> file. This argument should be {@code false} when there is
+     * another directory level (the module names) to process before to add content.
+     *
+     * @param directory a {@code "META-INF/versions/<n>"} or {@code "META-INF/versions-modular/<n>"} directory
+     * @param useDirectly whether the directory is {@code "META-INF/versions/<n>"}
+     * @return whether to skip the directory because of invalid version number
+     */
+    private boolean enterVersionDirectory(final Path directory, final boolean useDirectly) {
+        try {
+            currentTargetVersion = Runtime.Version.parse(directory.getFileName().toString());
+        } catch (IllegalArgumentException e) {
+            context.warnInvalidVersion(directory, e);
+            return true;
+        }
+        if (useDirectly) {
+            currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+        }
+        return false;
+    }
+
+    /**
+     * Determines if the given directory should be scanned for files to archive.
+     * This method may also update {@link #currentFilesToArchive} if it detects
+     * that we are entering in a new module or a new target Java release.
+     *
+     * @param directory the directory which will be traversed
+     * @param attributes the directory's basic attributes
+     */
+    @Override
+    @SuppressWarnings("checkstyle:MissingSwitchDefault")
+    public FileVisitResult preVisitDirectory(final Path directory, final BasicFileAttributes attributes)
+            throws IOException {
+        DirectoryRole role;
+        if (directoryRoles.isEmpty()) {
+            role = DirectoryRole.ROOT;
+        } else {
+            if (!directoryMatcher.matches(directory)) {
+                return FileVisitResult.SKIP_SUBTREE;
+            }
+            checkForManifest = false;
+            role = directoryRoles.getLast();
+            switch (role) {
+                case ROOT:
+                    /*
+                     * Entering in any subdirectory of `target/classes` (or other directory to archive).
+                     * We need to handle `META-INF` and modules in a special way, and archive the rest.
+                     */
+                    if (directory.endsWith(MetadataFiles.META_INF)) {
+                        role = DirectoryRole.META_INF;
+                        checkForManifest = true;
+                    } else if (Files.isRegularFile(directory.resolve(MODULE_DESCRIPTOR_FILE_NAME))) {
+                        role = DirectoryRole.NAMED_MODULE;
+                        enterModuleDirectory(directory);
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case META_INF:
+                    /*
+                     * Entering in a subdirectory of `META-INF` or `<module>/META-INF`. We will need to handle
+                     * `MANIFEST.MF`, `versions` and `versions-modular` in a special way, and archive the rest.
+                     */
+                    if (detectMultiReleaseJar && directory.endsWith(VERSIONS)) {
+                        role = DirectoryRole.VERSIONS;
+                    } else if (directory.endsWith(VERSIONS_MODULAR)) {
+                        if (!detectMultiReleaseJar) {
+                            // Used asked for no multi-release JAR.
+                            return FileVisitResult.SKIP_SUBTREE;
+                        }
+                        role = DirectoryRole.VERSIONS_MODULAR;
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case VERSIONS:
+                    /*
+                     * Entering in a `META-INF/versions/<n>/` directory for a specific target Java release.
+                     * May also be a `<module>/META-INF/versions/<n>/` directory, even if the latter is not
+                     * the layout generated by Maven Compiler Plugin.
+                     */
+                    if (enterVersionDirectory(directory, true)) {
+                        // An error occurred while parsing the version number.
+                        return FileVisitResult.SKIP_SUBTREE;
+                    }
+                    role = DirectoryRole.RESOURCES;
+                    break;
+
+                case VERSIONS_MODULAR:
+                    /*
+                     * Entering in a `META-INF/versions-modular/<n>/` directory for a specific target Java release.
+                     * That directory contains all modules for the version.
+                     */
+                    resetToPackageHierarchy(); // No module in particular yet.
+                    if (enterVersionDirectory(directory, false)) {
+                        // An error occurred while parsing the version number.
+                        return FileVisitResult.SKIP_SUBTREE;
+                    }
+                    role = DirectoryRole.MODULES;
+                    break;
+
+                case MODULES:
+                    /*
+                     * Entering in a `META-INF/versions-modular/<n>/<module>` directory.
+                     */
+                    enterModuleDirectory(directory);
+                    role = DirectoryRole.NAMED_MODULE;
+                    break;
+
+                case NAMED_MODULE:
+                    /*
+                     * Entering in a `<module>` or `META-INF/versions-modular/<n>/<module>` subdirectory.
+                     * A module could have its own `META-INF` subdirectory, so we need to check again.
+                     */
+                    if (directory.endsWith(MetadataFiles.META_INF)) {
+                        role = DirectoryRole.META_INF;
+                        checkForManifest = true;
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+            }
+        }
+        /*
+         * Do not move this condition inside the `switch` block because `role` may have been modified.
+         * The `role` value is now the role of `directory`, not anymore the role of parent directory.
+         */
+        if (addDirectories && role == DirectoryRole.RESOURCES) {
+            currentFilesToArchive.add(directory, attributes, true);
+            /*
+             * Since we are skipping the whole directory, `postVisitDirectory(…)` will not be invoked.
+             * We must reset `currentFilesToArchive` and `currentTargetVersion` by an explicit call.
+             * This is important mostly after we added a whole `META-INF/versions/<n>` directory,
+             * otherwise base files visited afterwards (directory iteration order is unspecified)
+             * would be added to this version's file set instead of the base release.
+             */
+            resetToParentDirectoryState();
+            return FileVisitResult.SKIP_SUBTREE;
+        } else {
+            directoryRoles.addLast(role);
+            return FileVisitResult.CONTINUE;
+        }
+    }
+
+    /**
+     * Updates the {@code FileCollector} state after we finished to scan the content of a directory.
+     * The fields to update depend on which directory has been visited (module, version, <i>etc.</i>).
+     *
+     * @param directory the directory which has been traversed
+     * @param error the error that occurred while traversing the directory, or {@code null} if none
+     */
+    @Override
+    public FileVisitResult postVisitDirectory(final Path directory, final IOException error) throws IOException {
+        if (error != null) {
+            throw error;
+        }
+        switch (directoryRoles.removeLast()) {
+            case NAMED_MODULE:
+                // Exited the directory of a single module.
+                resetToPackageHierarchy();
+                break;
+
+            case ROOT:
+                break;
+
+            default:
+                resetToParentDirectoryState();
+        }
+        return FileVisitResult.CONTINUE;
+    }
+
+    /**
+     * Updates {@code FileCollector} to a state suitable to the parent of the directory that we finished to scan.
+     * Contrarily to {@link #postVisitDirectory(Path, IOException)}, this method expects the last element of
+     * {@link #directoryRoles} to describe the parent directory, not the directory that we finished to visit.
+     */
+    @SuppressWarnings("checkstyle:MissingSwitchDefault")
+    private void resetToParentDirectoryState() {
+        switch (directoryRoles.getLast()) {
+            case VERSIONS:
+            case VERSIONS_MODULAR:
+                // Exited the directory for one target Java release.
+                currentFilesToArchive = currentModule.baseRelease();
+                currentTargetVersion = null;
+                break;
+
+            case META_INF:
+                checkForManifest = true;
+                break;
+        }
+    }
+
+    /**
+     * Archives a single file if accepted by the matcher.
+     *
+     * @param file the file
+     * @param attributes the file's basic attributes
+     */
+    @Override
+    public FileVisitResult visitFile(final Path file, final BasicFileAttributes attributes) {
+        if (fileMatcher.matches(file)) {
+            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.add(file, attributes, false);
+            }
+        }
+        return FileVisitResult.CONTINUE;
+    }
+
+    /**
+     * 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}, then this method ensures that at least one archive
+     * remains even if that archive is empty.
+     *
+     * @param skipIfEmpty value of {@link AbstractJarMojo#skipIfEmpty}
+     */
+    public void prune(boolean skipIfEmpty) {
+        boolean isModuleHierarchy = !moduleHierarchy.isEmpty();
+        moduleHierarchy.values().forEach((archive) -> archive.prune(skipIfEmpty));
+        moduleHierarchy.values().removeIf(Archive::isEmpty);
+        packageHierarchy.prune(isModuleHierarchy || skipIfEmpty);
+    }
+
+    /**
+     * Moves, copies or ignores orphan files.
+     * An orphan file is a file which is not in any module when module hierarchy is used.
+     * For example, some Maven plugins may create files such as {@code META-INF/LICENSE},
+     * {@code META-INF/NOTICE} or {@code META-INF/DEPENDENCIES}. These files are not in
+     * the correct directory (they should be in a {@code "<module>/META-INF"} directory)
+     * because the plugin may not be aware of module hierarchy.
+     *
+     * <p>A possible strategy could be to copy the {@code LICENSE} and {@code NOTICE} files
+     * in each module, and ignore the {@code DEPENDENCIES} file because its content is not
+     * correct for a module. For now, we just log a warning an ignore.</p>

Review Comment:
   Right, fixed.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3892085640


##########
src/main/java/org/apache/maven/plugins/jar/TimestampCheck.java:
##########
@@ -0,0 +1,237 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.nio.file.attribute.FileTime;
+import java.util.Collection;
+import java.util.Enumeration;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+
+import org.apache.maven.api.plugin.Log;
+
+/**
+ * Checks file timestamps in order to determine if anything changed compared to an existing <abbr>JAR</abbr> file.
+ * This class may scan directories, but only if they have not already been visited by {@link FileCollector}.
+ * Note that the latter can occur only if {@link FileCollector} has no {@code PathMatcher}.

Review Comment:
   Done.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3892092443


##########
src/main/java/org/apache/maven/plugins/jar/TimestampCheck.java:
##########
@@ -0,0 +1,237 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.nio.file.attribute.FileTime;
+import java.util.Collection;
+import java.util.Enumeration;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+
+import org.apache.maven.api.plugin.Log;
+
+/**
+ * Checks file timestamps in order to determine if anything changed compared to an existing <abbr>JAR</abbr> file.
+ * This class may scan directories, but only if they have not already been visited by {@link FileCollector}.
+ * Note that the latter can occur only if {@link FileCollector} has no {@code PathMatcher}.
+ * Therefore, this class uses no {@code PathMatcher} neither.
+ *
+ * <h2>Ignore files</h2>
+ * The {@code META-INF/MANIFEST.MF} file and the {@code META-INF/maven/} directory are ignored.
+ * See {@link #isIgnored(Path)} for the rational.
+ */
+final class TimestampCheck extends SimpleFileVisitor<Path> {
+    /**
+     * The base directory of archived files.
+     */
+    private final Path classesDir;
+
+    /**
+     * Path to the existing <abbr>JAR</abbr> file.
+     */
+    private final Path jarFile;
+
+    /**
+     * The last modified time of the <abbr>JAR</abbr> file.
+     */
+    private final FileTime jarFileTime;
+
+    /**
+     * Where to send non-fatal error messages.
+     */
+    private final Log logger;
+
+    /**
+     * Entries of the <abbr>JAR</abbr> file. Note that getting elements from this enumeration can be costly.
+     * Therefore, we do not fetch all elements in advance but only when needed.

Review Comment:
   Done.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3921874143


##########
src/main/java/org/apache/maven/plugins/jar/Archive.java:
##########
@@ -0,0 +1,655 @@
+/*
+ * 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.jar;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.TreeMap;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.Type;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.MojoException;
+
+/**
+ * Files or root directories to archive for a single module.
+ * A single instance of {@code Archive} can contain many directories for different target Java releases.
+ * Many instances of {@code Archive} can exist when archiving a multi-modules project.
+ */
+final class Archive {
+    /**
+     * Path to the <abbr>POM</abbr> file generated for this archive, or {@code null} if none.
+     * This is non-null only if module source hierarchy is used, in which case the dependencies
+     * declared in this file are the intersection of the project dependencies and the content of
+     * the {@code module-info.class} file.
+     */
+    @Nullable
+    Path pomFile;
+
+    /**
+     * The <var>JAR</var> file to create. Can be an existing file,
+     * in which case the file creation can be skipped if the file is still up-to-date.
+     */
+    @Nonnull
+    final Path jarFile;
+
+    /**
+     * A helper class for checking whether an existing <abbr>JAR</abbr> file is still up-to-date.
+     * This is null if there is no existing JAR file, or if we determined that the file is outdated.
+     */
+    private TimestampCheck existingJAR;
+
+    /**
+     * Name of the module being archived when the project is using module hierarchy.
+     * This is {@code null} if the project is using package hierarchy, either because it is a classical
+     * class-path project or because it is a single module compiled without using the module hierarchy.
+     * When using module source hierarchy, {@code javac} guarantees that the module name in the output
+     * directory is the name of the parent directory of {@code module-info.class}.
+     */
+    @Nullable
+    final String moduleName;
+
+    /**
+     * Path to {@code META-INF/MANIFEST.MF}, or {@code null} if none.
+     * If non-null, this value will be given to the {@code --manifest} option.
+     * The use of this option is preferable to adding {@code MANIFEST.MF} as an ordinary file.
+     *
+     * @see #setManifest(Path, boolean)
+     * @see #mergeManifest(Path, Manifest)
+     */
+    @Nullable
+    private Path manifest;
+
+    /**
+     * The Maven generated {@code pom.xml} and {@code pom.properties} files, or {@code null} if none.
+     * This first item must be the base directory where the files are located.
+     */
+    @Nullable
+    List<Path> mavenFiles;
+
+    /**
+     * Fully-qualified name of the main class, or {@code null} if none.
+     * This is the value to provide to the {@code --main-class} option.
+     */
+    private String mainClass;
+
+    /**
+     * Files or root directories to store in the <abbr>JAR</abbr> file for each target Java release
+     * other than the base release. Keys are the target Java release with {@code null} for the base
+     * release.
+     */
+    @Nonnull
+    private final NavigableMap<Runtime.Version, FileSet> filesetForRelease;
+
+    /**
+     * Files or root directories to archive for a single target Java release of a single module.
+     * The {@link Archive} enclosing must contain at least one instance of {@code FileSet} for
+     * the base release, and an arbitrary amount of other instances for other target releases.
+     */
+    final class FileSet {
+        /**
+         * The root directory of all files or directories to archive.
+         * This is the value to pass to the {@code -C} tool option.
+         */
+        @Nonnull
+        final Path directory;
+
+        /**
+         * The files or directories to include in the <var>JAR</var> file.
+         * Can be absolute paths or paths relative to {@link #directory}.
+         * It usually contains only the files or directories directly in
+         * the root {@linkplain #directory}, not in sub-directories.
+         */
+        @Nonnull
+        final List<Path> files;
+
+        /**
+         * Creates an initially empty set of files or directories for a specific target Java release.
+         *
+         * @param directory the base directory of the files or directories to archive
+         */
+        private FileSet(Path directory) {
+            this.directory = directory;
+            this.files = new ArrayList<>();
+        }
+
+        /**
+         * 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.
+         * The caller should use that common directory for logging a warning message.
+         *
+         * @param base base directory found by previous invocations of this method, or {@code null} if none
+         * @return common directory of discarded files
+         */
+        private Path discardAllFiles(Path base) {
+            for (Path file : files) {
+                if (base == null) {
+                    base = file.getParent();
+                } else {
+                    while (!file.startsWith(base)) {
+                        base = base.getParent();
+                        if (base == null) {
+                            break;
+                        }
+                    }
+                }
+            }
+            files.clear();
+            return base;
+        }
+
+        /**
+         * Adds the given path to the list of files or directories to archive.
+         * If the given path is a directory, then all children will be included.
+         * Children to exclude, if any, should be managed by {@link ExcludedFiles}.
+         *
+         * @param item a file or directory to archive
+         * @param attributes the file's basic attributes
+         * @param isDirectory whether the file is a directory
+         */
+        void add(Path item, BasicFileAttributes attributes, boolean isDirectory) {
+            TimestampCheck tc = existingJAR;
+            if (tc != null && tc.isUpdated(item, attributes, isDirectory)) {
+                existingJAR = null; // Signal that the existing file is outdated.
+            }
+            files.add(item);
+        }
+
+        /**
+         * Adds to the given list the arguments to provide to the "jar" tool for this version.
+         * The elements added to the list will be instances of {@link String} or {@link Path}.
+         *
+         * <h4>Note about the {@code -C} option</h4>
+         * This method repeats the {@code -C} option before each file.
+         * Our tests suggest that the first file after the directory specified by the {@code -C} option must
+         * be relative to that directory and all files after the first one must be prefixed by the directory
+         * which was specified in the {@code -C} option. This behavior is not very intuitive and replying on
+         * it can be fragile. Furthermore, it seems that the relativized file needs to be the shortest one,
+         * otherwise the {@code jar} tool rejects files after the first one with "names do not match".
+         * Which file is first depends on the unspecified directory-iteration order.
+         * Repeating the {@code -C} option for each file seems safer.
+         *
+         * @param addTo the list to add the arguments as {@link String} or {@link Path} instances to
+         * @param version the target Java release, or {@code null} for the base version of the <abbr>JAR</abbr> file
+         * @throws IllegalArgumentException if a path cannot be made relative to the base directory
+         */
+        private void arguments(List<Object> addTo, Runtime.Version version) {
+            if (files.isEmpty()) {
+                return;
+            }
+            if (version != null) {
+                addTo.add("--release");
+                addTo.add(version);
+            }
+            Path previous = null;
+            for (Path file : files) {
+                if (previous != null && file.startsWith(previous)) {
+                    // Already added a parent directory.
+                    continue;
+                }
+                previous = file;
+                file = directory.relativize(file);
+                if (file.getNameCount() <= 1 && file.toString().isEmpty()) {
+                    /*
+                     * The `-C` directory itself (e.g. a "META-INF/versions/<n>" directory added as a whole).
+                     * An empty file argument is invalid for the `jar` tool (some implementations reject it,
+                     * others silently misbehave), so archive the whole directory content with ".".
+                     */
+                    file = Path.of(".");
+                }
+                addTo.add("-C");
+                addTo.add(directory);
+                addTo.add(file);
+            }
+        }
+
+        /**
+         * {@return a string representation for debugging purposes}
+         */
+        @Override
+        public String toString() {
+            return getClass().getSimpleName() + '[' + directory.getFileName() + ": " + files.size() + " files]";
+        }
+    }
+
+    /**
+     * Creates an initially empty set of files or directories.
+     *
+     * @param jarFile path to the <abbr>JAR</abbr> file to create
+     * @param moduleName the module name if using module hierarchy, or {@code null} if using package hierarchy
+     * @param version the target Java release, or {@code null} for the base version
+     * @param directory the directory of the classes targeting the base Java release
+     * @param forceCreation whether to force a new <abbr>JAR</abbr> file even if the content seems unchanged
+     * @param logger where to send a warning if an error occurred while checking an existing <abbr>JAR</abbr> file
+     */
+    @SuppressWarnings("checkstyle:NeedBraces")
+    Archive(
+            final Path jarFile,
+            final String moduleName,
+            final Runtime.Version version,
+            final Path directory,
+            final boolean forceCreation,
+            final Log logger) {
+        this.jarFile = jarFile;
+        this.moduleName = moduleName;
+        filesetForRelease = new TreeMap<>((v1, v2) -> {
+            if (v1 == v2) return 0;
+            if (v1 == null) return -1;
+            if (v2 == null) return +1;
+            return v1.compareTo(v2);
+        });
+        filesetForRelease.put(version, new FileSet(directory));
+        if (!forceCreation && Files.isRegularFile(jarFile)) {
+            try {
+                existingJAR = new TimestampCheck(jarFile, directory, logger);
+            } catch (IOException e) {
+                // Ignore, we will regenerate the JAR file.
+                logger.warn(e);
+            }
+        }
+    }
+
+    /**
+     * {@return the files or directories to store in the <abbr>JAR</abbr> file for targeting the base Java release}
+     *
+     * @throws NoSuchElementException should not happen unless {@link #prune(boolean)} has been invoked
+     */
+    FileSet baseRelease() {
+        Map.Entry<Runtime.Version, FileSet> entry = filesetForRelease.firstEntry();
+        String message = null;
+        if (entry != null) {
+            Runtime.Version version = entry.getKey();
+            if (version == null) {
+                return entry.getValue();
+            }
+            message = "Expected base version but found version " + version;
+        }
+        throw new NoSuchElementException(message);
+    }
+
+    /**
+     * Returns the {@code module-info.class} files. Conceptually, there is at most once such file per module.
+     * However, more than one file can exist if additional files are provided for additional Java releases.
+     * This method returns only the files that exist.
+     *
+     * @return all {@code module-info.class} files found for all target Java releases
+     */
+    public List<Path> moduleInfoFiles() {
+        var files = new ArrayList<Path>();
+        filesetForRelease.values().forEach((release) -> {
+            Path file = release.directory.resolve(FileCollector.MODULE_DESCRIPTOR_FILE_NAME);
+            if (Files.isRegularFile(file)) {
+                files.add(file);
+            }
+        });
+        return files;
+    }
+
+    /**
+     * Discards all files in this archive, normally because those files are not in any module.
+     * This method returns a common parent directory for all the files that were discarded.
+     * The caller should use that common directory for logging a warning message.
+     *
+     * @return common directory of discarded files, or {@code null} if none
+     */
+    Path discardAllFiles() {
+        Path base = null;
+        for (FileSet release : filesetForRelease.values()) {
+            base = release.discardAllFiles(base);
+        }
+        filesetForRelease.clear();
+        return base;
+    }
+
+    /**
+     * Removes all empty file sets 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}, then this method ensures that at least one file set
+     * remains even if that file set is empty.
+     *
+     * @param skipIfEmpty value of {@link AbstractJarMojo#skipIfEmpty}
+     */
+    public void prune(final boolean skipIfEmpty) {
+        FileSet keep = (skipIfEmpty || isEmpty())
+                ? null
+                : filesetForRelease.firstEntry().getValue();
+        filesetForRelease.values().removeIf((fs) -> fs.files.isEmpty());
+        Iterator<Map.Entry<Runtime.Version, FileSet>> it =
+                filesetForRelease.entrySet().iterator();
+        if (it.hasNext()) {
+            Map.Entry<Runtime.Version, FileSet> first = it.next();
+            if (first.getKey() == null) {
+                return; // Already contains an entry for the base version, nothing to do.
+            }
+            keep = first.getValue();
+            it.remove();
+        }
+        if (keep != null) {
+            filesetForRelease.put(null, keep);
+        }
+    }
+
+    /**
+     * {@return whether this archive has nothing to archive}
+     * This method can return {@code false} even when there is zero file to archive.
+     * It can happen if {@link AbstractJarMojo#skipIfEmpty} is {@code false}. In such case, the
+     * "empty" <abbr>JAR</abbr> file will still contain at {@code META-INF/MANIFEST.MF} file.
+     *
+     * <h4>Prerequisites</h4>
+     * The {@link #prune(boolean)} method should be invoked before this method for accurate result.
+     */
+    public boolean isEmpty() {
+        return filesetForRelease.isEmpty();
+    }
+
+    /**
+     * Checks whether the <abbr>JAR</abbr> file already exists and can be reused.
+     * This method verifies that the <abbr>JAR</abbr> file contains all the files to archive,
+     * contains no extra file, and no file to archive is newer than the <abbr>JAR</abbr> file.

Review Comment:
   Done.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3949105555


##########
src/main/java/org/apache/maven/plugins/jar/ExcludedFiles.java:
##########
@@ -0,0 +1,146 @@
+/*
+ * 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.jar;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardCopyOption;
+import java.util.List;
+
+/**
+ * A list of files to temporarily move outside the directory to package in a <abbr>JAR</abbr> archive.
+ * This class is needed when the {@link AbstractJarMojo} configuration has include or exclude filters.
+ * Excluded files are temporarily moved outside the directory to archive.
+ * We move these files for making possible to specify the whole directory to the {@code jar} tool.
+ * This approach is used instead of enumerating files in arguments given to the {@code jar} tool because
+ * such enumeration cannot contain directory entries (otherwise the whole directory would be included).
+ * Some software such as Spring applications component scan relies on the presence of directory entries.
+ */
+final class ExcludedFiles implements Closeable {
+    /**
+     * The paths of files or directories to temporarily move in another directory.
+     */
+    private final Path[] original;
+
+    /**
+     * The paths where files or directories were moved.
+     * For each index <var>i</var>, the original path of {@code moved[i]} was {@code original[i]}.
+     */
+    private final Path[] moved;
+
+    /**
+     * Temporary directory which will contain the {@code moved} files.
+     * It should be a parent directory of {@link #original} files for
+     * increasing the chances that it is on the same file system.
+     */
+    private final Path temporaryDirectory;
+
+    /**
+     * Index of the first path which is a directory instead of a file.
+     * All paths before this index in the {@link #original} and {@link #moved} arrays are files.
+     * All paths at this index and after this index are directories.
+     */
+    private final int indexOfFirstDirectory;
+
+    /**
+     * Creates a new list of files to move in a temporary directory.
+     *
+     * @param directory the directory which was scanned for files to include in the <abbr>JAR</abbr>
+     * @param excludedFiles paths of files to temporarily move in another directory
+     * @param excludedDirectories paths of directories to temporarily move in another directory
+     * @throws IOException if an error occurred while creating the temporary directory.
+     */
+    ExcludedFiles(Path directory, List<Path> excludedFiles, List<Path> excludedDirectories) throws IOException {
+        indexOfFirstDirectory = excludedFiles.size();

Review Comment:
   Yes, the files are moved back to their original locations in a `finally` block, and all these moves are applied in the `target` directory only. We move the files to exclude because in the majority of cases, there is none. If any, I suspect that it would be only a few. By contrast, moving the files to include would move almost everything.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3949379669


##########
src/test/java/org/apache/maven/plugins/jar/ArchiveTest.java:
##########
@@ -0,0 +1,257 @@
+/*
+ * 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.jar;
+
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Unit tests for {@link Archive}, focused on the two behaviours that are otherwise only
+ * exercised by integration tests whose outcome depends on the (unspecified) filesystem
+ * directory-iteration order, and therefore pass on some platforms while failing on others.
+ */
+class ArchiveTest {
+
+    /**
+     * Creates an {@code Archive} suitable for a unit test. {@code forceCreation = true} skips the
+     * existing-JAR timestamp check, so the (here {@code null}) logger is never dereferenced.
+     */
+    private static Archive archive(String moduleName, Runtime.Version version, Path directory) {
+        return new Archive(directory.resolve("out.jar"), moduleName, version, directory, true, null);
+    }
+
+    /**
+     * Creates a manifest with the main class attribute set to the given value.
+     *
+     * @param value value of the main class attribute
+     * @return a new manifest with the given attribute value
+     */
+    private static Manifest manifestWithMainClass(String value) {
+        Manifest m = new Manifest();
+        Attributes attributes = m.getMainAttributes();
+        attributes.put(Attributes.Name.MANIFEST_VERSION, "1.0");
+        attributes.put(Attributes.Name.MAIN_CLASS, value);
+        return m;
+    }
+
+    /**
+     * Returns the value of the main class attribute.
+     *
+     * @param m the manifest from which to get the value
+     * @return the main class attribute value, or {@code null} if none
+     */
+    private static Object mainClassOf(Manifest m) {
+        return m.getMainAttributes().get(Attributes.Name.MAIN_CLASS);
+    }
+
+    /**
+     * Verifies that {@link Archive#setMainClass(Manifest)} takes ownership for a module-qualified
+     * {@code "module/Class"} main class.
+     *
+     * The {@code "foo.bar/"} prefix in this test (the module name) is a Maven extension.
+     * The standard <abbr>JAR</abbr> specification accepts only the {@code "foo.MainFile"} class name.
+     */
+    @Test
+    void owningModuleClaimsMainClassAndRemovesItFromManifest() {
+        Archive owner = archive("foo.bar", null, Path.of("."));
+        Manifest m = manifestWithMainClass("foo.bar/foo.MainFile");
+        // The owner keeps the main class (emitted via --main-class) ...
+        assertTrue(owner.setMainClass(m));
+        // ... and the raw `module/Class` value is removed from the written manifest.
+        assertNull(mainClassOf(m));
+    }
+
+    /**
+     * Verifies that {@link Archive#setMainClass(Manifest)} does <em>not</em> take ownership of
+     * a module-qualified {@code "module/Class"} main class when the module name does not match.
+     * The {@code "foo.bar/"} prefix in this test (the module name) is a Maven extension.
+     * The standard <abbr>JAR</abbr> specification accepts only the {@code "foo.MainFile"} class name.
+     */
+    @Test
+    void nonOwningModuleRejectsMainClass() {
+        Archive nonOwner = archive("foo.bar.more", null, Path.of("."));
+        Manifest m = manifestWithMainClass("foo.bar/foo.MainFile");
+        assertFalse(nonOwner.setMainClass(m));
+        assertNull(mainClassOf(m));
+    }
+
+    /**
+     * Tests that which module keeps the main class does not depend on processing order.
+     * {@link ToolExecutor} gives each module a <em>copy</em> of the shared plugin manifest;
+     * this pins that the owning module (and only it) keeps the main class in either order,
+     * and that the shared manifest is never consumed.
+     */
+    @Test
+    void mainClassAssignmentIsIndependentOfModuleOrder() {
+        assertOwnership("foo.bar", "foo.bar.more", true); // owner processed first
+        assertOwnership("foo.bar.more", "foo.bar", false); // non-owner processed first
+    }
+
+    /**
+     * Helper method for {@link #mainClassAssignmentIsIndependentOfModuleOrder()}.
+     * Asserts that {@link Archive#setMainClass(Manifest)} returns {@code true}
+     * for the owner and {@code false} for the other module.
+     *
+     * <p>The {@code "foo.bar/"} prefix in this test (the module name) is a Maven extension.
+     * The standard <abbr>JAR</abbr> specification accepts only the {@code "foo.MainFile"} class name.
+     * This extension is used by the plugin for identifying in which <abbr>JAR</abbr> file to add this
+     * {@code Main-Class} manifest entry.</p>
+     */
+    private static void assertOwnership(String first, String second, boolean ownerIsFirst) {
+        final Path path = Path.of(".");
+        final Manifest shared = manifestWithMainClass("foo.bar/foo.MainFile");
+        final Manifest m1 = new Manifest(shared);
+        final Manifest m2 = new Manifest(shared);
+        assertEquals(ownerIsFirst, archive(first, null, path).setMainClass(m1));
+        assertEquals(!ownerIsFirst, archive(second, null, path).setMainClass(m2));

Review Comment:
   Replaced `!ownerIsFirst` by an `ownerIsSecond` variable just to make it clear.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3950091334


##########
src/main/java/org/apache/maven/plugins/jar/ExcludedFiles.java:
##########
@@ -0,0 +1,146 @@
+/*
+ * 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.jar;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardCopyOption;
+import java.util.List;
+
+/**
+ * A list of files to temporarily move outside the directory to package in a <abbr>JAR</abbr> archive.
+ * This class is needed when the {@link AbstractJarMojo} configuration has include or exclude filters.
+ * Excluded files are temporarily moved outside the directory to archive.
+ * We move these files for making possible to specify the whole directory to the {@code jar} tool.
+ * This approach is used instead of enumerating files in arguments given to the {@code jar} tool because
+ * such enumeration cannot contain directory entries (otherwise the whole directory would be included).
+ * Some software such as Spring applications component scan relies on the presence of directory entries.
+ */
+final class ExcludedFiles implements Closeable {
+    /**
+     * The paths of files or directories to temporarily move in another directory.
+     */
+    private final Path[] original;
+
+    /**
+     * The paths where files or directories were moved.
+     * For each index <var>i</var>, the original path of {@code moved[i]} was {@code original[i]}.
+     */
+    private final Path[] moved;
+
+    /**
+     * Temporary directory which will contain the {@code moved} files.
+     * It should be a parent directory of {@link #original} files for
+     * increasing the chances that it is on the same file system.
+     */
+    private final Path temporaryDirectory;
+
+    /**
+     * Index of the first path which is a directory instead of a file.
+     * All paths before this index in the {@link #original} and {@link #moved} arrays are files.
+     * All paths at this index and after this index are directories.
+     */
+    private final int indexOfFirstDirectory;
+
+    /**
+     * Creates a new list of files to move in a temporary directory.
+     *
+     * @param directory the directory which was scanned for files to include in the <abbr>JAR</abbr>
+     * @param excludedFiles paths of files to temporarily move in another directory
+     * @param excludedDirectories paths of directories to temporarily move in another directory
+     * @throws IOException if an error occurred while creating the temporary directory.
+     */
+    ExcludedFiles(Path directory, List<Path> excludedFiles, List<Path> excludedDirectories) throws IOException {
+        indexOfFirstDirectory = excludedFiles.size();

Review Comment:
   There is no special treatment for `.git` and `.DS_Store`. If users want to exclude them, they need an explicit `excludes` configuration. These directories would then be handled as any other files or directories to exclude, by temporarily moving them. However, a presence of `.git` would be surprising since it would imply the versioning of the `target` directory, and I would not expect a `.DS_Store` to be created after a `mvn clean`, unless user navigates in `target` through the MacOS UI before the JAR plugin had the time to execute.
   
   When moving, we can move a full directory in one operation. When copying, we need to walk through the whole directory tree. This is more costly. Even if we move instead of copying, moving the files to include would be costly compared to the current approach if 95% of the files are included. I don't know if the impact would be noticeable however, but I believe that the cumulative effect in millions of projects may save a couple of CO₂ tons.
   
   P.S. if we wanted to exclude the `.git` and `.DS_Store` directories by default, it would be just one `boolean` argument value to change from `false` to `true` at line 186 of `FileCollector`. The current value is `false` because it matches the behaviour of version 3.x of the plugin. We could change this behaviour, but I suggest to do that in a separated commit as a way to document behavioural change when we can do that easily.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "laeubi (via GitHub)" <gi...@apache.org>.
laeubi commented on PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#issuecomment-5351497629

   > So the same sources produce **different manifest bytes on different JDK distributions**
   
   I wanted to note here that (binary) reproducible builds are not guaranteeing anyways between different JDK versions and vendors as they could provide different byte codes.
   
   Apart from that, supplying the manifest directly would be the safest choice (also for the future) and thats why I think generation of files should be independent from packaging a jar:
   
   - https://github.com/apache/maven-jar-plugin/issues/586
   
   Apart from that, having the validation of MR-jars baked into the jar tool is from my opinion a design flaw and actually what we aim here if I understand correctly, so if the `JarOutputStream` would have this support this would not only benefit maven but also others as this verification can then be reused see for reference here:
   
   - https://github.com/eclipse-jdt/eclipse.jdt.core/issues/4274
   
   so if anyone is in contact with the JDK team it would be great to bring this to their attention as it would avoid people doing duplicate work an/or workarounds where a programmatic solution would be superior.


-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#issuecomment-5395040822

   > I might add the actual JDK version since reproducible builds require the same toolchain for now.
   
   Are we requiring toolchain? I thought that we were betting on different JDKs producing the same bytecode when used with the same `--release` version (which seems a fragile assumption).
   
   > For the record, I do not think "semantically reproducible builds" are a thing. Byte-per-byte comparison is the only thing that works.
   
   For the security goal, I have not yet seen a technical argument explaining why semantically reproducible builds would not work. On the contrary, I think that it is _more_ secure than strictly reproducible builds for the [reason given above](https://github.com/apache/maven-jar-plugin/pull/508#issuecomment-5353734439).
   
   In addition of security goal, it seems that there is also a caching goal. It has been argued that Docker images use hash-code for caching JAR files. This is a more difficult case and may be a reason to keep strictly reproducible builds as an option, but not necessarily a reason for makes it the default if semantically reproducible builds can be guaranteed.


-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3844036040


##########
src/main/java/org/apache/maven/plugins/jar/Archive.java:
##########
@@ -0,0 +1,692 @@
+/*
+ * 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.jar;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.TreeMap;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.Type;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.MojoException;
+
+/**
+ * Files or root directories to archive for a single module.
+ * A single instance of {@code Archive} may contain many directories for different target Java releases.
+ * Many instances of {@code Archive} may exist when archiving a multi-modules project.
+ */
+final class Archive {
+    /**
+     * Whether to repeat the {@code -C} option before each file.
+     * Doing so makes the command-line very verbose while the documentation of
+     * <a href="https://docs.oracle.com/en/java/javase/25/docs/specs/man/jar.html">The jar Command</a>
+     * gives the impression that this option can be provided only once.
+     * However, our tests suggest that the first file after the directory specified by the {@code -C} option
+     * must be relative to that directory and all files after the first one must be prefixed by the directory
+     * which was specified in the {@code -C} option. This behavior is not documented, but we couldn't get the
+     * {@code jar} tool to work otherwise (except by repeating {@code -C} before each file).
+     * Furthermore, it seems that the relativized file needs to be the shortest one,
+     * otherwise the {@code jar} tool rejects files after the first one with "names do not match".
+     * Which file is first depends on the unspecified directory-iteration order.
+     *
+     * <p>If this flag is {@code true}, the plugin repeats {@code -C} before each file.
+     * This flag should be set to {@code false} if a future version of the {@code jar}
+     * tool allows to specify {@code -C} only once.</p>
+     *
+     * <p><b>Historical note:</b> we also tried to relativize only the first file after {@code -C}
+     * and keep all subsequent files as absolute. It works, but because we have to repeat the directory
+     * in the file name, it saves only 3 or 4 characters per file compared to repeating {@code -C}.</p>
+     */
+    private static final boolean REPEAT_C = true;
+
+    /**
+     * Path to the <abbr>POM</abbr> file generated for this archive, or {@code null} if none.
+     * This is non-null only if module source hierarchy is used, in which case the dependencies
+     * declared in this file are the intersection of the project dependencies and the content of
+     * the {@code module-info.class} file.
+     */
+    @Nullable
+    Path pomFile;
+
+    /**
+     * The <var>JAR</var> file to create. May be an existing file,
+     * in which case the file creation may be skipped if the file is still up-to-date.
+     */
+    @Nonnull
+    final Path jarFile;
+
+    /**
+     * A helper class for checking whether an existing <abbr>JAR</abbr> file is still up-to-date.
+     * This is null if there is no existing JAR file, or if we determined that the file is outdated.
+     */
+    private TimestampCheck existingJAR;
+
+    /**
+     * Name of the module being archived when the project is using module hierarchy.
+     * This is {@code null} if the project is using package hierarchy, either because it is a classical
+     * class-path project or because it is a single module compiled without using the module hierarchy.
+     * When using module source hierarchy, {@code javac} guarantees that the module name in the output
+     * directory is the name of the parent directory of {@code module-info.class}.
+     */
+    @Nullable
+    final String moduleName;
+
+    /**
+     * Path to {@code META-INF/MANIFEST.MF}, or {@code null} if none.
+     * If non-null, this value will be given to the {@code --manifest} option.
+     * The use of this option is preferable to adding {@code MANIFEST.MF} as an ordinary file.
+     *
+     * @see #setManifest(Path, boolean)
+     * @see #mergeManifest(Path, Manifest)
+     */
+    @Nullable
+    private Path manifest;
+
+    /**
+     * The Maven generated {@code pom.xml} and {@code pom.properties} files, or {@code null} if none.
+     * This first item shall be the base directory where the files are located.
+     */
+    @Nullable
+    List<Path> mavenFiles;
+
+    /**
+     * Fully-qualified name of the main class, or {@code null} if none.
+     * This is the value to provide to the {@code --main-class} option.
+     */
+    private String mainClass;
+
+    /**
+     * Files or root directories to store in the <abbr>JAR</abbr> file for each target Java release
+     * other than the base release. Keys are the target Java release with {@code null} for the base
+     * release.
+     */
+    @Nonnull
+    private final NavigableMap<Runtime.Version, FileSet> filesetForRelease;
+
+    /**
+     * Files or root directories to archive for a single target Java release of a single module.
+     * The {@link Archive} enclosing shall contain at least one instance of {@code FileSet} for
+     * the base release, and an arbitrary amount of other instances for other target releases.
+     */
+    final class FileSet {
+        /**
+         * A comparator for sorting paths in a reproducible order.
+         * This comparator assumes that all paths are relative to the same base directory (this is not verified).
+         * Note: we do not use {@link Path#compareTo(Path)} because the Javadoc said that it is platform dependent.
+         */
+        private static final Comparator<Path> REPRODUCIBLE_ORDER = (p1, p2) -> {
+            final int c1 = p1.getNameCount();
+            final int c2 = p2.getNameCount();
+            final int c = Math.min(c1, c2);
+            for (int i = 0; i < c; i++) {
+                String n1 = p1.getName(i).toString();
+                String n2 = p2.getName(i).toString();
+                int r = n1.compareTo(n2); // Case-sensitive comparison on all platforms.
+                if (r != 0) {
+                    return r;
+                }
+            }
+            return c1 - c2;
+        };
+
+        /**
+         * The root directory of all files or directories to archive.
+         * This is the value to pass to the {@code -C} tool option.
+         */
+        @Nonnull
+        final Path directory;
+
+        /**
+         * The files or directories to include in the <var>JAR</var> file.
+         * May be absolute paths or paths relative to {@link #directory}.
+         */
+        @Nonnull
+        final List<Path> files;
+
+        /**
+         * Creates an initially empty set of files or directories for a specific target Java release.
+         *
+         * @param directory the base directory of the files or directories to archive
+         */
+        private FileSet(Path directory) {
+            this.directory = directory;
+            this.files = new ArrayList<>();
+        }
+
+        /**
+         * 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.
+         * The caller should use that common directory for logging a warning message.
+         *
+         * @param base base directory found by previous invocations of this method, or {@code null} if none
+         * @return common directory of discarded files
+         */
+        private Path discardAllFiles(Path base) {
+            for (Path file : files) {
+                file = directory.resolve(file);
+                if (base == null) {
+                    base = file.getParent();
+                } else {
+                    while (!file.startsWith(base)) {
+                        base = base.getParent();
+                        if (base == null) {
+                            break;
+                        }
+                    }
+                }
+            }
+            files.clear();
+            return base;
+        }
+
+        /**
+         * Adds the given path to the list of files or directories to archive.
+         * This method may store a relative path instead of the absolute path.
+         *
+         * @param item a file or directory to archive
+         * @param attributes the file's basic attributes
+         * @param isDirectory whether the file is a directory
+         * @throws IllegalArgumentException if the given path cannot be made relative to the base directory
+         */
+        void add(Path item, BasicFileAttributes attributes, boolean isDirectory) {
+            TimestampCheck tc = existingJAR;
+            if (tc != null && tc.isUpdated(item, attributes, isDirectory)) {
+                existingJAR = null; // Signal that the existing file is outdated.
+            }
+            item = directory.relativize(item);
+            if (item.getNameCount() <= 1 && item.toString().isEmpty()) {
+                /*
+                 * The item is the `-C` directory itself (e.g. a `META-INF/versions/<n>` directory
+                 * added as a whole). An empty file argument is invalid for the `jar` tool
+                 * (some implementations reject it, others silently misbehave),
+                 * so archive the whole directory content with ".".
+                 */
+                item = Path.of(".");
+            }
+            files.add(item);
+        }
+
+        /**
+         * Adds to the given list the arguments to provide to the "jar" tool for this version.
+         * Elements added to the list shall be instances of {@link String} or {@link Path}.
+         *
+         * @param addTo the list where to add the arguments as {@link String} or {@link Path} instances
+         * @param version the target Java release, or {@code null} for the base version of the <abbr>JAR</abbr> file
+         */
+        private void arguments(List<Object> addTo, Runtime.Version version) {
+            if (!files.isEmpty()) {
+                if (version != null) {
+                    addTo.add("--release");
+                    addTo.add(version);
+                }
+                if (isReproducible) {
+                    files.sort(REPRODUCIBLE_ORDER);
+                }
+                if (REPEAT_C) {
+                    for (Path file : files) {
+                        addTo.add("-C");
+                        addTo.add(directory);
+                        addTo.add(file);
+                    }
+                } else {
+                    addTo.add("-C");
+                    addTo.add(directory);
+                    addTo.addAll(files);
+                }
+            }
+        }
+
+        /**
+         * {@return a string representation for debugging purposes}
+         */
+        @Override
+        public String toString() {
+            return getClass().getSimpleName() + '[' + directory.getFileName() + ": " + files.size() + " files]";
+        }
+    }
+
+    /**
+     * Whether reproducible build was requested.
+     */
+    private final boolean isReproducible;
+
+    /**
+     * Creates an initially empty set of files or directories.
+     *
+     * @param jarFile path to the <abbr>JAR</abbr> file to create
+     * @param moduleName the module name if using module hierarchy, or {@code null} if using package hierarchy
+     * @param version the target Java release, or {@code null} for the base version
+     * @param directory the directory of the classes targeting the base Java release
+     * @param forceCreation whether to force a new <abbr>JAR</abbr> file even if the content seems unchanged
+     * @param isReproducible whether reproducible build was requested
+     * @param logger where to send a warning if an error occurred while checking an existing <abbr>JAR</abbr> file
+     */
+    @SuppressWarnings("checkstyle:NeedBraces")
+    Archive(
+            final Path jarFile,
+            final String moduleName,
+            final Runtime.Version version,
+            final Path directory,
+            final boolean forceCreation,
+            final boolean isReproducible,
+            final Log logger) {
+        this.jarFile = jarFile;
+        this.moduleName = moduleName;
+        this.isReproducible = isReproducible;
+        filesetForRelease = new TreeMap<>((v1, v2) -> {
+            if (v1 == v2) return 0;
+            if (v1 == null) return -1;
+            if (v2 == null) return +1;
+            return v1.compareTo(v2);
+        });
+        filesetForRelease.put(version, new FileSet(directory));
+        if (!forceCreation && Files.isRegularFile(jarFile)) {
+            try {
+                existingJAR = new TimestampCheck(jarFile, directory, logger);
+            } catch (IOException e) {
+                // Ignore, we will regenerate the JAR file.
+                logger.warn(e);
+            }
+        }
+    }
+
+    /**
+     * {@return the files or directories to store in the <abbr>JAR</abbr> file for targeting the base Java release}
+     *
+     * @throws NoSuchElementException should not happen unless {@link #prune(boolean)} has been invoked
+     */
+    FileSet baseRelease() {
+        Map.Entry<Runtime.Version, FileSet> entry = filesetForRelease.firstEntry();
+        String message = null;
+        if (entry != null) {
+            Runtime.Version version = entry.getKey();
+            if (version == null) {
+                return entry.getValue();
+            }
+            message = "Expected base version but found version " + version;
+        }
+        throw new NoSuchElementException(message);
+    }
+
+    /**
+     * Returns the {@code module-info.class} files. Conceptually, there is at most once such file per module.
+     * However, more than one file may exist if additional files are provided for additional Java releases.
+     * This method returns only the files that exist.
+     *
+     * @return all {@code module-info.class} files found for all target Java releases
+     */
+    public List<Path> moduleInfoFiles() {
+        var files = new ArrayList<Path>();
+        filesetForRelease.values().forEach((release) -> {
+            Path file = release.directory.resolve(FileCollector.MODULE_DESCRIPTOR_FILE_NAME);
+            if (Files.isRegularFile(file)) {
+                files.add(file);
+            }
+        });
+        return files;
+    }
+
+    /**
+     * Discards all files in this archive, normally because those files are not in any module.
+     * This method returns a common parent directory for all the files that were discarded.
+     * The caller should use that common directory for logging a warning message.
+     *
+     * @return common directory of discarded files, or {@code null} if none
+     */
+    Path discardAllFiles() {
+        Path base = null;
+        for (FileSet release : filesetForRelease.values()) {
+            base = release.discardAllFiles(base);
+        }
+        filesetForRelease.clear();
+        return base;
+    }
+
+    /**
+     * Removes all empty file sets 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}, then this method ensures that at least one file set
+     * remains even if that file set is empty.
+     *
+     * @param skipIfEmpty value of {@link AbstractJarMojo#skipIfEmpty}
+     */
+    public void prune(final boolean skipIfEmpty) {
+        FileSet keep = (skipIfEmpty || isEmpty())
+                ? null
+                : filesetForRelease.firstEntry().getValue();
+        filesetForRelease.values().removeIf((fs) -> fs.files.isEmpty());
+        Iterator<Map.Entry<Runtime.Version, FileSet>> it =
+                filesetForRelease.entrySet().iterator();
+        if (it.hasNext()) {
+            Map.Entry<Runtime.Version, FileSet> first = it.next();
+            if (first.getKey() == null) {
+                return; // Already contains an entry for the base version, nothing to do.
+            }
+            keep = first.getValue();
+            it.remove();
+        }
+        if (keep != null) {
+            filesetForRelease.put(null, keep);
+        }
+    }
+
+    /**
+     * {@return whether this archive has nothing to archive}
+     * Note that this method may return {@code false} even when there is zero file to archive.
+     * It may happen if {@link AbstractJarMojo#skipIfEmpty} is {@code false}. In such case, the
+     * "empty" <abbr>JAR</abbr> file will still contain at {@code META-INF/MANIFEST.MF} file.
+     *
+     * <h4>Prerequisites</h4>
+     * The {@link #prune(boolean)} method should be invoked before this method for accurate result.
+     */
+    public boolean isEmpty() {
+        return filesetForRelease.isEmpty();
+    }
+
+    /**
+     * Checks whether the <abbr>JAR</abbr> file already exists and can be reused.
+     * This method verifies that the <abbr>JAR</abbr> file contains all the files to archive,
+     * contains no extra file, and no file to archive is newer than the <abbr>JAR</abbr> file.
+     *
+     * <p>This method can be invoked only once.
+     * If invoked more often, it returns {@code false} on all subsequent invocations.</p>
+     *
+     * @return whether the <abbr>JAR</abbr> file already exists and can be reused
+     */
+    public boolean isUpToDateJAR() {
+        final TimestampCheck tc = existingJAR;
+        if (tc == null) {
+            return false;
+        }
+        existingJAR = null; // Let GC do its job.
+        return tc.isUpToDateJAR(filesetForRelease.values());
+    }
+
+    /**
+     * Returns an initially empty set of files or directories for the specified target Java release.
+     *
+     * @param directory the base directory of the files to archive
+     * @param version the target Java release, or {@code null} for the base version
+     * @return container where to declare files and directories to archive
+     */
+    FileSet newTargetRelease(Path directory, Runtime.Version version) {
+        return filesetForRelease.computeIfAbsent(version, (key) -> new FileSet(directory));
+    }
+
+    /**
+     * Sets the {@code --main-class} option to the value of the {@code Main-Class} entry of the given manifest.
+     * As an extension, this method accepts the {@code module/classname} syntax (a syntax already used in some
+     * Java tools). If a module is specified, the main class is kept only if the module match. The intent is to
+     * allow users to specify on which module the main class applies when they use plugin configuration.
+     *
+     * <p>This method may modify the {@code content} manifest. Caller shall ensure that the given manifest
+     * is not a shared instance. This method returns whether a change has actually been done.</p>
+     *
+     * @param content combination of existing {@code MANIFEST.MF} and manifest inferred from configuration, or null
+     * @return whether the given manifest has been modified by this method
+     */
+    boolean setMainClass(Manifest content) {
+        if (content == null || mainClass != null) {
+            return false;
+        }
+        // We need to remove the attribute, otherwise it will conflict with `--main-class`.
+        mainClass = (String) content.getMainAttributes().remove(Attributes.Name.MAIN_CLASS);
+        if (mainClass != null) {
+            int s = mainClass.indexOf('/');
+            if (s >= 0) {
+                if (mainClass.substring(0, s).strip().equals(moduleName)) {
+                    mainClass = mainClass.substring(s + 1).strip();
+                } else {
+                    mainClass = null; // Main class is defined for another module.
+                }
+            }
+        }
+        return mainClass != null;
+    }
+
+    /**
+     * Sets the {@code --manifest} option to the given value if that option was not already set.
+     *
+     * @param file path to the manifest file
+     * @param force whether to set the manifest even if already set
+     * @return whether the manifest has been set
+     */
+    boolean setManifest(Path file, boolean force) {
+        if (manifest == null || force) {
+            manifest = file;
+            return true;
+        }
+        return false;
+    }
+
+    /**
+     * Merges the manifest of this module with the manifest specified in plugin configuration.
+     * If both {@code file} and {@code content} are non-null, then {@code content} must be the
+     * result of reading {@code file}.
+     *
+     * <p>This method never modifies the given {@code content} object. If manifest are merged,
+     * a new {@link Manifest} instance is created. Therefore, caller can check whether this
+     * method returned a new instance as a way to recognize that a merge occurred.</p>
+     *
+     * <p>If a merge occurs, the content specified to {@link #setManifest(Path)} has precedence.
+     * It should be the {@code target/classes/META-INF/MANIFEST.MF} file (or modular equivalent).</p>
+     *
+     * @param  file     an additional manifest file, or {@code null}
+     * @param  content  the content of {@code file}, or a standalone manifest produced at runtime
+     * @return the merged manifest as a new instance if some changes were necessary
+     * @throws IOException if an error occurred while reading a manifest file
+     */
+    Manifest mergeManifest(Path file, Manifest content) throws IOException {
+        if (manifest == null) {
+            manifest = file;
+        } else if (file != null && Files.isSameFile(file, manifest)) {
+            // Nothing to merge because of the constraint that `content` must be the content of `file`.
+        } else {
+            try (InputStream in = Files.newInputStream(manifest)) {
+                // No need to wrap in `BufferedInputStream`.
+                if (content != null) {
+                    content = new Manifest(content);
+                    content.read(in);
+                } else {
+                    content = new Manifest(in);
+                }
+            }
+        }
+        return content;
+    }
+
+    /**
+     * Adds to the given list the arguments to provide to the "jar" tool for each version.
+     * Elements added to the list shall be instances of {@link String} or {@link Path}.
+     * Callers should have added the following options (if applicable) before to invoke this method:
+     *
+     * <ul>
+     *   <li>{@code --create}</li>
+     *   <li>{@code --no-compress}</li>
+     *   <li>{@code --date} followed by the output time stamp</li>
+     *   <li>{@code --module-version} followed by module version</li>
+     *   <li>{@code --hash-modules} followed by patters of module names</li>
+     *   <li>{@code --module-path} followed by module path</li>
+     * </ul>
+     *
+     * This method adds the following options:
+     *
+     * <ul>
+     *   <li>{@code --file} followed by the path to the <abbr>JAR</abbr> file</li>
+     *   <li>{@code --manifest} followed by path to the manifest file</li>
+     *   <li>{@code --main-class} followed by fully qualified name class</li>
+     *   <li>{@code --release} followed by Java target release</li>
+     *   <li>{@code -C} followed by directory</li>
+     *   <li>files or directories to archive</li>
+     * </ul>
+     *
+     * @param addTo the list where to add the arguments as {@link String} or {@link Path} instances
+     */
+    void arguments(final List<Object> addTo) {
+        addTo.add("--file");
+        addTo.add(jarFile);
+        if (manifest != null) {
+            addTo.add("--manifest");
+            addTo.add(manifest);
+        }
+        if (mainClass != null) {
+            addTo.add("--main-class");
+            addTo.add(mainClass);
+        }
+        if (mavenFiles != null) {
+            addTo.add("-C");
+            addTo.addAll(mavenFiles);
+        }
+        for (Map.Entry<Runtime.Version, FileSet> entry : filesetForRelease.entrySet()) {
+            entry.getValue().arguments(addTo, entry.getKey());
+        }
+    }
+
+    /**
+     * Adds to the given list the arguments to provide to the "jar" tool for validating the <abbr>JAR</abbr> file.
+     * The file is validated only if the validation was not done implicitly at <abbr>JAR</abbr> creation time.
+     * This is the case if no {@code --release} option was used.
+     * This method adds the following options:
+     *
+     * <ul>
+     *   <li>{@code --validate} operation mode</li>
+     *   <li>{@code --file} followed by the path to the <abbr>JAR</abbr> file</li>
+     * </ul>
+     *
+     * @param  addTo the list where to add the arguments as {@link String} or {@link Path} instances
+     * @return whether a validation should be run
+     */
+    boolean validate(final List<Object> addTo) {
+        if (filesetForRelease.values().stream().allMatch(Objects::isNull)) {

Review Comment:
   The identification of the bug is correct, but the proposed fix is not: it checks that the JAR has no base version, which should never happen. I will apply a correct fix.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "rmannibucau (via GitHub)" <gi...@apache.org>.
rmannibucau commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3778775653


##########
src/main/java/org/apache/maven/plugins/jar/AbstractJarMojo.java:
##########
@@ -207,167 +205,199 @@ protected final Log getLog() {
     protected abstract String getType();
 
     /**
-     * Returns the JAR file to generate, based on an optional classifier.
+     * {@return the scope of dependencies}
+     * It should be {@link PathScope#MAIN_COMPILE} or {@link PathScope#TEST_COMPILE}.
+     * Note that we use compile scope rather than runtime scope because dependencies
+     * cannot appear in {@code requires} statement if they didn't had compile scope.
+     */
+    protected abstract PathScope getDependencyScope();
+
+    /**
+     * {@return the JAR tool to use for archiving the code}
      *
-     * @param basedir the output directory
-     * @param resultFinalName the name of the JAR file
-     * @param classifier an optional classifier
-     * @return the file to generate
+     * @throws MojoException if no JAR tool was found
+     *
+     * @since 4.0.0-beta-2
      */
-    protected Path getJarFile(Path basedir, String resultFinalName, String classifier) {
-        Objects.requireNonNull(basedir, "basedir is not allowed to be null");
-        Objects.requireNonNull(resultFinalName, "finalName is not allowed to be null");
-        String fileName = resultFinalName + (hasClassifier(classifier) ? '-' + classifier : "") + ".jar";
-        return basedir.resolve(fileName);
+    protected ToolProvider getJarTool() throws MojoException {
+        return ToolProvider.findFirst(toolId).orElseThrow(() -> new MojoException("No such \"" + toolId + "\" tool."));
     }
 
     /**
-     * Generates the JAR.
+     * Returns whether the specified Java version is supported.
      *
-     * @return the path to the created archive file
-     * @throws MojoException in case of an error
+     * @param release name of an {@link SourceVersion} enumeration constant
+     * @return whether the current environment support that version
      */
-    public Path createArchive() throws MojoException {
-        Path basedir = outputDirectory != null
-                ? outputDirectory
-                : Path.of(project.getBuild().getDirectory());
-        String resultFinalName =
-                finalName != null ? finalName : project.getBuild().getFinalName();
-        Path jarFile = getJarFile(basedir, resultFinalName, getClassifier());
-
-        FileSetManager fileSetManager = new FileSetManager();
-        FileSet jarContentFileSet = new FileSet();
-        jarContentFileSet.setDirectory(getClassesDirectory().toAbsolutePath().toString());
-        jarContentFileSet.setIncludes(Arrays.asList(getIncludes()));
-        jarContentFileSet.setExcludes(Arrays.asList(getExcludes()));
-
-        String[] includedFiles = fileSetManager.getIncludedFiles(jarContentFileSet);
-
-        if (detectMultiReleaseJar
-                && Arrays.stream(includedFiles)
-                        .anyMatch(
-                                p -> p.startsWith("META-INF" + File.separatorChar + "versions" + File.separatorChar))) {
-            getLog().debug("Adding 'Multi-Release: true' manifest entry.");
-            archive.addManifestEntry(Attributes.Name.MULTI_RELEASE.toString(), "true");
+    private static boolean isSupported(String release) {

Review Comment:
   +1 to drop it since there is not much impl of jar (compared to javac to be explicit)



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3923351253


##########
src/main/java/org/apache/maven/plugins/jar/ExcludedFiles.java:
##########
@@ -0,0 +1,145 @@
+/*
+ * 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.jar;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardCopyOption;
+import java.util.List;
+
+/**
+ * A list of files to temporarily move outside the directory to package in a <abbr>JAR</abbr> archive.
+ * This is used for excluding files from the <abbr>JAR</abbr> archive according to include/exclude filters.
+ * We move these files for making possible to specify the whole directory to the {@code jar} tool.
+ * This approach is used instead of enumerating files in arguments given to the {@code jar} tool because
+ * such enumeration can not contain directory entries (otherwise the whole directory would be included).
+ * Some software such as Spring applications component scan relies on the presence of directory entries.

Review Comment:
   Done as below:  This class is needed when the {@link AbstractJarMojo} configuration has include or exclude filters. Excluded files are temporarily moved outside the directory to archive.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3923432934


##########
src/main/java/org/apache/maven/plugins/jar/ExcludedFiles.java:
##########
@@ -0,0 +1,145 @@
+/*
+ * 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.jar;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardCopyOption;
+import java.util.List;
+
+/**
+ * A list of files to temporarily move outside the directory to package in a <abbr>JAR</abbr> archive.
+ * This is used for excluding files from the <abbr>JAR</abbr> archive according to include/exclude filters.
+ * We move these files for making possible to specify the whole directory to the {@code jar} tool.
+ * This approach is used instead of enumerating files in arguments given to the {@code jar} tool because
+ * such enumeration can not contain directory entries (otherwise the whole directory would be included).
+ * Some software such as Spring applications component scan relies on the presence of directory entries.
+ */
+final class ExcludedFiles implements Closeable {
+    /**
+     * The paths of files or directories to temporarily move in another directory.
+     */
+    private final Path[] original;
+
+    /**
+     * The paths where files or directories were moved.
+     * For each index <var>i</var>, the original path of {@code moved[i]} was {@code original[i]}.
+     */
+    private final Path[] moved;
+
+    /**
+     * Temporary directory which will contain the {@code moved} files.
+     * It should be a parent directory of {@link #original} files for
+     * increasing the chances that it is on the same file system.
+     */
+    private final Path temporaryDirectory;
+
+    /**
+     * Index of the first path which is a directory instead of a file.
+     * All paths before this index in the {@link #original} and {@link #moved} arrays are files.
+     * All paths at this index and after this index are directories.
+     */
+    private final int indexOfFirstDirectory;
+
+    /**
+     * Creates a new list of files to move in a temporary directory.
+     *
+     * @param directory the directory which was scanned for files to include in the <abbr>JAR</abbr>
+     * @param excludedFiles paths of files to temporarily move in another directory
+     * @param excludedDirectories paths of directories to temporarily move in another directory
+     * @throws IOException if an error occurred while creating the temporary directory.
+     */
+    ExcludedFiles(Path directory, List<Path> excludedFiles, List<Path> excludedDirectories) throws IOException {
+        indexOfFirstDirectory = excludedFiles.size();
+        final int nd = excludedDirectories.size();
+        original = excludedFiles.toArray(new Path[indexOfFirstDirectory + nd]);
+        System.arraycopy(excludedDirectories.toArray(), 0, original, indexOfFirstDirectory, nd);
+        moved = new Path[original.length];
+        temporaryDirectory = Files.createTempDirectory(directory, "excluded-");
+    }
+
+    /**
+     * Moves the files now. This method should be invoked inside the "try with resource" block.
+     *
+     * @throws IOException if an error occurred while moving a file.
+     */
+    public void move() throws IOException {
+        for (int i = 0; i < original.length; i++) {
+            final Path source = original[i];
+            String prefix = source.getFileName().toString();
+            String suffix = null;
+            Path target;
+            if (i < indexOfFirstDirectory) {
+                int s = prefix.lastIndexOf('.');
+                if (s > 0) {
+                    suffix = prefix.substring(s);
+                    prefix = prefix.substring(0, s);
+                }
+                target = Files.createTempFile(temporaryDirectory, prefix, suffix);
+            } else {
+                target = Files.createTempDirectory(temporaryDirectory, prefix);
+            }
+            try {
+                moved[i] = Files.move(source, target, StandardCopyOption.REPLACE_EXISTING);
+            } catch (IOException e) {
+                try {
+                    Files.delete(target);
+                } catch (IOException e2) {
+                    e.addSuppressed(e2);
+                }
+                throw e;
+            }
+        }
+    }
+
+    /**
+     * Moves the temporary files back to their original locations.
+     * This method can be invoked even if only a subset of the files were moved.
+     * The latter may happen if an error occurred in the middle of {@link #move()} execution.

Review Comment:
   Done.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3923642621


##########
src/main/java/org/apache/maven/plugins/jar/PomDerivation.java:
##########
@@ -0,0 +1,529 @@
+/*
+ * 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.jar;
+
+import javax.xml.stream.XMLStreamException;
+
+import java.io.BufferedInputStream;
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.UncheckedIOException;
+import java.lang.module.ModuleDescriptor;
+import java.lang.module.ModuleFinder;
+import java.lang.module.ModuleReference;
+import java.net.URI;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.DependencyCoordinates;
+import org.apache.maven.api.JavaPathType;
+import org.apache.maven.api.Session;
+import org.apache.maven.api.Type;
+import org.apache.maven.api.model.Dependency;
+import org.apache.maven.api.model.Model;
+import org.apache.maven.api.model.Parent;
+import org.apache.maven.api.plugin.MojoException;
+import org.apache.maven.api.services.DependencyCoordinatesFactory;
+import org.apache.maven.api.services.DependencyCoordinatesFactoryRequest;
+import org.apache.maven.api.services.DependencyResolver;
+import org.apache.maven.api.services.DependencyResolverRequest;
+import org.apache.maven.api.services.DependencyResolverResult;
+import org.apache.maven.api.services.ModelBuilderException;
+import org.apache.maven.model.v4.MavenStaxWriter;
+
+/**
+ * A mapper from Maven model dependencies to Java module names.
+ * A single instance of this class is created for a Maven project,
+ * then shared by all {@link ForModule} instances (one per module to archive).
+ */
+final class PomDerivation {
+    /**
+     * Whether to expand the list of transitive dependencies in the generated <abbr>POM</abbr>.
+     */
+    private static final boolean EXPAND_TRANSITIVE = false;
+
+    /**
+     * Copy of {@link AbstractJarMojo#session}.
+     */
+    private final Session session;
+
+    /**
+     * The project model, which includes dependencies of all modules.
+     */
+    private final Model projectModel;
+
+    /**
+     * The factory to use for creating temporary {@link DependencyCoordinates} instances.
+     */
+    private final DependencyCoordinatesFactory coordinateFactory;
+
+    /**
+     * Provide module descriptors from module names.
+     * May be {@code null} if no {@code module-info} was found.
+     */
+    private final ModuleFinder moduleFinder;
+
+    /**
+     * Module references from paths to the <abbr>JAR</abbr> file or root directory.
+     */
+    private final Map<URI, ModuleReference> fromURI;
+
+    /**
+     * Module names associated with Maven dependencies.
+     * This map contains {@link DependencyCoordinates#getId()} as keys and module references as values.
+     * This is used to detect which dependencies are really used according to {@code module-info.class}.
+     *
+     * @todo The keys should be instances of {@link DependencyCoordinates}. Unfortunately, as of Maven 4.0.0-rc-5
+     *       that interface does not define the {@code equals} and {@code hashCode} contracts.
+     */
+    private final Map<String, ModuleReference> fromDependency;
+
+    /**
+     * Modules that are built by the project. Keys are module names.
+     */
+    private final Map<String, Dependency> builtModules;
+
+    /**
+     * Creates a new mapper from Maven dependency to module name.
+     *
+     * @param mojo the enclosing <abbr>MOJO</abbr>
+     * @param moduleRoots paths to root directories of each module to archive in a module hierarchy
+     * @throws IOException if an I/O error occurred while fetching dependencies
+     * @throws MavenException if an error occurred while fetching dependencies for a reason other than I/O.
+     */
+    PomDerivation(final AbstractJarMojo mojo, final List<Path> moduleRoots) throws IOException {
+        this.session = mojo.session;
+        projectModel = mojo.project.getModel();
+        coordinateFactory = session.getService(DependencyCoordinatesFactory.class);
+        DependencyResolver resolver = session.getService(DependencyResolver.class);
+        DependencyResolverResult result = resolver.resolve(DependencyResolverRequest.builder()
+                .session(session)
+                .project(mojo.project)
+                .requestType(DependencyResolverRequest.RequestType.RESOLVE)
+                .pathScope(mojo.getDependencyScope())
+                .pathTypeFilter(Set.of(JavaPathType.MODULES, JavaPathType.CLASSES))
+                .build());
+
+        rethrow(result);
+        final Map<org.apache.maven.api.Dependency, Path> dependencies = result.getDependencies();
+        final Path[] allModulePaths = toRealPaths(moduleRoots, dependencies.values());
+        fromURI = new HashMap<>(allModulePaths.length); // TODO: use newHashMap with JDK19.
+        moduleFinder = ModuleFinder.of(allModulePaths);
+        if (moduleFinder != null) {
+            for (ModuleReference reference : moduleFinder.findAll()) {
+                reference.location().ifPresent((location) -> fromURI.put(location, reference));
+            }
+        }
+        fromDependency = new HashMap<>(dependencies.size()); // TODO: use newHashMap with JDK19.
+        for (Map.Entry<org.apache.maven.api.Dependency, Path> entry : dependencies.entrySet()) {
+            Path modulePath = entry.getValue().toRealPath();
+            ModuleReference reference = fromURI.get(modulePath.toUri());
+            if (reference != null) {
+                DependencyCoordinates coordinates = entry.getKey().toCoordinates();
+                String id = coordinates.getId();
+                ModuleReference old = fromDependency.putIfAbsent(id, reference);
+                if (old == null) {
+                    coordinates = withoutVersion(coordinates);
+                    id = coordinates.getId();
+                    old = fromDependency.putIfAbsent(id, reference);
+                }
+                if (old != null && !old.equals(reference)) {
+                    mojo.log.warn("The \"" + id + "\" dependency is declared twice with different module names: \""
+                            + old.descriptor().name() + "\" and \""
+                            + reference.descriptor().name() + "\".");
+                }
+            }
+        }
+        builtModules = new HashMap<>(moduleRoots.size()); // TODO: use newHashMap with JDK19.
+        for (Path root : moduleRoots) {
+            root = root.toRealPath();
+            ModuleReference reference = fromURI.get(root.toUri());
+            if (reference != null) { // Actually a null value would be a bug, but be tolerant.
+                String moduleName = reference.descriptor().name();
+                builtModules.put(
+                        moduleName,
+                        Dependency.newBuilder()
+                                .groupId(projectModel.getGroupId())
+                                .artifactId(moduleName)
+                                .version(projectModel.getVersion())
+                                .type(Type.MODULAR_JAR)
+                                .build());
+            }
+        }
+    }
+
+    /**
+     * Rebuilds the given dependency coordinates without version.
+     *
+     * Note: I'm not sure if it is necessary. This is done in case version numbers are not resolved
+     * in the dependencies of the model returned by {@code Project.getModel()}, or are not resolved
+     * in the same way as what we get from {@link DependencyResolver}.
+     */
+    private DependencyCoordinates withoutVersion(DependencyCoordinates coordinates) {
+        return coordinateFactory.create(DependencyCoordinatesFactoryRequest.builder()
+                .session(session)
+                .groupId(coordinates.getGroupId())
+                .artifactId(coordinates.getArtifactId())
+                .extension(coordinates.getExtension())
+                .classifier(coordinates.getClassifier())
+                .build());
+    }
+
+    /**
+     * If the resolver failed, propagates its exception.
+     *
+     * @param result the resolver result
+     * @throws IOException if the result contains an I/O error
+     */
+    private static void rethrow(DependencyResolverResult result) throws IOException {
+        Exception exception = null;
+        for (Exception cause : result.getExceptions()) {
+            if (cause instanceof UncheckedIOException e) {
+                cause = e.getCause();
+            }
+            if (exception != null) {
+                exception.addSuppressed(cause);
+            } else if (cause instanceof RuntimeException || cause instanceof IOException) {
+                exception = cause;
+            } else {
+                exception = new MojoException("Cannot collect the runtime dependencies.", cause);
+            }
+        }
+        if (exception != null) {
+            if (exception instanceof IOException e) {
+                throw e;
+            } else {
+                throw (RuntimeException) exception; // A ClassCastException here would be a bug in above loop.
+            }
+        }
+    }
+
+    /**
+     * Returns the real paths of the given collections, in iteration order and without duplicated values.
+     */
+    private static Path[] toRealPaths(Collection<Path> moduleRoots, Collection<Path> dependencies) throws IOException {
+        // TODO: use newLinkedHashSet(int) after we are allowed to compile for JDK19.
+        final var paths = new LinkedHashSet<Path>(moduleRoots.size() + dependencies.size());
+        for (Path path : moduleRoots) {
+            paths.add(path.toRealPath());
+        }
+        for (Path path : dependencies) {
+            paths.add(path.toRealPath());
+        }
+        return paths.toArray(Path[]::new);
+    }
+
+    /**
+     * Returns the module descriptor for the {@code module-info.class} at the given path.
+     *
+     * @param moduleInfo path to a {@code module-info.class} file
+     * @return module descriptor for the specified file
+     * @throws IOException if an error occurred while reading the file
+     */
+    private ModuleDescriptor findModuleDescriptor(Path moduleInfo) throws IOException {
+        Path directory = moduleInfo.toRealPath().getParent();
+        ModuleReference reference = fromURI.get(directory.toUri());
+        if (reference != null) {
+            return reference.descriptor();
+        }
+        try (InputStream in = new BufferedInputStream(Files.newInputStream(moduleInfo))) {
+            return ModuleDescriptor.read(in);
+        }
+    }
+
+    /**
+     * Returns the module descriptor for the specified Maven dependency.
+     *
+     * @param dependency dependency for which to get the module descriptor
+     * @return Java module descriptor for the given Maven dependency
+     */
+    private Optional<ModuleDescriptor> findModuleDescriptor(Dependency dependency) {
+        DependencyCoordinates coordinates = coordinateFactory.create(session, dependency);
+        ModuleReference reference = fromDependency.get(coordinates.getId());
+        if (reference == null) {
+            coordinates = withoutVersion(coordinates);
+            reference = fromDependency.get(coordinates.getId());
+            if (reference == null) {
+                return Optional.empty();
+            }
+        }
+        return Optional.of(reference.descriptor());
+    }
+
+    /**
+     * Returns the module descriptor for the specified module name.
+     *
+     * @param moduleName name of the module for which to get the descriptor
+     * @return module descriptor for the specified module name
+     */
+    private Optional<ModuleDescriptor> findModuleDescriptor(String moduleName) {
+        if (moduleFinder == null) {
+            return Optional.empty();
+        }
+        return moduleFinder.find(moduleName).map(ModuleReference::descriptor);
+    }
+
+    /**
+     * Derives a <abbr>POM</abbr> as the intersection of the consumer <abbr>POM</abbr>
+     * and the dependencies required by {@code module-info}.
+     */
+    final class ForModule {
+        /**
+         * Value of the {@code <name>} element in the derived <abbr>POM</abbr>, or {@code null} if none.
+         */
+        private String name;
+
+        /**
+         * Name of the module for which to derive a <abbr>POM</abbr> file.
+         */
+        private final String moduleName;
+
+        /**
+         * Whether a dependency is optional or required only at runtime.
+         */
+        private enum Modifier {
+            OPTIONAL,
+            RUNTIME
+        }
+
+        /**
+         * The required dependencies as Java module names, including transitive dependencies.
+         * Values tell whether the dependency is optional or should have runtime scope.
+         */
+        private final Map<String, EnumSet<Modifier>> requires;
+
+        /**
+         * Path to the <abbr>POM</abbr> file written by this class.
+         */
+        final Path pomFile;
+
+        /**
+         * Creates a new <abbr>POM</abbr> generator for the given archive.
+         *
+         * @param archive the archive for which to generate a <abbr>POM</abbr>
+         * @param manifest manifest to use for deriving project name, or {@code null} if none
+         * @throws IOException if an error occurred while reading the {@code module-info.class} file
+         */
+        ForModule(final Archive archive, final Manifest manifest) throws IOException {
+            moduleName = archive.moduleName;
+            pomFile = derivePathToPOM(archive.jarFile);
+            requires = new LinkedHashMap<>();
+            for (Path file : archive.moduleInfoFiles()) {
+                addDependencies(findModuleDescriptor(file), EnumSet.noneOf(Modifier.class));
+            }
+            if (manifest != null) {
+                name = (String) manifest.getMainAttributes().get(Attributes.Name.IMPLEMENTATION_TITLE);
+                if (name == null) {
+                    name = (String) manifest.getMainAttributes().get(Attributes.Name.SPECIFICATION_TITLE);
+                }
+            }
+        }
+
+        /**
+         * Add the dependencies of the given module, including transitive dependencies.
+         * If the same dependency is added twice with different optional flags,
+         * the {@code false} value (i.e., mandatory dependency) has precedence.
+         *
+         * @param descriptor description of the module for which to add dependencies
+         * @param parentModifiers modifiers of the parent module for which this method adds dependencies
+         */
+        private void addDependencies(final ModuleDescriptor descriptor, final EnumSet<Modifier> parentModifiers) {
+            for (ModuleDescriptor.Requires r : descriptor.requires()) {
+                final EnumSet<Modifier> modifiers = parentModifiers.clone();
+                if (r.modifiers().contains(ModuleDescriptor.Requires.Modifier.STATIC)) {
+                    modifiers.add(Modifier.OPTIONAL);
+                }
+                if (!r.modifiers().contains(ModuleDescriptor.Requires.Modifier.TRANSITIVE)) {
+                    modifiers.add(Modifier.RUNTIME);
+                }
+                EnumSet<Modifier> current = requires.computeIfAbsent(r.name(), (key) -> modifiers);
+                if (EXPAND_TRANSITIVE && (current == modifiers || current.retainAll(modifiers))) {
+                    // Transitive dependencies if not already added or if it needs to update modifiers.
+                    findModuleDescriptor(r.name()).ifPresent((td) -> addDependencies(td, modifiers));
+                }
+            }
+        }
+
+        /**
+         * Derives a <abbr>POM</abbr> file for the archive specified ad construction time.
+         *
+         * @throws IOException if an error occurred while writing the <abbr>POM</abbr> file
+         *
+         * @see #writeParentPOM(Archive)
+         */
+        void writeModulePOM() throws IOException {
+            try {
+                writePOM(deriveModulePOM(), pomFile);
+            } catch (ModelBuilderException | XMLStreamException e) {
+                throw new MojoException("Cannot derive a POM file for the \"" + moduleName + "\" module.", e);
+            }
+        }
+
+        /**
+         * Derives the module <abbr>POM</abbr> file as the intersection of the project <abbr>POM</abbr> and the archive.
+         *
+         * @return intersection of {@link #projectModel} and {@code module-info.class}
+         * @throws ModelBuilderException if an error occurred while building the model
+         */
+        private Model deriveModulePOM() throws ModelBuilderException {
+            Model.Builder builder = Model.newBuilder()
+                    .modelVersion("4.0.0")
+                    .groupId(projectModel.getGroupId())
+                    .artifactId(moduleName)
+                    .version(projectModel.getVersion())
+                    .parent(Parent.newBuilder()
+                            .groupId(projectModel.getGroupId())
+                            .artifactId(projectModel.getArtifactId())
+                            .version(projectModel.getVersion())
+                            .build());
+            if (name != null) {
+                builder = builder.name(name);
+            }
+            /*
+             * Filter the dependencies by keeping only the one declared in a `requires` statement of the
+             * `module-info.class` of the module that we are archiving. Also adjust the `<optional>` and
+             * `<scope>` values. The dependencies that we found are removed from the `requires` map as a
+             * way to make sure that we do not add them twice. In principle, the map should become empty
+             * at the end of this loop.
+             */
+            final List<Dependency> dependencies = projectModel.getDependencies();
+            if (dependencies != null) {
+                final var filteredDependencies = new ArrayList<Dependency>(dependencies.size());
+                for (var iterator = requires.entrySet().iterator(); iterator.hasNext(); ) {
+                    Map.Entry<String, EnumSet<Modifier>> entry = iterator.next();
+                    Dependency dependency = builtModules.get(entry.getKey());
+                    if (dependency != null) {
+                        filteredDependencies.add(amend(dependency, entry.getValue()));
+                        iterator.remove();
+                    }
+                }
+                for (Dependency dependency : dependencies) {
+                    String dependencyModuleName = findModuleDescriptor(dependency)
+                            .map(ModuleDescriptor::name)
+                            .orElse(null);
+                    /*
+                     * If `dependencyModuleName` is null, then the dependency scope is "test" or some other scope
+                     * that resolver has chosen to exclude. Note that this is true even for JAR on the classpath,
+                     * because we stored the automatic module name in `PomDerivation`. Next, if `modifiers` is null,
+                     * then the dependency has compile or runtime scope but is not used by the module to archive.
+                     */
+                    if (dependencyModuleName != null) {
+                        EnumSet<Modifier> modifiers = requires.remove(dependencyModuleName);
+                        if (modifiers != null) {
+                            filteredDependencies.add(amend(dependency, modifiers));
+                        }
+                    }
+                }
+                builder.dependencies(filteredDependencies);
+            }
+            /*
+             * Replace the `<name>` element by the equivalent value defined in MANIFEST.MF.
+             * We do this replacement because the `<name>` of the project model applies to all modules,
+             * while the MANIFEST.MF has more chances to be specific to the module that we are archiving.
+             */
+            return builder.build();
+        }
+
+        /**
+         * Modifies the optional and scope elements of the given dependency according to the given modifiers.
+         *
+         * @param dependency the dependency to amend
+         * @param modifiers the modifiers to apply
+         * @return the amended dependency
+         */
+        private static Dependency amend(Dependency dependency, EnumSet<Modifier> modifiers) {
+            String scope = modifiers.contains(Modifier.RUNTIME) ? "runtime" : null;
+            if (!Objects.equals(scope, dependency.getScope())) {
+                dependency = dependency.withScope(scope);
+            }
+            boolean optional = modifiers.contains(Modifier.OPTIONAL);
+            if (Boolean.parseBoolean(dependency.getOptional()) != optional) {
+                dependency = dependency.withOptional(Boolean.toString(optional));
+            }
+            return dependency;
+        }
+    }
+
+    /**
+     * Writes the parent <abbr>POM</abbr> file as the project file but without the dependencies.
+     * The dependencies are removed because they will declared on a module-by-module basis.
+     *
+     * @param packageHierarchy value of {@link FileCollector#packageHierarchy}
+     * @return path to the file that has been written
+     * @throws IOException if an I/O error occurred while writing the model
+     *
+     * @see ForModule#writeModulePOM()
+     */
+    Path writeParentPOM(final Archive packageHierarchy) throws IOException {
+        Path pomFile = derivePathToPOM(packageHierarchy.jarFile);
+        Model.Builder builder = Model.newBuilder(projectModel, true);
+        builder = builder.root(false).modules(null).subprojects(null);
+        builder = builder.dependencies(null).build(null).reporting(null).distributionManagement(null);
+        builder = builder.preserveModelVersion(false).modelVersion("4.0.0");
+        try {
+            writePOM(builder.build(), pomFile);
+        } catch (ModelBuilderException | XMLStreamException e) {
+            throw new MojoException("Cannot write the parent POM.", e);
+        }
+        return pomFile;
+    }
+
+    /**
+     * Derives the path to the <abbr>POM</abbr> file to generate.
+     *
+     * @param jarFile path to the <abbr>JAR</abbr> file (the file does not need to exist)
+     * @return path to the <abbr>POM</abbr> file to generate
+     */
+    private static Path derivePathToPOM(final Path jarFile) {
+        String filename = jarFile.getFileName().toString();
+        filename = filename.substring(0, filename.lastIndexOf('.') + 1) + "pom";
+        return jarFile.resolveSibling(filename);
+    }
+
+    /**
+     * Writes the given model in the given file.
+     *
+     * @param model the model to write
+     * @param file the destination file
+     * @throws IOException if an I/O error occurred while writing the model
+     * @throws XMLStreamException if a XML error occurred while writing the model
+     */
+    private static void writePOM(Model model, Path file) throws IOException, XMLStreamException {
+        try (BufferedWriter out = Files.newBufferedWriter(file)) {
+            var sw = new MavenStaxWriter();

Review Comment:
   Done. I used `xmlWriter` in case some peoples are not familiar about STAX. They get that this is some kind of XML writer, and the constructor tells us which one exactly.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3921928296


##########
src/main/java/org/apache/maven/plugins/jar/Archive.java:
##########
@@ -0,0 +1,655 @@
+/*
+ * 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.jar;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.TreeMap;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.Type;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.MojoException;
+
+/**
+ * Files or root directories to archive for a single module.
+ * A single instance of {@code Archive} can contain many directories for different target Java releases.
+ * Many instances of {@code Archive} can exist when archiving a multi-modules project.
+ */
+final class Archive {
+    /**
+     * Path to the <abbr>POM</abbr> file generated for this archive, or {@code null} if none.
+     * This is non-null only if module source hierarchy is used, in which case the dependencies
+     * declared in this file are the intersection of the project dependencies and the content of
+     * the {@code module-info.class} file.
+     */
+    @Nullable
+    Path pomFile;
+
+    /**
+     * The <var>JAR</var> file to create. Can be an existing file,
+     * in which case the file creation can be skipped if the file is still up-to-date.
+     */
+    @Nonnull
+    final Path jarFile;
+
+    /**
+     * A helper class for checking whether an existing <abbr>JAR</abbr> file is still up-to-date.
+     * This is null if there is no existing JAR file, or if we determined that the file is outdated.
+     */
+    private TimestampCheck existingJAR;
+
+    /**
+     * Name of the module being archived when the project is using module hierarchy.
+     * This is {@code null} if the project is using package hierarchy, either because it is a classical
+     * class-path project or because it is a single module compiled without using the module hierarchy.
+     * When using module source hierarchy, {@code javac} guarantees that the module name in the output
+     * directory is the name of the parent directory of {@code module-info.class}.
+     */
+    @Nullable
+    final String moduleName;
+
+    /**
+     * Path to {@code META-INF/MANIFEST.MF}, or {@code null} if none.
+     * If non-null, this value will be given to the {@code --manifest} option.
+     * The use of this option is preferable to adding {@code MANIFEST.MF} as an ordinary file.
+     *
+     * @see #setManifest(Path, boolean)
+     * @see #mergeManifest(Path, Manifest)
+     */
+    @Nullable
+    private Path manifest;
+
+    /**
+     * The Maven generated {@code pom.xml} and {@code pom.properties} files, or {@code null} if none.
+     * This first item must be the base directory where the files are located.
+     */
+    @Nullable
+    List<Path> mavenFiles;
+
+    /**
+     * Fully-qualified name of the main class, or {@code null} if none.
+     * This is the value to provide to the {@code --main-class} option.
+     */
+    private String mainClass;
+
+    /**
+     * Files or root directories to store in the <abbr>JAR</abbr> file for each target Java release
+     * other than the base release. Keys are the target Java release with {@code null} for the base
+     * release.
+     */
+    @Nonnull
+    private final NavigableMap<Runtime.Version, FileSet> filesetForRelease;
+
+    /**
+     * Files or root directories to archive for a single target Java release of a single module.
+     * The {@link Archive} enclosing must contain at least one instance of {@code FileSet} for
+     * the base release, and an arbitrary amount of other instances for other target releases.
+     */
+    final class FileSet {
+        /**
+         * The root directory of all files or directories to archive.
+         * This is the value to pass to the {@code -C} tool option.
+         */
+        @Nonnull
+        final Path directory;
+
+        /**
+         * The files or directories to include in the <var>JAR</var> file.
+         * Can be absolute paths or paths relative to {@link #directory}.
+         * It usually contains only the files or directories directly in
+         * the root {@linkplain #directory}, not in sub-directories.
+         */
+        @Nonnull
+        final List<Path> files;
+
+        /**
+         * Creates an initially empty set of files or directories for a specific target Java release.
+         *
+         * @param directory the base directory of the files or directories to archive
+         */
+        private FileSet(Path directory) {
+            this.directory = directory;
+            this.files = new ArrayList<>();
+        }
+
+        /**
+         * 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.
+         * The caller should use that common directory for logging a warning message.
+         *
+         * @param base base directory found by previous invocations of this method, or {@code null} if none
+         * @return common directory of discarded files
+         */
+        private Path discardAllFiles(Path base) {
+            for (Path file : files) {
+                if (base == null) {
+                    base = file.getParent();
+                } else {
+                    while (!file.startsWith(base)) {
+                        base = base.getParent();
+                        if (base == null) {
+                            break;
+                        }
+                    }
+                }
+            }
+            files.clear();
+            return base;
+        }
+
+        /**
+         * Adds the given path to the list of files or directories to archive.
+         * If the given path is a directory, then all children will be included.
+         * Children to exclude, if any, should be managed by {@link ExcludedFiles}.
+         *
+         * @param item a file or directory to archive
+         * @param attributes the file's basic attributes
+         * @param isDirectory whether the file is a directory
+         */
+        void add(Path item, BasicFileAttributes attributes, boolean isDirectory) {
+            TimestampCheck tc = existingJAR;
+            if (tc != null && tc.isUpdated(item, attributes, isDirectory)) {
+                existingJAR = null; // Signal that the existing file is outdated.
+            }
+            files.add(item);
+        }
+
+        /**
+         * Adds to the given list the arguments to provide to the "jar" tool for this version.
+         * The elements added to the list will be instances of {@link String} or {@link Path}.
+         *
+         * <h4>Note about the {@code -C} option</h4>
+         * This method repeats the {@code -C} option before each file.
+         * Our tests suggest that the first file after the directory specified by the {@code -C} option must
+         * be relative to that directory and all files after the first one must be prefixed by the directory
+         * which was specified in the {@code -C} option. This behavior is not very intuitive and replying on
+         * it can be fragile. Furthermore, it seems that the relativized file needs to be the shortest one,
+         * otherwise the {@code jar} tool rejects files after the first one with "names do not match".
+         * Which file is first depends on the unspecified directory-iteration order.
+         * Repeating the {@code -C} option for each file seems safer.
+         *
+         * @param addTo the list to add the arguments as {@link String} or {@link Path} instances to
+         * @param version the target Java release, or {@code null} for the base version of the <abbr>JAR</abbr> file
+         * @throws IllegalArgumentException if a path cannot be made relative to the base directory
+         */
+        private void arguments(List<Object> addTo, Runtime.Version version) {
+            if (files.isEmpty()) {
+                return;
+            }
+            if (version != null) {
+                addTo.add("--release");
+                addTo.add(version);
+            }
+            Path previous = null;
+            for (Path file : files) {
+                if (previous != null && file.startsWith(previous)) {
+                    // Already added a parent directory.
+                    continue;
+                }
+                previous = file;
+                file = directory.relativize(file);
+                if (file.getNameCount() <= 1 && file.toString().isEmpty()) {
+                    /*
+                     * The `-C` directory itself (e.g. a "META-INF/versions/<n>" directory added as a whole).
+                     * An empty file argument is invalid for the `jar` tool (some implementations reject it,
+                     * others silently misbehave), so archive the whole directory content with ".".
+                     */
+                    file = Path.of(".");
+                }
+                addTo.add("-C");
+                addTo.add(directory);
+                addTo.add(file);
+            }
+        }
+
+        /**
+         * {@return a string representation for debugging purposes}
+         */
+        @Override
+        public String toString() {
+            return getClass().getSimpleName() + '[' + directory.getFileName() + ": " + files.size() + " files]";
+        }
+    }
+
+    /**
+     * Creates an initially empty set of files or directories.
+     *
+     * @param jarFile path to the <abbr>JAR</abbr> file to create
+     * @param moduleName the module name if using module hierarchy, or {@code null} if using package hierarchy
+     * @param version the target Java release, or {@code null} for the base version
+     * @param directory the directory of the classes targeting the base Java release
+     * @param forceCreation whether to force a new <abbr>JAR</abbr> file even if the content seems unchanged
+     * @param logger where to send a warning if an error occurred while checking an existing <abbr>JAR</abbr> file
+     */
+    @SuppressWarnings("checkstyle:NeedBraces")
+    Archive(
+            final Path jarFile,
+            final String moduleName,
+            final Runtime.Version version,
+            final Path directory,
+            final boolean forceCreation,
+            final Log logger) {
+        this.jarFile = jarFile;
+        this.moduleName = moduleName;
+        filesetForRelease = new TreeMap<>((v1, v2) -> {
+            if (v1 == v2) return 0;
+            if (v1 == null) return -1;
+            if (v2 == null) return +1;
+            return v1.compareTo(v2);
+        });
+        filesetForRelease.put(version, new FileSet(directory));
+        if (!forceCreation && Files.isRegularFile(jarFile)) {
+            try {
+                existingJAR = new TimestampCheck(jarFile, directory, logger);
+            } catch (IOException e) {
+                // Ignore, we will regenerate the JAR file.
+                logger.warn(e);
+            }
+        }
+    }
+
+    /**
+     * {@return the files or directories to store in the <abbr>JAR</abbr> file for targeting the base Java release}
+     *
+     * @throws NoSuchElementException should not happen unless {@link #prune(boolean)} has been invoked
+     */
+    FileSet baseRelease() {
+        Map.Entry<Runtime.Version, FileSet> entry = filesetForRelease.firstEntry();
+        String message = null;
+        if (entry != null) {
+            Runtime.Version version = entry.getKey();
+            if (version == null) {
+                return entry.getValue();
+            }
+            message = "Expected base version but found version " + version;
+        }
+        throw new NoSuchElementException(message);
+    }
+
+    /**
+     * Returns the {@code module-info.class} files. Conceptually, there is at most once such file per module.
+     * However, more than one file can exist if additional files are provided for additional Java releases.
+     * This method returns only the files that exist.
+     *
+     * @return all {@code module-info.class} files found for all target Java releases
+     */
+    public List<Path> moduleInfoFiles() {
+        var files = new ArrayList<Path>();
+        filesetForRelease.values().forEach((release) -> {
+            Path file = release.directory.resolve(FileCollector.MODULE_DESCRIPTOR_FILE_NAME);
+            if (Files.isRegularFile(file)) {
+                files.add(file);
+            }
+        });
+        return files;
+    }
+
+    /**
+     * Discards all files in this archive, normally because those files are not in any module.
+     * This method returns a common parent directory for all the files that were discarded.
+     * The caller should use that common directory for logging a warning message.
+     *
+     * @return common directory of discarded files, or {@code null} if none
+     */
+    Path discardAllFiles() {
+        Path base = null;
+        for (FileSet release : filesetForRelease.values()) {
+            base = release.discardAllFiles(base);
+        }
+        filesetForRelease.clear();
+        return base;
+    }
+
+    /**
+     * Removes all empty file sets 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}, then this method ensures that at least one file set
+     * remains even if that file set is empty.
+     *
+     * @param skipIfEmpty value of {@link AbstractJarMojo#skipIfEmpty}
+     */
+    public void prune(final boolean skipIfEmpty) {
+        FileSet keep = (skipIfEmpty || isEmpty())
+                ? null
+                : filesetForRelease.firstEntry().getValue();
+        filesetForRelease.values().removeIf((fs) -> fs.files.isEmpty());
+        Iterator<Map.Entry<Runtime.Version, FileSet>> it =
+                filesetForRelease.entrySet().iterator();
+        if (it.hasNext()) {
+            Map.Entry<Runtime.Version, FileSet> first = it.next();
+            if (first.getKey() == null) {
+                return; // Already contains an entry for the base version, nothing to do.
+            }
+            keep = first.getValue();
+            it.remove();
+        }
+        if (keep != null) {
+            filesetForRelease.put(null, keep);
+        }
+    }
+
+    /**
+     * {@return whether this archive has nothing to archive}
+     * This method can return {@code false} even when there is zero file to archive.
+     * It can happen if {@link AbstractJarMojo#skipIfEmpty} is {@code false}. In such case, the
+     * "empty" <abbr>JAR</abbr> file will still contain at {@code META-INF/MANIFEST.MF} file.
+     *
+     * <h4>Prerequisites</h4>
+     * The {@link #prune(boolean)} method should be invoked before this method for accurate result.
+     */
+    public boolean isEmpty() {
+        return filesetForRelease.isEmpty();
+    }
+
+    /**
+     * Checks whether the <abbr>JAR</abbr> file already exists and can be reused.
+     * This method verifies that the <abbr>JAR</abbr> file contains all the files to archive,
+     * contains no extra file, and no file to archive is newer than the <abbr>JAR</abbr> file.
+     *
+     * <p>This method can be invoked only once.
+     * If invoked more often, it returns {@code false} on all subsequent invocations.</p>
+     *
+     * @return whether the <abbr>JAR</abbr> file already exists and can be reused
+     */
+    public boolean isUpToDateJAR() {
+        final TimestampCheck tc = existingJAR;
+        if (tc == null) {
+            return false;
+        }
+        existingJAR = null; // Let GC do its job.
+        return tc.isUpToDateJAR(filesetForRelease.values());
+    }
+
+    /**
+     * Returns an initially empty set of files or directories for the specified target Java release.
+     *
+     * @param directory the base directory of the files to archive
+     * @param version the target Java release, or {@code null} for the base version
+     * @return container where to declare files and directories to archive
+     */
+    FileSet newTargetRelease(Path directory, Runtime.Version version) {
+        return filesetForRelease.computeIfAbsent(version, (key) -> new FileSet(directory));
+    }
+
+    /**
+     * Sets the {@code --main-class} option to the value of the {@code Main-Class} entry of the given manifest.
+     * As an extension, this method accepts the {@code module/classname} syntax (a syntax already used in some
+     * Java tools). If a module is specified, the main class is kept only if the module match. The intent is to
+     * allow users to specify on which module the main class applies when they use plugin configuration.
+     *
+     * <p>This method may modify the {@code content} manifest. Caller must ensure that the given manifest
+     * is not a shared instance. This method returns whether a change has actually been done.</p>
+     *
+     * @param content combination of existing {@code MANIFEST.MF} and manifest inferred from configuration, or null
+     * @return whether the given manifest has been modified by this method
+     */
+    boolean setMainClass(Manifest content) {
+        if (content == null || mainClass != null) {
+            return false;
+        }
+        // We need to remove the attribute, otherwise it will conflict with `--main-class`.
+        mainClass = (String) content.getMainAttributes().remove(Attributes.Name.MAIN_CLASS);
+        if (mainClass != null) {
+            int s = mainClass.indexOf('/');
+            if (s >= 0) {
+                if (mainClass.substring(0, s).strip().equals(moduleName)) {
+                    mainClass = mainClass.substring(s + 1).strip();
+                } else {
+                    mainClass = null; // Main class is defined for another module.
+                }
+            }
+        }
+        return mainClass != null;
+    }
+
+    /**
+     * Sets the {@code --manifest} option to the given value if that option was not already set.
+     *
+     * @param file path to the manifest file
+     * @param force whether to set the manifest even if already set
+     * @return whether the manifest has been set
+     */
+    boolean setManifest(Path file, boolean force) {
+        if (manifest == null || force) {
+            manifest = file;
+            return true;
+        }
+        return false;
+    }
+
+    /**
+     * Merges the manifest of this module with the manifest specified in plugin configuration.
+     * If both {@code file} and {@code content} are non-null, then {@code content} must be the
+     * result of reading {@code file}.
+     *
+     * <p>This method never modifies the given {@code content} object. If manifest are merged,

Review Comment:
   Done.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3923347036


##########
src/main/java/org/apache/maven/plugins/jar/TimestampCheck.java:
##########
@@ -0,0 +1,261 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.nio.file.attribute.FileTime;
+import java.util.Collection;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+
+import org.apache.maven.api.plugin.Log;
+
+/**
+ * Checks file timestamps in order to determine if anything changed compared to an existing <abbr>JAR</abbr> file.
+ * This class may scan directories, but only if they have not already been visited by {@link FileCollector}.
+ * The latter can only occur if {@link FileCollector} has no {@code PathMatcher}.
+ * Therefore, this class uses no {@code PathMatcher}.
+ *
+ * <h2>Ignore files</h2>
+ * The {@code META-INF/MANIFEST.MF} file and the {@code META-INF/maven/} directory are ignored.
+ * See {@link #isIgnored(Path)} for the rational.
+ */
+final class TimestampCheck extends SimpleFileVisitor<Path> {
+    /**
+     * The base directory of archived files.
+     */
+    private final Path classesDir;
+
+    /**
+     * Path to the existing <abbr>JAR</abbr> file.
+     */
+    private final Path jarFile;
+
+    /**
+     * The last modified time of the <abbr>JAR</abbr> file.
+     */
+    private final FileTime jarFileTime;
+
+    /**
+     * Where to send non-fatal error messages.
+     */
+    private final Log logger;
+
+    /**
+     * Entries of the <abbr>JAR</abbr> file. Note that getting elements from this enumeration can be costly.
+     * Therefore, we only fetch elements when needed.
+     */
+    private Enumeration<? extends ZipEntry> entries;
+
+    /**
+     * Files found in the <abbr>JAR</abbr> file but not yet traversed by the file visitor.
+     * Files are added lazily when needed, and removed as soon as they have been traversed.
+     * Path are absolute (resolved with {@link #classesDir}).
+     * For each entry, the associated value is whether the path is a directory.
+     */
+    private final Map<Path, Boolean> filesInJAR;
+
+    /**
+     * Some of the files in the build directory. This list contains only the files for which we have already
+     * verified the timestamp. We store them in a separate list for avoiding to check the timestamp twice.
+     * We need this list because we still need to verify if the files are in the {@link #jarFile}.
+     * For each entry, the associated value is whether the path is a directory.
+     */
+    private final Map<Path, Boolean> filesInBuild;
+
+    /**
+     * Whether at least one file is more recent than the <abbr>JAR</abbr> file.
+     * The scan of files will stop quickly after this flag become {@code true}.
+     */
+    private boolean hasUpdates;
+
+    /**
+     * Creates a new visitor for checking the validity of a <abbr>JAR</abbr> file.
+     *
+     * @param jarFile the existing <abbr>JAR</abbr> file
+     * @param jarFileTime the last modified time of the <abbr>JAR</abbr> file
+     * @param classesDir base directory of archived files
+     * @param logger where to send a warning if an error occurred while checking an existing <abbr>JAR</abbr> file
+     * @throws IOException if an error occurred while fetching the <abbr>JAR</abbr> file modification time
+     */
+    TimestampCheck(final Path jarFile, final Path classesDir, final Log logger) throws IOException {
+        this.classesDir = classesDir;
+        this.jarFile = jarFile;
+        this.logger = logger;
+        jarFileTime = Files.getLastModifiedTime(jarFile);
+        filesInJAR = new HashMap<>();
+        filesInBuild = new HashMap<>();
+    }
+
+    /**
+     * Returns {@code true} if the given file is more recent that the <abbr>JAR</abbr> file.
+     *
+     * @param file the file to check
+     * @param attributes the file's basic attributes
+     * @param isDirectory whether the file is a directory
+     * @return whether the modification time is more recent than the <abbr>JAR</abbr> file
+     */
+    boolean isUpdated(final Path file, final BasicFileAttributes attributes, final boolean isDirectory) {
+        if (jarFileTime.compareTo(attributes.lastModifiedTime()) < 0) {
+            return true;
+        }
+        filesInBuild.put(file, isDirectory);
+        return false;
+    }
+
+    /**
+     * Checks if the <abbr>JAR</abbr> file contains all the given files, no extra entry, and no outdated entry.

Review Comment:
   Done.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "hboutemy (via GitHub)" <gi...@apache.org>.
hboutemy commented on PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#issuecomment-5338357796

   it seems I'll have to revisit Reproducible Builds for the jar plugin: after so many years of success, this looks like a regression that is so tiring to have to work back on :/ ... but I suppose better Java Module support deserves such efforts
   
   in the past, we did some JDK detection to patch when using JDK earlier than 18 https://issues.apache.org/jira/browse/MJAR-275
   perhaps we'll have to do some equivalent tweaks
   


-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3805948497


##########
src/main/java/org/apache/maven/plugins/jar/AbstractJarMojo.java:
##########
@@ -72,23 +72,20 @@ public abstract class AbstractJarMojo implements org.apache.maven.api.plugin.Moj
     protected String[] excludes;
 
     /**
-     * Directory containing the generated JAR.
+     * Directory containing the generated <abbr>JAR</abbr> files.
      */
     @Parameter(defaultValue = "${project.build.directory}", required = true)
     protected Path outputDirectory;
 
     /**
-     * Name of the generated JAR.
+     * Name of the generated <abbr>JAR</abbr> file.

Review Comment:
   Indeed, the usefulness of `<abbr>` without `title` is uncertain. I sometime use `<abbr>` anyway in the hope to give a very slight help to the robots with the semantic. It would also be possible in the future, if we wanted, to have a doclet adding the `title` automatically at javadoc generation time.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#issuecomment-5345187466

   > if this true?
   
   Not any more. When I wrote this comment, I was not aware of [JDK-8276764](https://bugs.openjdk.org/browse/JDK-8276764). The proposal to apply a post-processing step is obsolete now.


-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "rmannibucau (via GitHub)" <gi...@apache.org>.
rmannibucau commented on PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#issuecomment-5361141133

   > IMO it's critical to support binary reproducibility for all JDKs since minimal 17, otherwise it'll be a regression.
   
   stating that for maven 4 java 17 bytecode is supported using a java 21 or more (to speak "LTS") doesn't sound crazy to me
   also agree it is reproducible only for the same JVM baseline (not even minor matching) so on my side it stays not critical since covered technically if well documented
   
   > like moditect for example
   
   ZipFileSystem#sync can be worth benching on a big jar (some thousands of classes), ideally it is very small compared to producing the zip (jar) itself but worth evaluating before thinking this is an option IMHO - since we know we can always do it right directly if needed and JDK version is a blocker (once again not for me)


-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "hboutemy (via GitHub)" <gi...@apache.org>.
hboutemy commented on PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#issuecomment-5352213156

   continuing my base test (no MR or modular build yet, just basic classic jars)
   
   rebuilding on a Mac in parallel of a Linux box with JDK 21 gave me same output: great, we have the output stability that I expect and got until now
   
   So definitively, the JDK 17 and 18 reproducibility issue is what has to be solved for now
   
   
   We'll see in a second step about modular or MR jars: if someone can point me to a simple project that I can build mself easily, that would be nice, please
   
   
   one issue I get is twice attach:
   ```
   [INFO] --- jar:4.0.0-beta-2-SNAPSHOT:jar (default-jar) @ maven-dependency-analyzer ---
   [INFO] Building JAR: "target/maven-dependency-analyzer-1.17.2-SNAPSHOT.jar".
   [WARNING] artifact 'org.apache.maven.shared:maven-dependency-analyzer:pom:consumer:1.17.2-SNAPSHOT' already attached, replacing previous instance
   ```
   that is also visible in the `artifact:3.6.1:describe-build-output` too: and the message that says "replacing" is apparently not replacing but adding another attach
   but perhaps it's more a Maven 4.0..0-rc-6 bug: if I drop the `artifact:3.6.1:describe-build-output` goal to the `mvn` command, this issue disappears
   I'll open a Maven issue for that


-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "jaikiran (via GitHub)" <gi...@apache.org>.
jaikiran commented on PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#issuecomment-5354533866

   Hello Martin,
   
   > And since the file ordering issue (JDK-8276764) was fixed in JDK 18 only, even if we fix the timestamp the build would still non-reproducible on JDK 17. 
   
   Bug fixes/enhancements in the JDK are sometimes backported. Those backports are tracked/linked against the original issue. For this specific issue, under the issue description, there's a backports section which shows that this enhancement was backported in JDK 17 too (the Resolved/Fixed status on those backports is a sign that the work is complete).
   
   Having said that, my comment is mostly informational and isn't meant as an input to whether or not some post processing should be done for the JAR files.


-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "hboutemy (via GitHub)" <gi...@apache.org>.
hboutemy commented on PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#issuecomment-5312740419

   I'm having hard time at testing, so I'll ask:
   in this new implementation, is the MANIFEST.MF content still generated first by our usual tooling, then only added to the jar and tidied up by `jar` tool?
   said another way: do we get a maximum compatibility against configuration done until now?


-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3891585394


##########
src/main/java/org/apache/maven/plugins/jar/AbstractJarMojo.java:
##########
@@ -18,44 +18,44 @@
  */
 package org.apache.maven.plugins.jar;
 
-import java.io.File;
 import java.io.IOException;
 import java.nio.file.Files;
 import java.nio.file.Path;
+import java.time.Instant;
 import java.util.Arrays;
+import java.util.List;
 import java.util.Map;
-import java.util.Objects;
-import java.util.jar.Attributes;
-import java.util.stream.Stream;
+import java.util.spi.ToolProvider;
 
+import org.apache.maven.api.PathScope;
 import org.apache.maven.api.ProducedArtifact;
 import org.apache.maven.api.Project;
 import org.apache.maven.api.Session;
+import org.apache.maven.api.Type;
 import org.apache.maven.api.di.Inject;
 import org.apache.maven.api.plugin.Log;
 import org.apache.maven.api.plugin.MojoException;
 import org.apache.maven.api.plugin.annotations.Parameter;
+import org.apache.maven.api.services.PathMatcherFactory;
 import org.apache.maven.api.services.ProjectManager;
 import org.apache.maven.shared.archiver.MavenArchiveConfiguration;
 import org.apache.maven.shared.archiver.MavenArchiver;
-import org.apache.maven.shared.archiver.MavenArchiverException;
-import org.apache.maven.shared.model.fileset.FileSet;
-import org.apache.maven.shared.model.fileset.util.FileSetManager;
-import org.codehaus.plexus.archiver.Archiver;
-import org.codehaus.plexus.archiver.jar.JarArchiver;
 
 /**
  * Base class for creating a <abbr>JAR</abbr> file from project classes.
  *
  * @author <a href="evenisse@apache.org">Emmanuel Venisse</a>
+ * @author Martin Desruisseaux
  */
 public abstract class AbstractJarMojo implements org.apache.maven.api.plugin.Mojo {
-
-    private static final String[] DEFAULT_EXCLUDES = new String[] {"**/package.html"};
-
-    private static final String[] DEFAULT_INCLUDES = new String[] {"**/**"};
-
-    private static final String MODULE_DESCRIPTOR_FILE_NAME = "module-info.class";
+    /**
+     * Identifier of the tool to use. This identifier shall match the identifier of a tool

Review Comment:
   Replaced all occurrences of "shall" by "must".



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3891821055


##########
src/main/java/org/apache/maven/plugins/jar/AbstractJarMojo.java:
##########
@@ -207,167 +205,208 @@ protected final Log getLog() {
     protected abstract String getType();
 
     /**
-     * Returns the JAR file to generate, based on an optional classifier.
+     * {@return the scope of dependencies}
+     * It should be {@link PathScope#MAIN_COMPILE} or {@link PathScope#TEST_COMPILE}.
+     * Note that we use compile scope rather than runtime scope because dependencies
+     * cannot appear in {@code requires} statement if they didn't had compile scope.
+     */
+    protected abstract PathScope getDependencyScope();
+
+    /**
+     * {@return the JAR tool to use for archiving the code}
      *
-     * @param basedir the output directory
-     * @param resultFinalName the name of the JAR file
-     * @param classifier an optional classifier
-     * @return the file to generate
+     * @throws MojoException if no JAR tool was found
+     *
+     * @since 4.0.0-beta-2
      */
-    protected Path getJarFile(Path basedir, String resultFinalName, String classifier) {
-        Objects.requireNonNull(basedir, "basedir is not allowed to be null");
-        Objects.requireNonNull(resultFinalName, "finalName is not allowed to be null");
-        String fileName = resultFinalName + (hasClassifier(classifier) ? '-' + classifier : "") + ".jar";
-        return basedir.resolve(fileName);
+    protected ToolProvider getJarTool() throws MojoException {
+        return ToolProvider.findFirst(toolId).orElseThrow(() -> new MojoException("No such \"" + toolId + "\" tool."));
     }
 
     /**
-     * Generates the JAR.
+     * Returns the output time stamp or, as a fallback, the {@code SOURCE_DATE_EPOCH} environment variable.

Review Comment:
   Done as suggested.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3891895435


##########
src/main/java/org/apache/maven/plugins/jar/Archive.java:
##########
@@ -0,0 +1,692 @@
+/*
+ * 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.jar;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.TreeMap;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.Type;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.MojoException;
+
+/**
+ * Files or root directories to archive for a single module.
+ * A single instance of {@code Archive} may contain many directories for different target Java releases.
+ * Many instances of {@code Archive} may exist when archiving a multi-modules project.
+ */
+final class Archive {
+    /**
+     * Whether to repeat the {@code -C} option before each file.
+     * Doing so makes the command-line very verbose while the documentation of
+     * <a href="https://docs.oracle.com/en/java/javase/25/docs/specs/man/jar.html">The jar Command</a>
+     * gives the impression that this option can be provided only once.
+     * However, our tests suggest that the first file after the directory specified by the {@code -C} option
+     * must be relative to that directory and all files after the first one must be prefixed by the directory
+     * which was specified in the {@code -C} option. This behavior is not documented, but we couldn't get the
+     * {@code jar} tool to work otherwise (except by repeating {@code -C} before each file).
+     * Furthermore, it seems that the relativized file needs to be the shortest one,
+     * otherwise the {@code jar} tool rejects files after the first one with "names do not match".
+     * Which file is first depends on the unspecified directory-iteration order.
+     *
+     * <p>If this flag is {@code true}, the plugin repeats {@code -C} before each file.
+     * This flag should be set to {@code false} if a future version of the {@code jar}
+     * tool allows to specify {@code -C} only once.</p>
+     *
+     * <p><b>Historical note:</b> we also tried to relativize only the first file after {@code -C}
+     * and keep all subsequent files as absolute. It works, but because we have to repeat the directory
+     * in the file name, it saves only 3 or 4 characters per file compared to repeating {@code -C}.</p>
+     */
+    private static final boolean REPEAT_C = true;
+
+    /**
+     * Path to the <abbr>POM</abbr> file generated for this archive, or {@code null} if none.
+     * This is non-null only if module source hierarchy is used, in which case the dependencies
+     * declared in this file are the intersection of the project dependencies and the content of
+     * the {@code module-info.class} file.
+     */
+    @Nullable
+    Path pomFile;
+
+    /**
+     * The <var>JAR</var> file to create. May be an existing file,

Review Comment:
   Replaced by "can".



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3892030267


##########
src/main/java/org/apache/maven/plugins/jar/FileCollector.java:
##########
@@ -0,0 +1,496 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.PathMatcher;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayDeque;
+import java.util.Deque;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.services.PathMatcherFactory;
+
+/**
+ * Dispatch the files in the output directory into the <abbr>JAR</abbr> files to create.
+ * Instead of just archiving as-is the content of the output directory, this class separates
+ * the following subdirectories to the options listed below:
+ *
+ * <ul>
+ *   <li>The {@code META-INF/MANIFEST.MF} file will be given to the {@code --manifest} option.</li>
+ *   <li>Files in the following directories will be given to the {@code --release} option:
+ *     <ul>
+ *       <li>{@code META-INF/versions/}</li>
+ *       <li>{@code META-INF/versions-modular/<module>/}</li>
+ *       <li>{@code <module>/META-INF/versions/}</li>
+ *     </ul>
+ *   </li>
+ * </ul>
+ *
+ * The reason for using the options is that they allow the {@code jar} tool to perform additional verifications.
+ * For example, when using the {@code --release} option, {@code jar} verifies the <abbr>API</abbr> compatibility.
+ */
+final class FileCollector extends SimpleFileVisitor<Path> {
+    /**
+     * The file to check for deciding whether the <abbr>JAR</abbr> is modular.
+     */
+    static final String MODULE_DESCRIPTOR_FILE_NAME = "module-info.class";
+
+    /**
+     * The {@value} directory.
+     * This is part of <abbr>JAR</abbr> file specification.
+     */
+    private static final String VERSIONS = "versions";
+
+    /**
+     * The {@value} directory.
+     * This is Maven-specific.
+     */
+    private static final String VERSIONS_MODULAR = "versions-modular";
+
+    /**
+     * Context (logger, configuration) in which the <abbr>JAR</abbr> file are created.
+     */
+    private final ToolExecutor context;
+
+    /**
+     * Whether to detect multi-release <abbr>JAR</abbr> files.
+     * The default value is {@code true}.
+     *
+     * @see AbstractJarMojo#detectMultiReleaseJar
+     */
+    private final boolean detectMultiReleaseJar;
+
+    /**
+     * Combination of includes and excludes path matcher applied on files.
+     */
+    @Nonnull
+    private final PathMatcher fileMatcher;
+
+    /**
+     * Combination of includes and excludes path matcher applied on directories.
+     */
+    @Nonnull
+    private final PathMatcher directoryMatcher;
+
+    /**
+     * Whether the matchers accept all files and there is no need to sort the files.
+     * In such case, we can declare whole directories to the {@code jar} tool instead
+     * of scanning the directory tree ourselves.
+     */
+    private final boolean addDirectories;
+
+    /**
+     * Files found in the output directory when package hierarchy is used.
+     * At most one of {@code packageHierarchy} and {@link #moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Archive packageHierarchy;
+
+    /**
+     * Files found in the output directory when module hierarchy is used. Keys are module names.
+     * At most one of {@link #packageHierarchy} and {@code moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Map<String, Archive> moduleHierarchy;
+
+    /**
+     * The current module being archived. This field is updated every times that {@code FileCollector}
+     * enters in a new module directory.
+     */
+    @Nonnull
+    private Archive currentModule;
+
+    /**
+     * The module and target Java release currently being scanned. This field is updated every times that
+     * {@code FileCollector} enters in a new module directory or in a new target Java release for a given module.
+     */
+    @Nonnull
+    private Archive.FileSet currentFilesToArchive;
+
+    /**
+     * The current target Java release, or {@code null} if none.
+     */
+    @Nullable
+    private Runtime.Version currentTargetVersion;
+
+    /**
+     * Identification of the kinds of directories being traversed.
+     * The length of this list is the depth in the directory hierarchy.
+     * The last element identifies the type of the current directory.
+     */
+    private final Deque<DirectoryRole> directoryRoles;
+
+    /**
+     * Whether to check when a file is the {@code MANIFEST.MF} file.
+     * This is allowed only when scanning the content of a {@code META-INF} directory.
+     */
+    private boolean checkForManifest;
+
+    /**
+     * Creates a new file collector.
+     *
+     * @param mojo the <abbr>MOJO</abbr> from which to get the configuration
+     * @param context context (logger, configuration) in which the <abbr>JAR</abbr> file are created
+     * @param directory the base directory of the files to archive
+     */
+    FileCollector(AbstractJarMojo mojo, ToolExecutor context, Path directory, PathMatcherFactory matcherFactory) {
+        this.context = context;
+        detectMultiReleaseJar = mojo.detectMultiReleaseJar;
+        directoryRoles = new ArrayDeque<>();
+        fileMatcher = matcherFactory.createPathMatcher(directory, mojo.getIncludes(), mojo.getExcludes(), false);
+        directoryMatcher = matcherFactory.deriveDirectoryMatcher(fileMatcher);
+        addDirectories = !context.isReproducible()
+                && matcherFactory.isIncludesAll(fileMatcher)
+                && matcherFactory.isIncludesAll(directoryMatcher);
+        packageHierarchy = context.newArchive(null, null, directory);
+        moduleHierarchy = new LinkedHashMap<>();
+        resetToPackageHierarchy();
+    }
+
+    /**
+     * Resets this {@code FileCollector} to the state where a package hierarchy is presumed.
+     */
+    private void resetToPackageHierarchy() {
+        currentModule = packageHierarchy;
+        currentFilesToArchive = currentModule.baseRelease();
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a module.
+     * For an output generated by {@code javac} from a module source hierarchy,
+     * the directory name is guaranteed to be the module name.
+     *
+     * @param directory a {@code "<module>"} or {@code "META-INF/versions-modular/<module>"} directory
+     */
+    private void enterModuleDirectory(final Path directory) {
+        String moduleName = directory.getFileName().toString();
+        currentModule = moduleHierarchy.computeIfAbsent(
+                moduleName, (name) -> context.newArchive(name, currentTargetVersion, directory));
+        currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a target Java version.
+     * The {@code useDirectly} argument tells whether the content of this directory will be specified directly
+     * as the content to add in the <abbr>JAR</abbr> file. This argument should be {@code false} when there is
+     * another directory level (the module names) to process before to add content.
+     *
+     * @param directory a {@code "META-INF/versions/<n>"} or {@code "META-INF/versions-modular/<n>"} directory
+     * @param useDirectly whether the directory is {@code "META-INF/versions/<n>"}
+     * @return whether to skip the directory because of invalid version number
+     */
+    private boolean enterVersionDirectory(final Path directory, final boolean useDirectly) {
+        try {
+            currentTargetVersion = Runtime.Version.parse(directory.getFileName().toString());
+        } catch (IllegalArgumentException e) {
+            context.warnInvalidVersion(directory, e);
+            return true;
+        }
+        if (useDirectly) {
+            currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+        }
+        return false;
+    }
+
+    /**
+     * Determines if the given directory should be scanned for files to archive.
+     * This method may also update {@link #currentFilesToArchive} if it detects
+     * that we are entering in a new module or a new target Java release.
+     *
+     * @param directory the directory which will be traversed
+     * @param attributes the directory's basic attributes
+     */
+    @Override
+    @SuppressWarnings("checkstyle:MissingSwitchDefault")
+    public FileVisitResult preVisitDirectory(final Path directory, final BasicFileAttributes attributes)
+            throws IOException {
+        DirectoryRole role;
+        if (directoryRoles.isEmpty()) {
+            role = DirectoryRole.ROOT;
+        } else {
+            if (!directoryMatcher.matches(directory)) {
+                return FileVisitResult.SKIP_SUBTREE;
+            }
+            checkForManifest = false;
+            role = directoryRoles.getLast();
+            switch (role) {
+                case ROOT:
+                    /*
+                     * Entering in any subdirectory of `target/classes` (or other directory to archive).
+                     * We need to handle `META-INF` and modules in a special way, and archive the rest.
+                     */
+                    if (directory.endsWith(MetadataFiles.META_INF)) {
+                        role = DirectoryRole.META_INF;
+                        checkForManifest = true;
+                    } else if (Files.isRegularFile(directory.resolve(MODULE_DESCRIPTOR_FILE_NAME))) {
+                        role = DirectoryRole.NAMED_MODULE;
+                        enterModuleDirectory(directory);
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case META_INF:
+                    /*
+                     * Entering in a subdirectory of `META-INF` or `<module>/META-INF`. We will need to handle
+                     * `MANIFEST.MF`, `versions` and `versions-modular` in a special way, and archive the rest.
+                     */
+                    if (detectMultiReleaseJar && directory.endsWith(VERSIONS)) {
+                        role = DirectoryRole.VERSIONS;
+                    } else if (directory.endsWith(VERSIONS_MODULAR)) {
+                        if (!detectMultiReleaseJar) {
+                            // Used asked for no multi-release JAR.
+                            return FileVisitResult.SKIP_SUBTREE;
+                        }
+                        role = DirectoryRole.VERSIONS_MODULAR;
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case VERSIONS:
+                    /*
+                     * Entering in a `META-INF/versions/<n>/` directory for a specific target Java release.
+                     * May also be a `<module>/META-INF/versions/<n>/` directory, even if the latter is not
+                     * the layout generated by Maven Compiler Plugin.
+                     */
+                    if (enterVersionDirectory(directory, true)) {
+                        // An error occurred while parsing the version number.
+                        return FileVisitResult.SKIP_SUBTREE;
+                    }
+                    role = DirectoryRole.RESOURCES;
+                    break;
+
+                case VERSIONS_MODULAR:
+                    /*
+                     * Entering in a `META-INF/versions-modular/<n>/` directory for a specific target Java release.
+                     * That directory contains all modules for the version.
+                     */
+                    resetToPackageHierarchy(); // No module in particular yet.
+                    if (enterVersionDirectory(directory, false)) {
+                        // An error occurred while parsing the version number.
+                        return FileVisitResult.SKIP_SUBTREE;
+                    }
+                    role = DirectoryRole.MODULES;
+                    break;
+
+                case MODULES:
+                    /*
+                     * Entering in a `META-INF/versions-modular/<n>/<module>` directory.
+                     */
+                    enterModuleDirectory(directory);
+                    role = DirectoryRole.NAMED_MODULE;
+                    break;
+
+                case NAMED_MODULE:
+                    /*
+                     * Entering in a `<module>` or `META-INF/versions-modular/<n>/<module>` subdirectory.
+                     * A module could have its own `META-INF` subdirectory, so we need to check again.
+                     */
+                    if (directory.endsWith(MetadataFiles.META_INF)) {
+                        role = DirectoryRole.META_INF;
+                        checkForManifest = true;
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+            }
+        }
+        /*
+         * Do not move this condition inside the `switch` block because `role` may have been modified.
+         * The `role` value is now the role of `directory`, not anymore the role of parent directory.
+         */
+        if (addDirectories && role == DirectoryRole.RESOURCES) {
+            currentFilesToArchive.add(directory, attributes, true);
+            /*
+             * Since we are skipping the whole directory, `postVisitDirectory(…)` will not be invoked.
+             * We must reset `currentFilesToArchive` and `currentTargetVersion` by an explicit call.
+             * This is important mostly after we added a whole `META-INF/versions/<n>` directory,
+             * otherwise base files visited afterwards (directory iteration order is unspecified)
+             * would be added to this version's file set instead of the base release.
+             */
+            resetToParentDirectoryState();
+            return FileVisitResult.SKIP_SUBTREE;
+        } else {
+            directoryRoles.addLast(role);
+            return FileVisitResult.CONTINUE;
+        }
+    }
+
+    /**
+     * Updates the {@code FileCollector} state after we finished to scan the content of a directory.
+     * The fields to update depend on which directory has been visited (module, version, <i>etc.</i>).
+     *
+     * @param directory the directory which has been traversed
+     * @param error the error that occurred while traversing the directory, or {@code null} if none
+     */
+    @Override
+    public FileVisitResult postVisitDirectory(final Path directory, final IOException error) throws IOException {
+        if (error != null) {
+            throw error;
+        }
+        switch (directoryRoles.removeLast()) {
+            case NAMED_MODULE:
+                // Exited the directory of a single module.
+                resetToPackageHierarchy();
+                break;
+
+            case ROOT:
+                break;
+
+            default:
+                resetToParentDirectoryState();
+        }
+        return FileVisitResult.CONTINUE;
+    }
+
+    /**
+     * Updates {@code FileCollector} to a state suitable to the parent of the directory that we finished to scan.
+     * Contrarily to {@link #postVisitDirectory(Path, IOException)}, this method expects the last element of
+     * {@link #directoryRoles} to describe the parent directory, not the directory that we finished to visit.
+     */
+    @SuppressWarnings("checkstyle:MissingSwitchDefault")
+    private void resetToParentDirectoryState() {
+        switch (directoryRoles.getLast()) {
+            case VERSIONS:
+            case VERSIONS_MODULAR:
+                // Exited the directory for one target Java release.
+                currentFilesToArchive = currentModule.baseRelease();
+                currentTargetVersion = null;
+                break;
+
+            case META_INF:
+                checkForManifest = true;
+                break;
+        }
+    }
+
+    /**
+     * Archives a single file if accepted by the matcher.
+     *
+     * @param file the file
+     * @param attributes the file's basic attributes
+     */
+    @Override
+    public FileVisitResult visitFile(final Path file, final BasicFileAttributes attributes) {
+        if (fileMatcher.matches(file)) {
+            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.add(file, attributes, false);
+            }
+        }
+        return FileVisitResult.CONTINUE;
+    }
+
+    /**
+     * 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}, then this method ensures that at least one archive
+     * remains even if that archive is empty.
+     *
+     * @param skipIfEmpty value of {@link AbstractJarMojo#skipIfEmpty}
+     */
+    public void prune(boolean skipIfEmpty) {
+        boolean isModuleHierarchy = !moduleHierarchy.isEmpty();
+        moduleHierarchy.values().forEach((archive) -> archive.prune(skipIfEmpty));
+        moduleHierarchy.values().removeIf(Archive::isEmpty);
+        packageHierarchy.prune(isModuleHierarchy || skipIfEmpty);
+    }
+
+    /**
+     * Moves, copies or ignores orphan files.
+     * An orphan file is a file which is not in any module when module hierarchy is used.
+     * For example, some Maven plugins may create files such as {@code META-INF/LICENSE},
+     * {@code META-INF/NOTICE} or {@code META-INF/DEPENDENCIES}. These files are not in
+     * the correct directory (they should be in a {@code "<module>/META-INF"} directory)
+     * because the plugin may not be aware of module hierarchy.
+     *
+     * <p>A possible strategy could be to copy the {@code LICENSE} and {@code NOTICE} files
+     * in each module, and ignore the {@code DEPENDENCIES} file because its content is not
+     * correct for a module. For now, we just log a warning an ignore.</p>
+     *
+     * <h4>Prerequisites</h4>
+     * The {@link #prune(boolean)} method should have been invoked once before to invoke this method.

Review Comment:
   done



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3949076575


##########
src/main/java/org/apache/maven/plugins/jar/ExcludedFiles.java:
##########
@@ -0,0 +1,146 @@
+/*
+ * 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.jar;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardCopyOption;
+import java.util.List;
+
+/**
+ * A list of files to temporarily move outside the directory to package in a <abbr>JAR</abbr> archive.
+ * This class is needed when the {@link AbstractJarMojo} configuration has include or exclude filters.
+ * Excluded files are temporarily moved outside the directory to archive.
+ * We move these files for making possible to specify the whole directory to the {@code jar} tool.
+ * This approach is used instead of enumerating files in arguments given to the {@code jar} tool because
+ * such enumeration cannot contain directory entries (otherwise the whole directory would be included).
+ * Some software such as Spring applications component scan relies on the presence of directory entries.
+ */
+final class ExcludedFiles implements Closeable {
+    /**
+     * The paths of files or directories to temporarily move in another directory.
+     */
+    private final Path[] original;
+
+    /**
+     * The paths where files or directories were moved.
+     * For each index <var>i</var>, the original path of {@code moved[i]} was {@code original[i]}.
+     */
+    private final Path[] moved;
+
+    /**
+     * Temporary directory which will contain the {@code moved} files.
+     * It should be a parent directory of {@link #original} files for
+     * increasing the chances that it is on the same file system.
+     */
+    private final Path temporaryDirectory;
+
+    /**
+     * Index of the first path which is a directory instead of a file.
+     * All paths before this index in the {@link #original} and {@link #moved} arrays are files.
+     * All paths at this index and after this index are directories.
+     */
+    private final int indexOfFirstDirectory;
+
+    /**
+     * Creates a new list of files to move in a temporary directory.
+     *
+     * @param directory the directory which was scanned for files to include in the <abbr>JAR</abbr>
+     * @param excludedFiles paths of files to temporarily move in another directory

Review Comment:
   Done.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3949128710


##########
src/main/java/org/apache/maven/plugins/jar/FileCollector.java:
##########
@@ -0,0 +1,542 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.PathMatcher;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Deque;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.services.PathMatcherFactory;
+
+/**
+ * Dispatch the files from the output directory into the <abbr>JAR</abbr> files to create.

Review Comment:
   I will try "Distribute".



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3891950110


##########
src/main/java/org/apache/maven/plugins/jar/Archive.java:
##########
@@ -0,0 +1,692 @@
+/*
+ * 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.jar;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.TreeMap;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.Type;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.MojoException;
+
+/**
+ * Files or root directories to archive for a single module.
+ * A single instance of {@code Archive} may contain many directories for different target Java releases.
+ * Many instances of {@code Archive} may exist when archiving a multi-modules project.
+ */
+final class Archive {
+    /**
+     * Whether to repeat the {@code -C} option before each file.
+     * Doing so makes the command-line very verbose while the documentation of
+     * <a href="https://docs.oracle.com/en/java/javase/25/docs/specs/man/jar.html">The jar Command</a>
+     * gives the impression that this option can be provided only once.
+     * However, our tests suggest that the first file after the directory specified by the {@code -C} option
+     * must be relative to that directory and all files after the first one must be prefixed by the directory
+     * which was specified in the {@code -C} option. This behavior is not documented, but we couldn't get the
+     * {@code jar} tool to work otherwise (except by repeating {@code -C} before each file).
+     * Furthermore, it seems that the relativized file needs to be the shortest one,
+     * otherwise the {@code jar} tool rejects files after the first one with "names do not match".
+     * Which file is first depends on the unspecified directory-iteration order.
+     *
+     * <p>If this flag is {@code true}, the plugin repeats {@code -C} before each file.
+     * This flag should be set to {@code false} if a future version of the {@code jar}
+     * tool allows to specify {@code -C} only once.</p>
+     *
+     * <p><b>Historical note:</b> we also tried to relativize only the first file after {@code -C}
+     * and keep all subsequent files as absolute. It works, but because we have to repeat the directory
+     * in the file name, it saves only 3 or 4 characters per file compared to repeating {@code -C}.</p>
+     */
+    private static final boolean REPEAT_C = true;
+
+    /**
+     * Path to the <abbr>POM</abbr> file generated for this archive, or {@code null} if none.
+     * This is non-null only if module source hierarchy is used, in which case the dependencies
+     * declared in this file are the intersection of the project dependencies and the content of
+     * the {@code module-info.class} file.
+     */
+    @Nullable
+    Path pomFile;
+
+    /**
+     * The <var>JAR</var> file to create. May be an existing file,
+     * in which case the file creation may be skipped if the file is still up-to-date.
+     */
+    @Nonnull
+    final Path jarFile;
+
+    /**
+     * A helper class for checking whether an existing <abbr>JAR</abbr> file is still up-to-date.
+     * This is null if there is no existing JAR file, or if we determined that the file is outdated.
+     */
+    private TimestampCheck existingJAR;
+
+    /**
+     * Name of the module being archived when the project is using module hierarchy.
+     * This is {@code null} if the project is using package hierarchy, either because it is a classical
+     * class-path project or because it is a single module compiled without using the module hierarchy.
+     * When using module source hierarchy, {@code javac} guarantees that the module name in the output
+     * directory is the name of the parent directory of {@code module-info.class}.
+     */
+    @Nullable
+    final String moduleName;
+
+    /**
+     * Path to {@code META-INF/MANIFEST.MF}, or {@code null} if none.
+     * If non-null, this value will be given to the {@code --manifest} option.
+     * The use of this option is preferable to adding {@code MANIFEST.MF} as an ordinary file.
+     *
+     * @see #setManifest(Path, boolean)
+     * @see #mergeManifest(Path, Manifest)
+     */
+    @Nullable
+    private Path manifest;
+
+    /**
+     * The Maven generated {@code pom.xml} and {@code pom.properties} files, or {@code null} if none.
+     * This first item shall be the base directory where the files are located.
+     */
+    @Nullable
+    List<Path> mavenFiles;
+
+    /**
+     * Fully-qualified name of the main class, or {@code null} if none.
+     * This is the value to provide to the {@code --main-class} option.
+     */
+    private String mainClass;
+
+    /**
+     * Files or root directories to store in the <abbr>JAR</abbr> file for each target Java release
+     * other than the base release. Keys are the target Java release with {@code null} for the base
+     * release.
+     */
+    @Nonnull
+    private final NavigableMap<Runtime.Version, FileSet> filesetForRelease;
+
+    /**
+     * Files or root directories to archive for a single target Java release of a single module.
+     * The {@link Archive} enclosing shall contain at least one instance of {@code FileSet} for
+     * the base release, and an arbitrary amount of other instances for other target releases.
+     */
+    final class FileSet {
+        /**
+         * A comparator for sorting paths in a reproducible order.
+         * This comparator assumes that all paths are relative to the same base directory (this is not verified).
+         * Note: we do not use {@link Path#compareTo(Path)} because the Javadoc said that it is platform dependent.
+         */
+        private static final Comparator<Path> REPRODUCIBLE_ORDER = (p1, p2) -> {
+            final int c1 = p1.getNameCount();
+            final int c2 = p2.getNameCount();
+            final int c = Math.min(c1, c2);
+            for (int i = 0; i < c; i++) {
+                String n1 = p1.getName(i).toString();
+                String n2 = p2.getName(i).toString();
+                int r = n1.compareTo(n2); // Case-sensitive comparison on all platforms.
+                if (r != 0) {
+                    return r;
+                }
+            }
+            return c1 - c2;
+        };
+
+        /**
+         * The root directory of all files or directories to archive.
+         * This is the value to pass to the {@code -C} tool option.
+         */
+        @Nonnull
+        final Path directory;
+
+        /**
+         * The files or directories to include in the <var>JAR</var> file.
+         * May be absolute paths or paths relative to {@link #directory}.
+         */
+        @Nonnull
+        final List<Path> files;
+
+        /**
+         * Creates an initially empty set of files or directories for a specific target Java release.
+         *
+         * @param directory the base directory of the files or directories to archive
+         */
+        private FileSet(Path directory) {
+            this.directory = directory;
+            this.files = new ArrayList<>();
+        }
+
+        /**
+         * 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.
+         * The caller should use that common directory for logging a warning message.
+         *
+         * @param base base directory found by previous invocations of this method, or {@code null} if none
+         * @return common directory of discarded files
+         */
+        private Path discardAllFiles(Path base) {
+            for (Path file : files) {
+                file = directory.resolve(file);
+                if (base == null) {
+                    base = file.getParent();
+                } else {
+                    while (!file.startsWith(base)) {
+                        base = base.getParent();
+                        if (base == null) {
+                            break;
+                        }
+                    }
+                }
+            }
+            files.clear();
+            return base;
+        }
+
+        /**
+         * Adds the given path to the list of files or directories to archive.
+         * This method may store a relative path instead of the absolute path.
+         *
+         * @param item a file or directory to archive
+         * @param attributes the file's basic attributes
+         * @param isDirectory whether the file is a directory
+         * @throws IllegalArgumentException if the given path cannot be made relative to the base directory
+         */
+        void add(Path item, BasicFileAttributes attributes, boolean isDirectory) {
+            TimestampCheck tc = existingJAR;
+            if (tc != null && tc.isUpdated(item, attributes, isDirectory)) {
+                existingJAR = null; // Signal that the existing file is outdated.
+            }
+            item = directory.relativize(item);
+            if (item.getNameCount() <= 1 && item.toString().isEmpty()) {
+                /*
+                 * The item is the `-C` directory itself (e.g. a `META-INF/versions/<n>` directory
+                 * added as a whole). An empty file argument is invalid for the `jar` tool
+                 * (some implementations reject it, others silently misbehave),
+                 * so archive the whole directory content with ".".
+                 */
+                item = Path.of(".");
+            }
+            files.add(item);
+        }
+
+        /**
+         * Adds to the given list the arguments to provide to the "jar" tool for this version.
+         * Elements added to the list shall be instances of {@link String} or {@link Path}.
+         *
+         * @param addTo the list where to add the arguments as {@link String} or {@link Path} instances
+         * @param version the target Java release, or {@code null} for the base version of the <abbr>JAR</abbr> file
+         */
+        private void arguments(List<Object> addTo, Runtime.Version version) {
+            if (!files.isEmpty()) {
+                if (version != null) {
+                    addTo.add("--release");
+                    addTo.add(version);
+                }
+                if (isReproducible) {
+                    files.sort(REPRODUCIBLE_ORDER);
+                }
+                if (REPEAT_C) {
+                    for (Path file : files) {
+                        addTo.add("-C");
+                        addTo.add(directory);
+                        addTo.add(file);
+                    }
+                } else {
+                    addTo.add("-C");
+                    addTo.add(directory);
+                    addTo.addAll(files);
+                }
+            }
+        }
+
+        /**
+         * {@return a string representation for debugging purposes}
+         */
+        @Override
+        public String toString() {
+            return getClass().getSimpleName() + '[' + directory.getFileName() + ": " + files.size() + " files]";
+        }
+    }
+
+    /**
+     * Whether reproducible build was requested.
+     */
+    private final boolean isReproducible;
+
+    /**
+     * Creates an initially empty set of files or directories.
+     *
+     * @param jarFile path to the <abbr>JAR</abbr> file to create
+     * @param moduleName the module name if using module hierarchy, or {@code null} if using package hierarchy
+     * @param version the target Java release, or {@code null} for the base version
+     * @param directory the directory of the classes targeting the base Java release
+     * @param forceCreation whether to force a new <abbr>JAR</abbr> file even if the content seems unchanged
+     * @param isReproducible whether reproducible build was requested
+     * @param logger where to send a warning if an error occurred while checking an existing <abbr>JAR</abbr> file
+     */
+    @SuppressWarnings("checkstyle:NeedBraces")
+    Archive(
+            final Path jarFile,
+            final String moduleName,
+            final Runtime.Version version,
+            final Path directory,
+            final boolean forceCreation,
+            final boolean isReproducible,
+            final Log logger) {
+        this.jarFile = jarFile;
+        this.moduleName = moduleName;
+        this.isReproducible = isReproducible;
+        filesetForRelease = new TreeMap<>((v1, v2) -> {
+            if (v1 == v2) return 0;
+            if (v1 == null) return -1;
+            if (v2 == null) return +1;
+            return v1.compareTo(v2);
+        });
+        filesetForRelease.put(version, new FileSet(directory));
+        if (!forceCreation && Files.isRegularFile(jarFile)) {
+            try {
+                existingJAR = new TimestampCheck(jarFile, directory, logger);
+            } catch (IOException e) {
+                // Ignore, we will regenerate the JAR file.
+                logger.warn(e);
+            }
+        }
+    }
+
+    /**
+     * {@return the files or directories to store in the <abbr>JAR</abbr> file for targeting the base Java release}
+     *
+     * @throws NoSuchElementException should not happen unless {@link #prune(boolean)} has been invoked
+     */
+    FileSet baseRelease() {
+        Map.Entry<Runtime.Version, FileSet> entry = filesetForRelease.firstEntry();
+        String message = null;
+        if (entry != null) {
+            Runtime.Version version = entry.getKey();
+            if (version == null) {
+                return entry.getValue();
+            }
+            message = "Expected base version but found version " + version;
+        }
+        throw new NoSuchElementException(message);
+    }
+
+    /**
+     * Returns the {@code module-info.class} files. Conceptually, there is at most once such file per module.
+     * However, more than one file may exist if additional files are provided for additional Java releases.
+     * This method returns only the files that exist.
+     *
+     * @return all {@code module-info.class} files found for all target Java releases
+     */
+    public List<Path> moduleInfoFiles() {
+        var files = new ArrayList<Path>();
+        filesetForRelease.values().forEach((release) -> {
+            Path file = release.directory.resolve(FileCollector.MODULE_DESCRIPTOR_FILE_NAME);
+            if (Files.isRegularFile(file)) {
+                files.add(file);
+            }
+        });
+        return files;
+    }
+
+    /**
+     * Discards all files in this archive, normally because those files are not in any module.
+     * This method returns a common parent directory for all the files that were discarded.
+     * The caller should use that common directory for logging a warning message.
+     *
+     * @return common directory of discarded files, or {@code null} if none
+     */
+    Path discardAllFiles() {
+        Path base = null;
+        for (FileSet release : filesetForRelease.values()) {
+            base = release.discardAllFiles(base);
+        }
+        filesetForRelease.clear();
+        return base;
+    }
+
+    /**
+     * Removes all empty file sets 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}, then this method ensures that at least one file set
+     * remains even if that file set is empty.
+     *
+     * @param skipIfEmpty value of {@link AbstractJarMojo#skipIfEmpty}
+     */
+    public void prune(final boolean skipIfEmpty) {
+        FileSet keep = (skipIfEmpty || isEmpty())
+                ? null
+                : filesetForRelease.firstEntry().getValue();
+        filesetForRelease.values().removeIf((fs) -> fs.files.isEmpty());
+        Iterator<Map.Entry<Runtime.Version, FileSet>> it =
+                filesetForRelease.entrySet().iterator();
+        if (it.hasNext()) {
+            Map.Entry<Runtime.Version, FileSet> first = it.next();
+            if (first.getKey() == null) {
+                return; // Already contains an entry for the base version, nothing to do.
+            }
+            keep = first.getValue();
+            it.remove();
+        }
+        if (keep != null) {
+            filesetForRelease.put(null, keep);
+        }
+    }
+
+    /**
+     * {@return whether this archive has nothing to archive}
+     * Note that this method may return {@code false} even when there is zero file to archive.
+     * It may happen if {@link AbstractJarMojo#skipIfEmpty} is {@code false}. In such case, the
+     * "empty" <abbr>JAR</abbr> file will still contain at {@code META-INF/MANIFEST.MF} file.
+     *
+     * <h4>Prerequisites</h4>
+     * The {@link #prune(boolean)} method should be invoked before this method for accurate result.
+     */
+    public boolean isEmpty() {
+        return filesetForRelease.isEmpty();
+    }
+
+    /**
+     * Checks whether the <abbr>JAR</abbr> file already exists and can be reused.
+     * This method verifies that the <abbr>JAR</abbr> file contains all the files to archive,
+     * contains no extra file, and no file to archive is newer than the <abbr>JAR</abbr> file.
+     *
+     * <p>This method can be invoked only once.
+     * If invoked more often, it returns {@code false} on all subsequent invocations.</p>
+     *
+     * @return whether the <abbr>JAR</abbr> file already exists and can be reused
+     */
+    public boolean isUpToDateJAR() {
+        final TimestampCheck tc = existingJAR;
+        if (tc == null) {
+            return false;
+        }
+        existingJAR = null; // Let GC do its job.
+        return tc.isUpToDateJAR(filesetForRelease.values());
+    }
+
+    /**
+     * Returns an initially empty set of files or directories for the specified target Java release.
+     *
+     * @param directory the base directory of the files to archive
+     * @param version the target Java release, or {@code null} for the base version
+     * @return container where to declare files and directories to archive
+     */
+    FileSet newTargetRelease(Path directory, Runtime.Version version) {
+        return filesetForRelease.computeIfAbsent(version, (key) -> new FileSet(directory));
+    }
+
+    /**
+     * Sets the {@code --main-class} option to the value of the {@code Main-Class} entry of the given manifest.
+     * As an extension, this method accepts the {@code module/classname} syntax (a syntax already used in some
+     * Java tools). If a module is specified, the main class is kept only if the module match. The intent is to
+     * allow users to specify on which module the main class applies when they use plugin configuration.
+     *
+     * <p>This method may modify the {@code content} manifest. Caller shall ensure that the given manifest
+     * is not a shared instance. This method returns whether a change has actually been done.</p>
+     *
+     * @param content combination of existing {@code MANIFEST.MF} and manifest inferred from configuration, or null
+     * @return whether the given manifest has been modified by this method
+     */
+    boolean setMainClass(Manifest content) {
+        if (content == null || mainClass != null) {
+            return false;
+        }
+        // We need to remove the attribute, otherwise it will conflict with `--main-class`.
+        mainClass = (String) content.getMainAttributes().remove(Attributes.Name.MAIN_CLASS);
+        if (mainClass != null) {
+            int s = mainClass.indexOf('/');
+            if (s >= 0) {
+                if (mainClass.substring(0, s).strip().equals(moduleName)) {
+                    mainClass = mainClass.substring(s + 1).strip();
+                } else {
+                    mainClass = null; // Main class is defined for another module.
+                }
+            }
+        }
+        return mainClass != null;
+    }
+
+    /**
+     * Sets the {@code --manifest} option to the given value if that option was not already set.
+     *
+     * @param file path to the manifest file
+     * @param force whether to set the manifest even if already set
+     * @return whether the manifest has been set
+     */
+    boolean setManifest(Path file, boolean force) {
+        if (manifest == null || force) {
+            manifest = file;
+            return true;
+        }
+        return false;
+    }
+
+    /**
+     * Merges the manifest of this module with the manifest specified in plugin configuration.
+     * If both {@code file} and {@code content} are non-null, then {@code content} must be the
+     * result of reading {@code file}.
+     *
+     * <p>This method never modifies the given {@code content} object. If manifest are merged,
+     * a new {@link Manifest} instance is created. Therefore, caller can check whether this
+     * method returned a new instance as a way to recognize that a merge occurred.</p>
+     *
+     * <p>If a merge occurs, the content specified to {@link #setManifest(Path)} has precedence.
+     * It should be the {@code target/classes/META-INF/MANIFEST.MF} file (or modular equivalent).</p>
+     *
+     * @param  file     an additional manifest file, or {@code null}
+     * @param  content  the content of {@code file}, or a standalone manifest produced at runtime
+     * @return the merged manifest as a new instance if some changes were necessary
+     * @throws IOException if an error occurred while reading a manifest file
+     */
+    Manifest mergeManifest(Path file, Manifest content) throws IOException {
+        if (manifest == null) {
+            manifest = file;
+        } else if (file != null && Files.isSameFile(file, manifest)) {
+            // Nothing to merge because of the constraint that `content` must be the content of `file`.
+        } else {
+            try (InputStream in = Files.newInputStream(manifest)) {
+                // No need to wrap in `BufferedInputStream`.
+                if (content != null) {
+                    content = new Manifest(content);
+                    content.read(in);
+                } else {
+                    content = new Manifest(in);
+                }
+            }
+        }
+        return content;
+    }
+
+    /**
+     * Adds to the given list the arguments to provide to the "jar" tool for each version.
+     * Elements added to the list shall be instances of {@link String} or {@link Path}.
+     * Callers should have added the following options (if applicable) before to invoke this method:
+     *
+     * <ul>
+     *   <li>{@code --create}</li>
+     *   <li>{@code --no-compress}</li>
+     *   <li>{@code --date} followed by the output time stamp</li>
+     *   <li>{@code --module-version} followed by module version</li>
+     *   <li>{@code --hash-modules} followed by patters of module names</li>
+     *   <li>{@code --module-path} followed by module path</li>
+     * </ul>
+     *
+     * This method adds the following options:
+     *
+     * <ul>
+     *   <li>{@code --file} followed by the path to the <abbr>JAR</abbr> file</li>
+     *   <li>{@code --manifest} followed by path to the manifest file</li>
+     *   <li>{@code --main-class} followed by fully qualified name class</li>
+     *   <li>{@code --release} followed by Java target release</li>
+     *   <li>{@code -C} followed by directory</li>
+     *   <li>files or directories to archive</li>
+     * </ul>
+     *
+     * @param addTo the list where to add the arguments as {@link String} or {@link Path} instances
+     */
+    void arguments(final List<Object> addTo) {
+        addTo.add("--file");
+        addTo.add(jarFile);
+        if (manifest != null) {
+            addTo.add("--manifest");
+            addTo.add(manifest);
+        }
+        if (mainClass != null) {
+            addTo.add("--main-class");
+            addTo.add(mainClass);
+        }
+        if (mavenFiles != null) {
+            addTo.add("-C");
+            addTo.addAll(mavenFiles);
+        }
+        for (Map.Entry<Runtime.Version, FileSet> entry : filesetForRelease.entrySet()) {
+            entry.getValue().arguments(addTo, entry.getKey());
+        }
+    }
+
+    /**
+     * Adds to the given list the arguments to provide to the "jar" tool for validating the <abbr>JAR</abbr> file.
+     * The file is validated only if the validation was not done implicitly at <abbr>JAR</abbr> creation time.
+     * This is the case if no {@code --release} option was used.
+     * This method adds the following options:
+     *
+     * <ul>
+     *   <li>{@code --validate} operation mode</li>
+     *   <li>{@code --file} followed by the path to the <abbr>JAR</abbr> file</li>
+     * </ul>
+     *
+     * @param  addTo the list where to add the arguments as {@link String} or {@link Path} instances
+     * @return whether a validation should be run
+     */
+    boolean validate(final List<Object> addTo) {
+        if (filesetForRelease.values().stream().allMatch(Objects::isNull)) {
+            // At least one --release option was used. Validation was implicit.
+            return false;
+        }
+        addTo.add("--validate");
+        addTo.add("--file");
+        addTo.add(jarFile);
+        return true;
+    }
+
+    /**
+     * Dumps the tool options together with the list of files into a debug file.
+     * This is invoked in case of compilation failure, or if debug is enabled.
+     * The arguments can be separated by spaces or by new line characters.
+     * File name should be between double quotation marks.
+     *
+     * @param baseDir project base directory for relativizing the arguments
+     * @param debugDirectory the directory where to write the debug file
+     * @param classifier the classifier (e.g. "tests"), or {@code null} if none
+     * @param arguments the arguments formatted by {@link #arguments(List)}
+     * @return the debug file where arguments have been written
+     * @throws IOException if an error occurred while writing the debug file
+     */
+    Path writeDebugFile(Path baseDir, Path debugDirectory, String classifier, List<Object> arguments)
+            throws IOException {
+        var filename = new StringBuilder("jar");
+        if (moduleName != null) {
+            filename.append('-').append(moduleName);
+        }
+        if (classifier != null) {
+            filename.append('-').append(classifier);
+        }
+        Path debugFile = debugDirectory.resolve(filename.append(".args").toString());
+        try (BufferedWriter out = Files.newBufferedWriter(debugFile)) {
+            boolean isNewLine = true;
+            for (Object argument : arguments) {
+                if (argument instanceof Path file) {
+                    try {
+                        file = baseDir.relativize(file);
+                    } catch (IllegalArgumentException e) {
+                        // Ignore, keep the absolute path.
+                    }
+                    if (!isNewLine) {
+                        out.write(' ');
+                    }
+                    out.write('"');
+                    out.write(file.toString());
+                    out.write('"');
+                    out.newLine();
+                    isNewLine = true;
+                } else {
+                    String option = argument.toString();
+                    if (!isNewLine) {
+                        if (option.startsWith("--") || option.equals("-C")) {
+                            out.newLine();
+                        } else {
+                            out.write(' ');
+                        }
+                    }
+                    out.write(option);
+                    isNewLine = false;
+                }
+            }
+        }
+        return debugFile;
+    }
+
+    /**
+     * Stores in the given map the paths to the artifacts produced for this archive.

Review Comment:
   Done.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3891927794


##########
src/main/java/org/apache/maven/plugins/jar/Archive.java:
##########
@@ -0,0 +1,692 @@
+/*
+ * 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.jar;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.TreeMap;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.Type;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.MojoException;
+
+/**
+ * Files or root directories to archive for a single module.
+ * A single instance of {@code Archive} may contain many directories for different target Java releases.
+ * Many instances of {@code Archive} may exist when archiving a multi-modules project.
+ */
+final class Archive {
+    /**
+     * Whether to repeat the {@code -C} option before each file.
+     * Doing so makes the command-line very verbose while the documentation of
+     * <a href="https://docs.oracle.com/en/java/javase/25/docs/specs/man/jar.html">The jar Command</a>
+     * gives the impression that this option can be provided only once.
+     * However, our tests suggest that the first file after the directory specified by the {@code -C} option
+     * must be relative to that directory and all files after the first one must be prefixed by the directory
+     * which was specified in the {@code -C} option. This behavior is not documented, but we couldn't get the
+     * {@code jar} tool to work otherwise (except by repeating {@code -C} before each file).
+     * Furthermore, it seems that the relativized file needs to be the shortest one,
+     * otherwise the {@code jar} tool rejects files after the first one with "names do not match".
+     * Which file is first depends on the unspecified directory-iteration order.
+     *
+     * <p>If this flag is {@code true}, the plugin repeats {@code -C} before each file.
+     * This flag should be set to {@code false} if a future version of the {@code jar}
+     * tool allows to specify {@code -C} only once.</p>
+     *
+     * <p><b>Historical note:</b> we also tried to relativize only the first file after {@code -C}
+     * and keep all subsequent files as absolute. It works, but because we have to repeat the directory
+     * in the file name, it saves only 3 or 4 characters per file compared to repeating {@code -C}.</p>
+     */
+    private static final boolean REPEAT_C = true;
+
+    /**
+     * Path to the <abbr>POM</abbr> file generated for this archive, or {@code null} if none.
+     * This is non-null only if module source hierarchy is used, in which case the dependencies
+     * declared in this file are the intersection of the project dependencies and the content of
+     * the {@code module-info.class} file.
+     */
+    @Nullable
+    Path pomFile;
+
+    /**
+     * The <var>JAR</var> file to create. May be an existing file,
+     * in which case the file creation may be skipped if the file is still up-to-date.
+     */
+    @Nonnull
+    final Path jarFile;
+
+    /**
+     * A helper class for checking whether an existing <abbr>JAR</abbr> file is still up-to-date.
+     * This is null if there is no existing JAR file, or if we determined that the file is outdated.
+     */
+    private TimestampCheck existingJAR;
+
+    /**
+     * Name of the module being archived when the project is using module hierarchy.
+     * This is {@code null} if the project is using package hierarchy, either because it is a classical
+     * class-path project or because it is a single module compiled without using the module hierarchy.
+     * When using module source hierarchy, {@code javac} guarantees that the module name in the output
+     * directory is the name of the parent directory of {@code module-info.class}.
+     */
+    @Nullable
+    final String moduleName;
+
+    /**
+     * Path to {@code META-INF/MANIFEST.MF}, or {@code null} if none.
+     * If non-null, this value will be given to the {@code --manifest} option.
+     * The use of this option is preferable to adding {@code MANIFEST.MF} as an ordinary file.
+     *
+     * @see #setManifest(Path, boolean)
+     * @see #mergeManifest(Path, Manifest)
+     */
+    @Nullable
+    private Path manifest;
+
+    /**
+     * The Maven generated {@code pom.xml} and {@code pom.properties} files, or {@code null} if none.
+     * This first item shall be the base directory where the files are located.
+     */
+    @Nullable
+    List<Path> mavenFiles;
+
+    /**
+     * Fully-qualified name of the main class, or {@code null} if none.
+     * This is the value to provide to the {@code --main-class} option.
+     */
+    private String mainClass;
+
+    /**
+     * Files or root directories to store in the <abbr>JAR</abbr> file for each target Java release
+     * other than the base release. Keys are the target Java release with {@code null} for the base
+     * release.
+     */
+    @Nonnull
+    private final NavigableMap<Runtime.Version, FileSet> filesetForRelease;
+
+    /**
+     * Files or root directories to archive for a single target Java release of a single module.
+     * The {@link Archive} enclosing shall contain at least one instance of {@code FileSet} for
+     * the base release, and an arbitrary amount of other instances for other target releases.
+     */
+    final class FileSet {
+        /**
+         * A comparator for sorting paths in a reproducible order.
+         * This comparator assumes that all paths are relative to the same base directory (this is not verified).
+         * Note: we do not use {@link Path#compareTo(Path)} because the Javadoc said that it is platform dependent.
+         */
+        private static final Comparator<Path> REPRODUCIBLE_ORDER = (p1, p2) -> {
+            final int c1 = p1.getNameCount();
+            final int c2 = p2.getNameCount();
+            final int c = Math.min(c1, c2);
+            for (int i = 0; i < c; i++) {
+                String n1 = p1.getName(i).toString();
+                String n2 = p2.getName(i).toString();
+                int r = n1.compareTo(n2); // Case-sensitive comparison on all platforms.
+                if (r != 0) {
+                    return r;
+                }
+            }
+            return c1 - c2;
+        };
+
+        /**
+         * The root directory of all files or directories to archive.
+         * This is the value to pass to the {@code -C} tool option.
+         */
+        @Nonnull
+        final Path directory;
+
+        /**
+         * The files or directories to include in the <var>JAR</var> file.
+         * May be absolute paths or paths relative to {@link #directory}.
+         */
+        @Nonnull
+        final List<Path> files;
+
+        /**
+         * Creates an initially empty set of files or directories for a specific target Java release.
+         *
+         * @param directory the base directory of the files or directories to archive
+         */
+        private FileSet(Path directory) {
+            this.directory = directory;
+            this.files = new ArrayList<>();
+        }
+
+        /**
+         * 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.
+         * The caller should use that common directory for logging a warning message.
+         *
+         * @param base base directory found by previous invocations of this method, or {@code null} if none
+         * @return common directory of discarded files
+         */
+        private Path discardAllFiles(Path base) {
+            for (Path file : files) {
+                file = directory.resolve(file);
+                if (base == null) {
+                    base = file.getParent();
+                } else {
+                    while (!file.startsWith(base)) {
+                        base = base.getParent();
+                        if (base == null) {
+                            break;
+                        }
+                    }
+                }
+            }
+            files.clear();
+            return base;
+        }
+
+        /**
+         * Adds the given path to the list of files or directories to archive.
+         * This method may store a relative path instead of the absolute path.
+         *
+         * @param item a file or directory to archive
+         * @param attributes the file's basic attributes
+         * @param isDirectory whether the file is a directory
+         * @throws IllegalArgumentException if the given path cannot be made relative to the base directory
+         */
+        void add(Path item, BasicFileAttributes attributes, boolean isDirectory) {
+            TimestampCheck tc = existingJAR;
+            if (tc != null && tc.isUpdated(item, attributes, isDirectory)) {
+                existingJAR = null; // Signal that the existing file is outdated.
+            }
+            item = directory.relativize(item);
+            if (item.getNameCount() <= 1 && item.toString().isEmpty()) {
+                /*
+                 * The item is the `-C` directory itself (e.g. a `META-INF/versions/<n>` directory
+                 * added as a whole). An empty file argument is invalid for the `jar` tool
+                 * (some implementations reject it, others silently misbehave),
+                 * so archive the whole directory content with ".".
+                 */
+                item = Path.of(".");
+            }
+            files.add(item);
+        }
+
+        /**
+         * Adds to the given list the arguments to provide to the "jar" tool for this version.
+         * Elements added to the list shall be instances of {@link String} or {@link Path}.
+         *
+         * @param addTo the list where to add the arguments as {@link String} or {@link Path} instances
+         * @param version the target Java release, or {@code null} for the base version of the <abbr>JAR</abbr> file
+         */
+        private void arguments(List<Object> addTo, Runtime.Version version) {
+            if (!files.isEmpty()) {
+                if (version != null) {
+                    addTo.add("--release");
+                    addTo.add(version);
+                }
+                if (isReproducible) {
+                    files.sort(REPRODUCIBLE_ORDER);
+                }
+                if (REPEAT_C) {
+                    for (Path file : files) {
+                        addTo.add("-C");
+                        addTo.add(directory);
+                        addTo.add(file);
+                    }
+                } else {
+                    addTo.add("-C");
+                    addTo.add(directory);
+                    addTo.addAll(files);
+                }
+            }
+        }
+
+        /**
+         * {@return a string representation for debugging purposes}
+         */
+        @Override
+        public String toString() {
+            return getClass().getSimpleName() + '[' + directory.getFileName() + ": " + files.size() + " files]";
+        }
+    }
+
+    /**
+     * Whether reproducible build was requested.
+     */
+    private final boolean isReproducible;
+
+    /**
+     * Creates an initially empty set of files or directories.
+     *
+     * @param jarFile path to the <abbr>JAR</abbr> file to create
+     * @param moduleName the module name if using module hierarchy, or {@code null} if using package hierarchy
+     * @param version the target Java release, or {@code null} for the base version
+     * @param directory the directory of the classes targeting the base Java release
+     * @param forceCreation whether to force a new <abbr>JAR</abbr> file even if the content seems unchanged
+     * @param isReproducible whether reproducible build was requested
+     * @param logger where to send a warning if an error occurred while checking an existing <abbr>JAR</abbr> file
+     */
+    @SuppressWarnings("checkstyle:NeedBraces")
+    Archive(
+            final Path jarFile,
+            final String moduleName,
+            final Runtime.Version version,
+            final Path directory,
+            final boolean forceCreation,
+            final boolean isReproducible,
+            final Log logger) {
+        this.jarFile = jarFile;
+        this.moduleName = moduleName;
+        this.isReproducible = isReproducible;
+        filesetForRelease = new TreeMap<>((v1, v2) -> {
+            if (v1 == v2) return 0;
+            if (v1 == null) return -1;
+            if (v2 == null) return +1;
+            return v1.compareTo(v2);
+        });
+        filesetForRelease.put(version, new FileSet(directory));
+        if (!forceCreation && Files.isRegularFile(jarFile)) {
+            try {
+                existingJAR = new TimestampCheck(jarFile, directory, logger);
+            } catch (IOException e) {
+                // Ignore, we will regenerate the JAR file.
+                logger.warn(e);
+            }
+        }
+    }
+
+    /**
+     * {@return the files or directories to store in the <abbr>JAR</abbr> file for targeting the base Java release}
+     *
+     * @throws NoSuchElementException should not happen unless {@link #prune(boolean)} has been invoked
+     */
+    FileSet baseRelease() {
+        Map.Entry<Runtime.Version, FileSet> entry = filesetForRelease.firstEntry();
+        String message = null;
+        if (entry != null) {
+            Runtime.Version version = entry.getKey();
+            if (version == null) {
+                return entry.getValue();
+            }
+            message = "Expected base version but found version " + version;
+        }
+        throw new NoSuchElementException(message);
+    }
+
+    /**
+     * Returns the {@code module-info.class} files. Conceptually, there is at most once such file per module.
+     * However, more than one file may exist if additional files are provided for additional Java releases.
+     * This method returns only the files that exist.
+     *
+     * @return all {@code module-info.class} files found for all target Java releases
+     */
+    public List<Path> moduleInfoFiles() {
+        var files = new ArrayList<Path>();
+        filesetForRelease.values().forEach((release) -> {
+            Path file = release.directory.resolve(FileCollector.MODULE_DESCRIPTOR_FILE_NAME);
+            if (Files.isRegularFile(file)) {
+                files.add(file);
+            }
+        });
+        return files;
+    }
+
+    /**
+     * Discards all files in this archive, normally because those files are not in any module.
+     * This method returns a common parent directory for all the files that were discarded.
+     * The caller should use that common directory for logging a warning message.
+     *
+     * @return common directory of discarded files, or {@code null} if none
+     */
+    Path discardAllFiles() {
+        Path base = null;
+        for (FileSet release : filesetForRelease.values()) {
+            base = release.discardAllFiles(base);
+        }
+        filesetForRelease.clear();
+        return base;
+    }
+
+    /**
+     * Removes all empty file sets 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}, then this method ensures that at least one file set
+     * remains even if that file set is empty.
+     *
+     * @param skipIfEmpty value of {@link AbstractJarMojo#skipIfEmpty}
+     */
+    public void prune(final boolean skipIfEmpty) {
+        FileSet keep = (skipIfEmpty || isEmpty())
+                ? null
+                : filesetForRelease.firstEntry().getValue();
+        filesetForRelease.values().removeIf((fs) -> fs.files.isEmpty());
+        Iterator<Map.Entry<Runtime.Version, FileSet>> it =
+                filesetForRelease.entrySet().iterator();
+        if (it.hasNext()) {
+            Map.Entry<Runtime.Version, FileSet> first = it.next();
+            if (first.getKey() == null) {
+                return; // Already contains an entry for the base version, nothing to do.
+            }
+            keep = first.getValue();
+            it.remove();
+        }
+        if (keep != null) {
+            filesetForRelease.put(null, keep);
+        }
+    }
+
+    /**
+     * {@return whether this archive has nothing to archive}
+     * Note that this method may return {@code false} even when there is zero file to archive.
+     * It may happen if {@link AbstractJarMojo#skipIfEmpty} is {@code false}. In such case, the
+     * "empty" <abbr>JAR</abbr> file will still contain at {@code META-INF/MANIFEST.MF} file.
+     *
+     * <h4>Prerequisites</h4>
+     * The {@link #prune(boolean)} method should be invoked before this method for accurate result.
+     */
+    public boolean isEmpty() {
+        return filesetForRelease.isEmpty();
+    }
+
+    /**
+     * Checks whether the <abbr>JAR</abbr> file already exists and can be reused.
+     * This method verifies that the <abbr>JAR</abbr> file contains all the files to archive,
+     * contains no extra file, and no file to archive is newer than the <abbr>JAR</abbr> file.
+     *
+     * <p>This method can be invoked only once.
+     * If invoked more often, it returns {@code false} on all subsequent invocations.</p>
+     *
+     * @return whether the <abbr>JAR</abbr> file already exists and can be reused
+     */
+    public boolean isUpToDateJAR() {
+        final TimestampCheck tc = existingJAR;
+        if (tc == null) {
+            return false;
+        }
+        existingJAR = null; // Let GC do its job.
+        return tc.isUpToDateJAR(filesetForRelease.values());
+    }
+
+    /**
+     * Returns an initially empty set of files or directories for the specified target Java release.
+     *
+     * @param directory the base directory of the files to archive
+     * @param version the target Java release, or {@code null} for the base version
+     * @return container where to declare files and directories to archive
+     */
+    FileSet newTargetRelease(Path directory, Runtime.Version version) {
+        return filesetForRelease.computeIfAbsent(version, (key) -> new FileSet(directory));
+    }
+
+    /**
+     * Sets the {@code --main-class} option to the value of the {@code Main-Class} entry of the given manifest.
+     * As an extension, this method accepts the {@code module/classname} syntax (a syntax already used in some
+     * Java tools). If a module is specified, the main class is kept only if the module match. The intent is to
+     * allow users to specify on which module the main class applies when they use plugin configuration.
+     *
+     * <p>This method may modify the {@code content} manifest. Caller shall ensure that the given manifest
+     * is not a shared instance. This method returns whether a change has actually been done.</p>
+     *
+     * @param content combination of existing {@code MANIFEST.MF} and manifest inferred from configuration, or null
+     * @return whether the given manifest has been modified by this method
+     */
+    boolean setMainClass(Manifest content) {
+        if (content == null || mainClass != null) {
+            return false;
+        }
+        // We need to remove the attribute, otherwise it will conflict with `--main-class`.
+        mainClass = (String) content.getMainAttributes().remove(Attributes.Name.MAIN_CLASS);
+        if (mainClass != null) {
+            int s = mainClass.indexOf('/');
+            if (s >= 0) {
+                if (mainClass.substring(0, s).strip().equals(moduleName)) {
+                    mainClass = mainClass.substring(s + 1).strip();
+                } else {
+                    mainClass = null; // Main class is defined for another module.
+                }
+            }
+        }
+        return mainClass != null;
+    }
+
+    /**
+     * Sets the {@code --manifest} option to the given value if that option was not already set.
+     *
+     * @param file path to the manifest file
+     * @param force whether to set the manifest even if already set
+     * @return whether the manifest has been set
+     */
+    boolean setManifest(Path file, boolean force) {
+        if (manifest == null || force) {
+            manifest = file;
+            return true;
+        }
+        return false;
+    }
+
+    /**
+     * Merges the manifest of this module with the manifest specified in plugin configuration.
+     * If both {@code file} and {@code content} are non-null, then {@code content} must be the
+     * result of reading {@code file}.
+     *
+     * <p>This method never modifies the given {@code content} object. If manifest are merged,
+     * a new {@link Manifest} instance is created. Therefore, caller can check whether this
+     * method returned a new instance as a way to recognize that a merge occurred.</p>
+     *
+     * <p>If a merge occurs, the content specified to {@link #setManifest(Path)} has precedence.
+     * It should be the {@code target/classes/META-INF/MANIFEST.MF} file (or modular equivalent).</p>
+     *
+     * @param  file     an additional manifest file, or {@code null}
+     * @param  content  the content of {@code file}, or a standalone manifest produced at runtime
+     * @return the merged manifest as a new instance if some changes were necessary
+     * @throws IOException if an error occurred while reading a manifest file
+     */
+    Manifest mergeManifest(Path file, Manifest content) throws IOException {
+        if (manifest == null) {
+            manifest = file;
+        } else if (file != null && Files.isSameFile(file, manifest)) {
+            // Nothing to merge because of the constraint that `content` must be the content of `file`.
+        } else {
+            try (InputStream in = Files.newInputStream(manifest)) {
+                // No need to wrap in `BufferedInputStream`.
+                if (content != null) {
+                    content = new Manifest(content);
+                    content.read(in);
+                } else {
+                    content = new Manifest(in);
+                }
+            }
+        }
+        return content;
+    }
+
+    /**
+     * Adds to the given list the arguments to provide to the "jar" tool for each version.

Review Comment:
   If we do not said "to the given list", the natural tendency is to assume that stuff are added in `this`.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "gnodet (via GitHub)" <gi...@apache.org>.
gnodet commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3839858511


##########
src/main/java/org/apache/maven/plugins/jar/PomDerivation.java:
##########
@@ -0,0 +1,525 @@
+/*
+ * 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.jar;
+
+import javax.xml.stream.XMLStreamException;
+
+import java.io.BufferedInputStream;
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.UncheckedIOException;
+import java.lang.module.ModuleDescriptor;
+import java.lang.module.ModuleFinder;
+import java.lang.module.ModuleReference;
+import java.net.URI;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.DependencyCoordinates;
+import org.apache.maven.api.JavaPathType;
+import org.apache.maven.api.Session;
+import org.apache.maven.api.Type;
+import org.apache.maven.api.model.Dependency;
+import org.apache.maven.api.model.Model;
+import org.apache.maven.api.model.Parent;
+import org.apache.maven.api.plugin.MojoException;
+import org.apache.maven.api.services.DependencyCoordinatesFactory;
+import org.apache.maven.api.services.DependencyCoordinatesFactoryRequest;
+import org.apache.maven.api.services.DependencyResolver;
+import org.apache.maven.api.services.DependencyResolverRequest;
+import org.apache.maven.api.services.DependencyResolverResult;
+import org.apache.maven.api.services.ModelBuilderException;
+import org.apache.maven.model.v4.MavenStaxWriter;
+
+/**
+ * A mapper from Maven model dependencies to Java module names.
+ * A single instance of this class is created for a Maven project,
+ * then shared by all {@link ForModule} instances (one per module to archive).
+ */
+final class PomDerivation {
+    /**
+     * Whether to expand the list of transitive dependencies in the generated <abbr>POM</abbr>.
+     */
+    private static final boolean EXPAND_TRANSITIVE = false;
+
+    /**
+     * Copy of {@link AbstractJarMojo#session}.
+     */
+    private final Session session;
+
+    /**
+     * The project model, which includes dependencies of all modules.
+     */
+    private final Model projectModel;
+
+    /**
+     * The factory to use for creating temporary {@link DependencyCoordinates} instances.
+     */
+    private final DependencyCoordinatesFactory coordinateFactory;
+
+    /**
+     * Provide module descriptors from module names.
+     * May be {@code null} if no {@code module-info} was found.
+     */
+    private final ModuleFinder moduleFinder;
+
+    /**
+     * Module references from paths to the <abbr>JAR</abbr> file or root directory.
+     */
+    private final Map<URI, ModuleReference> fromURI;
+
+    /**
+     * Module names associated to Maven dependencies.
+     * This map contains {@link DependencyCoordinates#getId()} as keys and module references as values.
+     * This is used for detecting which dependencies are really used according {@code module-info.class}.
+     *
+     * @todo The keys should be instances of {@link DependencyCoordinates}. Unfortunately, as of Maven 4.0.0-rc-5
+     *       that interface does not define the {@code equals} and {@code hashCode} contracts.
+     */
+    private final Map<String, ModuleReference> fromDependency;
+
+    /**
+     * Modules that are built by the project. Keys are module names.
+     */
+    private final Map<String, Dependency> builtModules;
+
+    /**
+     * Creates a new mapper from Maven dependency to module name.
+     *
+     * @param mojo the enclosing <abbr>MOJO</abbr>
+     * @param moduleRoots paths to root directories of each module to archive in a module hierarchy
+     * @throws IOException if an I/O error occurred while fetching dependencies
+     * @throws MavenException if an error occurred while fetching dependencies for a reason other than I/O.
+     */
+    PomDerivation(final AbstractJarMojo mojo, final List<Path> moduleRoots) throws IOException {
+        this.session = mojo.session;
+        projectModel = mojo.project.getModel();
+        coordinateFactory = session.getService(DependencyCoordinatesFactory.class);
+        DependencyResolver resolver = session.getService(DependencyResolver.class);
+        DependencyResolverResult result = resolver.resolve(DependencyResolverRequest.builder()
+                .session(session)
+                .project(mojo.project)
+                .requestType(DependencyResolverRequest.RequestType.RESOLVE)
+                .pathScope(mojo.getDependencyScope())
+                .pathTypeFilter(Set.of(JavaPathType.MODULES, JavaPathType.CLASSES))
+                .build());
+
+        rethrow(result);
+        final Map<org.apache.maven.api.Dependency, Path> dependencies = result.getDependencies();
+        final Path[] allModulePaths = toRealPaths(moduleRoots, dependencies.values());
+        fromURI = new HashMap<>(allModulePaths.length); // TODO: use newHashMap with JDK19.
+        moduleFinder = ModuleFinder.of(allModulePaths);
+        if (moduleFinder != null) {
+            for (ModuleReference reference : moduleFinder.findAll()) {
+                reference.location().ifPresent((location) -> fromURI.put(location, reference));
+            }
+        }
+        fromDependency = new HashMap<>(dependencies.size()); // TODO: use newHashMap with JDK19.
+        for (Map.Entry<org.apache.maven.api.Dependency, Path> entry : dependencies.entrySet()) {
+            Path modulePath = entry.getValue().toRealPath();
+            ModuleReference reference = fromURI.get(modulePath.toUri());
+            if (reference != null) {
+                DependencyCoordinates coordinates = entry.getKey().toCoordinates();
+                String id = coordinates.getId();
+                ModuleReference old = fromDependency.putIfAbsent(id, reference);
+                if (old == null) {
+                    coordinates = withoutVersion(coordinates);
+                    id = coordinates.getId();
+                    old = fromDependency.putIfAbsent(id, reference);
+                }
+                if (old != null && !old.equals(reference)) {
+                    mojo.log.warn("The \"" + id + "\" dependency is declared twice with different module names: \""
+                            + old.descriptor().name() + "\" and \""
+                            + reference.descriptor().name() + "\".");
+                }
+            }
+        }
+        builtModules = new HashMap<>(moduleRoots.size()); // TODO: use newHashMap with JDK19.
+        for (Path root : moduleRoots) {
+            ModuleDescriptor descriptor = fromURI.get(root.toUri()).descriptor();

Review Comment:
   **[I1 — Important] Potential NPE: `toUri()` vs `toRealPath().toUri()` mismatch**
   
   The `fromURI` map is populated with keys from `ModuleFinder.of(allModulePaths)`, where `allModulePaths` uses `toRealPath()`. But this lookup uses `root.toUri()` **without** `toRealPath()`.
   
   If `root` contains symlinks or non-normalized components, `root.toUri()` and `root.toRealPath().toUri()` produce different URIs, so the lookup returns `null` and `.descriptor()` throws NPE.
   
   ```suggestion
               ModuleDescriptor descriptor = fromURI.get(root.toRealPath().toUri()).descriptor();
   ```



##########
src/main/java/org/apache/maven/plugins/jar/AbstractJarMojo.java:
##########
@@ -207,167 +205,208 @@ protected final Log getLog() {
     protected abstract String getType();
 
     /**
-     * Returns the JAR file to generate, based on an optional classifier.
+     * {@return the scope of dependencies}
+     * It should be {@link PathScope#MAIN_COMPILE} or {@link PathScope#TEST_COMPILE}.
+     * Note that we use compile scope rather than runtime scope because dependencies
+     * cannot appear in {@code requires} statement if they didn't had compile scope.
+     */
+    protected abstract PathScope getDependencyScope();
+
+    /**
+     * {@return the JAR tool to use for archiving the code}
      *
-     * @param basedir the output directory
-     * @param resultFinalName the name of the JAR file
-     * @param classifier an optional classifier
-     * @return the file to generate
+     * @throws MojoException if no JAR tool was found
+     *
+     * @since 4.0.0-beta-2
      */
-    protected Path getJarFile(Path basedir, String resultFinalName, String classifier) {
-        Objects.requireNonNull(basedir, "basedir is not allowed to be null");
-        Objects.requireNonNull(resultFinalName, "finalName is not allowed to be null");
-        String fileName = resultFinalName + (hasClassifier(classifier) ? '-' + classifier : "") + ".jar";
-        return basedir.resolve(fileName);
+    protected ToolProvider getJarTool() throws MojoException {
+        return ToolProvider.findFirst(toolId).orElseThrow(() -> new MojoException("No such \"" + toolId + "\" tool."));
     }
 
     /**
-     * Generates the JAR.
+     * Returns the output time stamp or, as a fallback, the {@code SOURCE_DATE_EPOCH} environment variable.
+     * If the time stamp is expressed in seconds, it is converted to ISO 8601 format. Otherwise it is returned as-is.
      *
-     * @return the path to the created archive file
-     * @throws MojoException in case of an error
+     * @return the time stamp in presumed ISO 8601 format, or {@code null} if none
+     *
+     * @since 4.0.0-beta-2
      */
-    public Path createArchive() throws MojoException {
-        Path basedir = outputDirectory != null
-                ? outputDirectory
-                : Path.of(project.getBuild().getDirectory());
-        String resultFinalName =
-                finalName != null ? finalName : project.getBuild().getFinalName();
-        Path jarFile = getJarFile(basedir, resultFinalName, getClassifier());
-
-        FileSetManager fileSetManager = new FileSetManager();
-        FileSet jarContentFileSet = new FileSet();
-        jarContentFileSet.setDirectory(getClassesDirectory().toAbsolutePath().toString());
-        jarContentFileSet.setIncludes(Arrays.asList(getIncludes()));
-        jarContentFileSet.setExcludes(Arrays.asList(getExcludes()));
-
-        String[] includedFiles = fileSetManager.getIncludedFiles(jarContentFileSet);
-
-        if (detectMultiReleaseJar
-                && Arrays.stream(includedFiles)
-                        .anyMatch(
-                                p -> p.startsWith("META-INF" + File.separatorChar + "versions" + File.separatorChar))) {
-            getLog().debug("Adding 'Multi-Release: true' manifest entry.");
-            archive.addManifestEntry(Attributes.Name.MULTI_RELEASE.toString(), "true");
+    protected String getOutputTimestamp() {
+        String time = nullIfAbsent(outputTimestamp);
+        if (time == null) {
+            time = nullIfAbsent(System.getenv("SOURCE_DATE_EPOCH"));
+            if (time == null) {
+                return null;
+            }
         }
+        if (Runtime.version().feature() < ToolExecutor.JDK_SUPPORT_DATE) {
+            log.warn("Reproducible build requires Java " + ToolExecutor.JDK_SUPPORT_DATE + " or later.");

Review Comment:
   **[I5 — Important] Reproducible builds silently degrade on JDK 17/18**
   
   Since Maven 4 requires JDK 17+, users on JDK 17/18 will silently lose reproducible build support — the warning goes to the log but the build succeeds, meaning CI pipelines that rely on reproducible builds may silently produce non-reproducible artifacts.
   
   Consider making this an error (or at least error-level logging) when `outputTimestamp` is **explicitly** configured and the JDK cannot honor it.



##########
src/main/java/org/apache/maven/plugins/jar/Archive.java:
##########
@@ -0,0 +1,692 @@
+/*
+ * 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.jar;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.TreeMap;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.Type;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.MojoException;
+
+/**
+ * Files or root directories to archive for a single module.
+ * A single instance of {@code Archive} may contain many directories for different target Java releases.
+ * Many instances of {@code Archive} may exist when archiving a multi-modules project.
+ */
+final class Archive {
+    /**
+     * Whether to repeat the {@code -C} option before each file.
+     * Doing so makes the command-line very verbose while the documentation of
+     * <a href="https://docs.oracle.com/en/java/javase/25/docs/specs/man/jar.html">The jar Command</a>
+     * gives the impression that this option can be provided only once.
+     * However, our tests suggest that the first file after the directory specified by the {@code -C} option
+     * must be relative to that directory and all files after the first one must be prefixed by the directory
+     * which was specified in the {@code -C} option. This behavior is not documented, but we couldn't get the
+     * {@code jar} tool to work otherwise (except by repeating {@code -C} before each file).
+     * Furthermore, it seems that the relativized file needs to be the shortest one,
+     * otherwise the {@code jar} tool rejects files after the first one with "names do not match".
+     * Which file is first depends on the unspecified directory-iteration order.
+     *
+     * <p>If this flag is {@code true}, the plugin repeats {@code -C} before each file.
+     * This flag should be set to {@code false} if a future version of the {@code jar}
+     * tool allows to specify {@code -C} only once.</p>
+     *
+     * <p><b>Historical note:</b> we also tried to relativize only the first file after {@code -C}
+     * and keep all subsequent files as absolute. It works, but because we have to repeat the directory
+     * in the file name, it saves only 3 or 4 characters per file compared to repeating {@code -C}.</p>
+     */
+    private static final boolean REPEAT_C = true;
+
+    /**
+     * Path to the <abbr>POM</abbr> file generated for this archive, or {@code null} if none.
+     * This is non-null only if module source hierarchy is used, in which case the dependencies
+     * declared in this file are the intersection of the project dependencies and the content of
+     * the {@code module-info.class} file.
+     */
+    @Nullable
+    Path pomFile;
+
+    /**
+     * The <var>JAR</var> file to create. May be an existing file,
+     * in which case the file creation may be skipped if the file is still up-to-date.
+     */
+    @Nonnull
+    final Path jarFile;
+
+    /**
+     * A helper class for checking whether an existing <abbr>JAR</abbr> file is still up-to-date.
+     * This is null if there is no existing JAR file, or if we determined that the file is outdated.
+     */
+    private TimestampCheck existingJAR;
+
+    /**
+     * Name of the module being archived when the project is using module hierarchy.
+     * This is {@code null} if the project is using package hierarchy, either because it is a classical
+     * class-path project or because it is a single module compiled without using the module hierarchy.
+     * When using module source hierarchy, {@code javac} guarantees that the module name in the output
+     * directory is the name of the parent directory of {@code module-info.class}.
+     */
+    @Nullable
+    final String moduleName;
+
+    /**
+     * Path to {@code META-INF/MANIFEST.MF}, or {@code null} if none.
+     * If non-null, this value will be given to the {@code --manifest} option.
+     * The use of this option is preferable to adding {@code MANIFEST.MF} as an ordinary file.
+     *
+     * @see #setManifest(Path, boolean)
+     * @see #mergeManifest(Path, Manifest)
+     */
+    @Nullable
+    private Path manifest;
+
+    /**
+     * The Maven generated {@code pom.xml} and {@code pom.properties} files, or {@code null} if none.
+     * This first item shall be the base directory where the files are located.
+     */
+    @Nullable
+    List<Path> mavenFiles;
+
+    /**
+     * Fully-qualified name of the main class, or {@code null} if none.
+     * This is the value to provide to the {@code --main-class} option.
+     */
+    private String mainClass;
+
+    /**
+     * Files or root directories to store in the <abbr>JAR</abbr> file for each target Java release
+     * other than the base release. Keys are the target Java release with {@code null} for the base
+     * release.
+     */
+    @Nonnull
+    private final NavigableMap<Runtime.Version, FileSet> filesetForRelease;
+
+    /**
+     * Files or root directories to archive for a single target Java release of a single module.
+     * The {@link Archive} enclosing shall contain at least one instance of {@code FileSet} for
+     * the base release, and an arbitrary amount of other instances for other target releases.
+     */
+    final class FileSet {
+        /**
+         * A comparator for sorting paths in a reproducible order.
+         * This comparator assumes that all paths are relative to the same base directory (this is not verified).
+         * Note: we do not use {@link Path#compareTo(Path)} because the Javadoc said that it is platform dependent.
+         */
+        private static final Comparator<Path> REPRODUCIBLE_ORDER = (p1, p2) -> {
+            final int c1 = p1.getNameCount();
+            final int c2 = p2.getNameCount();
+            final int c = Math.min(c1, c2);
+            for (int i = 0; i < c; i++) {
+                String n1 = p1.getName(i).toString();
+                String n2 = p2.getName(i).toString();
+                int r = n1.compareTo(n2); // Case-sensitive comparison on all platforms.
+                if (r != 0) {
+                    return r;
+                }
+            }
+            return c1 - c2;
+        };
+
+        /**
+         * The root directory of all files or directories to archive.
+         * This is the value to pass to the {@code -C} tool option.
+         */
+        @Nonnull
+        final Path directory;
+
+        /**
+         * The files or directories to include in the <var>JAR</var> file.
+         * May be absolute paths or paths relative to {@link #directory}.
+         */
+        @Nonnull
+        final List<Path> files;
+
+        /**
+         * Creates an initially empty set of files or directories for a specific target Java release.
+         *
+         * @param directory the base directory of the files or directories to archive
+         */
+        private FileSet(Path directory) {
+            this.directory = directory;
+            this.files = new ArrayList<>();
+        }
+
+        /**
+         * 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.
+         * The caller should use that common directory for logging a warning message.
+         *
+         * @param base base directory found by previous invocations of this method, or {@code null} if none
+         * @return common directory of discarded files
+         */
+        private Path discardAllFiles(Path base) {
+            for (Path file : files) {
+                file = directory.resolve(file);
+                if (base == null) {
+                    base = file.getParent();
+                } else {
+                    while (!file.startsWith(base)) {
+                        base = base.getParent();
+                        if (base == null) {
+                            break;
+                        }
+                    }
+                }
+            }
+            files.clear();
+            return base;
+        }
+
+        /**
+         * Adds the given path to the list of files or directories to archive.
+         * This method may store a relative path instead of the absolute path.
+         *
+         * @param item a file or directory to archive
+         * @param attributes the file's basic attributes
+         * @param isDirectory whether the file is a directory
+         * @throws IllegalArgumentException if the given path cannot be made relative to the base directory
+         */
+        void add(Path item, BasicFileAttributes attributes, boolean isDirectory) {
+            TimestampCheck tc = existingJAR;
+            if (tc != null && tc.isUpdated(item, attributes, isDirectory)) {
+                existingJAR = null; // Signal that the existing file is outdated.
+            }
+            item = directory.relativize(item);
+            if (item.getNameCount() <= 1 && item.toString().isEmpty()) {
+                /*
+                 * The item is the `-C` directory itself (e.g. a `META-INF/versions/<n>` directory
+                 * added as a whole). An empty file argument is invalid for the `jar` tool
+                 * (some implementations reject it, others silently misbehave),
+                 * so archive the whole directory content with ".".
+                 */
+                item = Path.of(".");
+            }
+            files.add(item);
+        }
+
+        /**
+         * Adds to the given list the arguments to provide to the "jar" tool for this version.
+         * Elements added to the list shall be instances of {@link String} or {@link Path}.
+         *
+         * @param addTo the list where to add the arguments as {@link String} or {@link Path} instances
+         * @param version the target Java release, or {@code null} for the base version of the <abbr>JAR</abbr> file
+         */
+        private void arguments(List<Object> addTo, Runtime.Version version) {
+            if (!files.isEmpty()) {
+                if (version != null) {
+                    addTo.add("--release");
+                    addTo.add(version);
+                }
+                if (isReproducible) {
+                    files.sort(REPRODUCIBLE_ORDER);
+                }
+                if (REPEAT_C) {
+                    for (Path file : files) {
+                        addTo.add("-C");
+                        addTo.add(directory);
+                        addTo.add(file);
+                    }
+                } else {
+                    addTo.add("-C");
+                    addTo.add(directory);
+                    addTo.addAll(files);
+                }
+            }
+        }
+
+        /**
+         * {@return a string representation for debugging purposes}
+         */
+        @Override
+        public String toString() {
+            return getClass().getSimpleName() + '[' + directory.getFileName() + ": " + files.size() + " files]";
+        }
+    }
+
+    /**
+     * Whether reproducible build was requested.
+     */
+    private final boolean isReproducible;
+
+    /**
+     * Creates an initially empty set of files or directories.
+     *
+     * @param jarFile path to the <abbr>JAR</abbr> file to create
+     * @param moduleName the module name if using module hierarchy, or {@code null} if using package hierarchy
+     * @param version the target Java release, or {@code null} for the base version
+     * @param directory the directory of the classes targeting the base Java release
+     * @param forceCreation whether to force a new <abbr>JAR</abbr> file even if the content seems unchanged
+     * @param isReproducible whether reproducible build was requested
+     * @param logger where to send a warning if an error occurred while checking an existing <abbr>JAR</abbr> file
+     */
+    @SuppressWarnings("checkstyle:NeedBraces")
+    Archive(
+            final Path jarFile,
+            final String moduleName,
+            final Runtime.Version version,
+            final Path directory,
+            final boolean forceCreation,
+            final boolean isReproducible,
+            final Log logger) {
+        this.jarFile = jarFile;
+        this.moduleName = moduleName;
+        this.isReproducible = isReproducible;
+        filesetForRelease = new TreeMap<>((v1, v2) -> {
+            if (v1 == v2) return 0;
+            if (v1 == null) return -1;
+            if (v2 == null) return +1;
+            return v1.compareTo(v2);
+        });
+        filesetForRelease.put(version, new FileSet(directory));
+        if (!forceCreation && Files.isRegularFile(jarFile)) {
+            try {
+                existingJAR = new TimestampCheck(jarFile, directory, logger);
+            } catch (IOException e) {
+                // Ignore, we will regenerate the JAR file.
+                logger.warn(e);
+            }
+        }
+    }
+
+    /**
+     * {@return the files or directories to store in the <abbr>JAR</abbr> file for targeting the base Java release}
+     *
+     * @throws NoSuchElementException should not happen unless {@link #prune(boolean)} has been invoked
+     */
+    FileSet baseRelease() {
+        Map.Entry<Runtime.Version, FileSet> entry = filesetForRelease.firstEntry();
+        String message = null;
+        if (entry != null) {
+            Runtime.Version version = entry.getKey();
+            if (version == null) {
+                return entry.getValue();
+            }
+            message = "Expected base version but found version " + version;
+        }
+        throw new NoSuchElementException(message);
+    }
+
+    /**
+     * Returns the {@code module-info.class} files. Conceptually, there is at most once such file per module.
+     * However, more than one file may exist if additional files are provided for additional Java releases.
+     * This method returns only the files that exist.
+     *
+     * @return all {@code module-info.class} files found for all target Java releases
+     */
+    public List<Path> moduleInfoFiles() {
+        var files = new ArrayList<Path>();
+        filesetForRelease.values().forEach((release) -> {
+            Path file = release.directory.resolve(FileCollector.MODULE_DESCRIPTOR_FILE_NAME);
+            if (Files.isRegularFile(file)) {
+                files.add(file);
+            }
+        });
+        return files;
+    }
+
+    /**
+     * Discards all files in this archive, normally because those files are not in any module.
+     * This method returns a common parent directory for all the files that were discarded.
+     * The caller should use that common directory for logging a warning message.
+     *
+     * @return common directory of discarded files, or {@code null} if none
+     */
+    Path discardAllFiles() {
+        Path base = null;
+        for (FileSet release : filesetForRelease.values()) {
+            base = release.discardAllFiles(base);
+        }
+        filesetForRelease.clear();
+        return base;
+    }
+
+    /**
+     * Removes all empty file sets 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}, then this method ensures that at least one file set
+     * remains even if that file set is empty.
+     *
+     * @param skipIfEmpty value of {@link AbstractJarMojo#skipIfEmpty}
+     */
+    public void prune(final boolean skipIfEmpty) {
+        FileSet keep = (skipIfEmpty || isEmpty())
+                ? null
+                : filesetForRelease.firstEntry().getValue();
+        filesetForRelease.values().removeIf((fs) -> fs.files.isEmpty());
+        Iterator<Map.Entry<Runtime.Version, FileSet>> it =
+                filesetForRelease.entrySet().iterator();
+        if (it.hasNext()) {
+            Map.Entry<Runtime.Version, FileSet> first = it.next();
+            if (first.getKey() == null) {
+                return; // Already contains an entry for the base version, nothing to do.
+            }
+            keep = first.getValue();
+            it.remove();
+        }
+        if (keep != null) {
+            filesetForRelease.put(null, keep);
+        }
+    }
+
+    /**
+     * {@return whether this archive has nothing to archive}
+     * Note that this method may return {@code false} even when there is zero file to archive.
+     * It may happen if {@link AbstractJarMojo#skipIfEmpty} is {@code false}. In such case, the
+     * "empty" <abbr>JAR</abbr> file will still contain at {@code META-INF/MANIFEST.MF} file.
+     *
+     * <h4>Prerequisites</h4>
+     * The {@link #prune(boolean)} method should be invoked before this method for accurate result.
+     */
+    public boolean isEmpty() {
+        return filesetForRelease.isEmpty();
+    }
+
+    /**
+     * Checks whether the <abbr>JAR</abbr> file already exists and can be reused.
+     * This method verifies that the <abbr>JAR</abbr> file contains all the files to archive,
+     * contains no extra file, and no file to archive is newer than the <abbr>JAR</abbr> file.
+     *
+     * <p>This method can be invoked only once.
+     * If invoked more often, it returns {@code false} on all subsequent invocations.</p>
+     *
+     * @return whether the <abbr>JAR</abbr> file already exists and can be reused
+     */
+    public boolean isUpToDateJAR() {
+        final TimestampCheck tc = existingJAR;
+        if (tc == null) {
+            return false;
+        }
+        existingJAR = null; // Let GC do its job.
+        return tc.isUpToDateJAR(filesetForRelease.values());
+    }
+
+    /**
+     * Returns an initially empty set of files or directories for the specified target Java release.
+     *
+     * @param directory the base directory of the files to archive
+     * @param version the target Java release, or {@code null} for the base version
+     * @return container where to declare files and directories to archive
+     */
+    FileSet newTargetRelease(Path directory, Runtime.Version version) {
+        return filesetForRelease.computeIfAbsent(version, (key) -> new FileSet(directory));
+    }
+
+    /**
+     * Sets the {@code --main-class} option to the value of the {@code Main-Class} entry of the given manifest.
+     * As an extension, this method accepts the {@code module/classname} syntax (a syntax already used in some
+     * Java tools). If a module is specified, the main class is kept only if the module match. The intent is to
+     * allow users to specify on which module the main class applies when they use plugin configuration.
+     *
+     * <p>This method may modify the {@code content} manifest. Caller shall ensure that the given manifest
+     * is not a shared instance. This method returns whether a change has actually been done.</p>
+     *
+     * @param content combination of existing {@code MANIFEST.MF} and manifest inferred from configuration, or null
+     * @return whether the given manifest has been modified by this method
+     */
+    boolean setMainClass(Manifest content) {
+        if (content == null || mainClass != null) {
+            return false;
+        }
+        // We need to remove the attribute, otherwise it will conflict with `--main-class`.
+        mainClass = (String) content.getMainAttributes().remove(Attributes.Name.MAIN_CLASS);
+        if (mainClass != null) {
+            int s = mainClass.indexOf('/');
+            if (s >= 0) {
+                if (mainClass.substring(0, s).strip().equals(moduleName)) {
+                    mainClass = mainClass.substring(s + 1).strip();
+                } else {
+                    mainClass = null; // Main class is defined for another module.
+                }
+            }
+        }
+        return mainClass != null;
+    }
+
+    /**
+     * Sets the {@code --manifest} option to the given value if that option was not already set.
+     *
+     * @param file path to the manifest file
+     * @param force whether to set the manifest even if already set
+     * @return whether the manifest has been set
+     */
+    boolean setManifest(Path file, boolean force) {
+        if (manifest == null || force) {
+            manifest = file;
+            return true;
+        }
+        return false;
+    }
+
+    /**
+     * Merges the manifest of this module with the manifest specified in plugin configuration.
+     * If both {@code file} and {@code content} are non-null, then {@code content} must be the
+     * result of reading {@code file}.
+     *
+     * <p>This method never modifies the given {@code content} object. If manifest are merged,
+     * a new {@link Manifest} instance is created. Therefore, caller can check whether this
+     * method returned a new instance as a way to recognize that a merge occurred.</p>
+     *
+     * <p>If a merge occurs, the content specified to {@link #setManifest(Path)} has precedence.
+     * It should be the {@code target/classes/META-INF/MANIFEST.MF} file (or modular equivalent).</p>
+     *
+     * @param  file     an additional manifest file, or {@code null}
+     * @param  content  the content of {@code file}, or a standalone manifest produced at runtime
+     * @return the merged manifest as a new instance if some changes were necessary
+     * @throws IOException if an error occurred while reading a manifest file
+     */
+    Manifest mergeManifest(Path file, Manifest content) throws IOException {
+        if (manifest == null) {
+            manifest = file;
+        } else if (file != null && Files.isSameFile(file, manifest)) {
+            // Nothing to merge because of the constraint that `content` must be the content of `file`.
+        } else {
+            try (InputStream in = Files.newInputStream(manifest)) {
+                // No need to wrap in `BufferedInputStream`.
+                if (content != null) {
+                    content = new Manifest(content);
+                    content.read(in);
+                } else {
+                    content = new Manifest(in);
+                }
+            }
+        }
+        return content;
+    }
+
+    /**
+     * Adds to the given list the arguments to provide to the "jar" tool for each version.
+     * Elements added to the list shall be instances of {@link String} or {@link Path}.
+     * Callers should have added the following options (if applicable) before to invoke this method:
+     *
+     * <ul>
+     *   <li>{@code --create}</li>
+     *   <li>{@code --no-compress}</li>
+     *   <li>{@code --date} followed by the output time stamp</li>
+     *   <li>{@code --module-version} followed by module version</li>
+     *   <li>{@code --hash-modules} followed by patters of module names</li>
+     *   <li>{@code --module-path} followed by module path</li>
+     * </ul>
+     *
+     * This method adds the following options:
+     *
+     * <ul>
+     *   <li>{@code --file} followed by the path to the <abbr>JAR</abbr> file</li>
+     *   <li>{@code --manifest} followed by path to the manifest file</li>
+     *   <li>{@code --main-class} followed by fully qualified name class</li>
+     *   <li>{@code --release} followed by Java target release</li>
+     *   <li>{@code -C} followed by directory</li>
+     *   <li>files or directories to archive</li>
+     * </ul>
+     *
+     * @param addTo the list where to add the arguments as {@link String} or {@link Path} instances
+     */
+    void arguments(final List<Object> addTo) {
+        addTo.add("--file");
+        addTo.add(jarFile);
+        if (manifest != null) {
+            addTo.add("--manifest");
+            addTo.add(manifest);
+        }
+        if (mainClass != null) {
+            addTo.add("--main-class");
+            addTo.add(mainClass);
+        }
+        if (mavenFiles != null) {
+            addTo.add("-C");
+            addTo.addAll(mavenFiles);
+        }
+        for (Map.Entry<Runtime.Version, FileSet> entry : filesetForRelease.entrySet()) {
+            entry.getValue().arguments(addTo, entry.getKey());
+        }
+    }
+
+    /**
+     * Adds to the given list the arguments to provide to the "jar" tool for validating the <abbr>JAR</abbr> file.
+     * The file is validated only if the validation was not done implicitly at <abbr>JAR</abbr> creation time.
+     * This is the case if no {@code --release} option was used.
+     * This method adds the following options:
+     *
+     * <ul>
+     *   <li>{@code --validate} operation mode</li>
+     *   <li>{@code --file} followed by the path to the <abbr>JAR</abbr> file</li>
+     * </ul>
+     *
+     * @param  addTo the list where to add the arguments as {@link String} or {@link Path} instances
+     * @return whether a validation should be run
+     */
+    boolean validate(final List<Object> addTo) {
+        if (filesetForRelease.values().stream().allMatch(Objects::isNull)) {

Review Comment:
   **[B1 — Blocking] `validate()` dead-code condition: checks map values (never null) instead of keys**
   
   The intent here is to skip `--validate` when all entries used `--release` (since the jar tool validates implicitly). However, `filesetForRelease` values are `FileSet` instances — they are **never null** (created via `new FileSet(directory)` in the constructor and `computeIfAbsent`). So `allMatch(Objects::isNull)` is always `false`, and this early-return never triggers.
   
   After `prune()`, the map almost always has a null key (for the base release), so in practice validation always runs anyway. But the code does not match its documented intent.
   
   ```suggestion
           if (!filesetForRelease.containsKey(null)) {
   ```
   
   This checks whether all entries are versioned releases that used `--release`, making the optimization effective.



##########
src/main/java/org/apache/maven/plugins/jar/MetadataFiles.java:
##########
@@ -0,0 +1,250 @@
+/*
+ * 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.jar;
+
+import java.io.BufferedWriter;
+import java.io.Closeable;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Properties;
+import java.util.jar.Manifest;
+import java.util.stream.Collectors;
+
+import org.apache.maven.api.ProducedArtifact;
+import org.apache.maven.api.Project;
+import org.apache.maven.shared.archiver.MavenArchiveConfiguration;
+
+/**
+ * Temporary metadata files generated by Maven before inclusion in the archive.
+ * Those files are created in a temporary {@code META-INF} directory when first needed.
+ * Those files are deleted after the build, unless the build failed or Maven was run in verbose mode.
+ */
+final class MetadataFiles implements Closeable {
+    /**
+     * The {@value} directory.
+     * This is part of <abbr>JAR</abbr> file specification.
+     */
+    static final String META_INF = "META-INF";
+
+    /**
+     * The {@value} file.
+     * This is part of <abbr>JAR</abbr> file specification.
+     */
+    static final String MANIFEST = "MANIFEST.MF";
+
+    /**
+     * The subdirectory where to add Maven-specific files.
+     */
+    static final String MAVEN_DIR = "maven";
+
+    /**
+     * The project for which to write metadata files.
+     */
+    private final Project project;
+
+    /**
+     * The output directory (usually {@code ${baseDir}/target/}).
+     */
+    private final Path buildDir;
+
+    /**
+     * All files and directories in the order that they were created.
+     * The first element of this list shall be the root temporary directory created by this class.
+     */
+    private final List<Path> filesToDelete;
+
+    /**
+     * The <abbr>POM</abbr> file to attach to the artifact. This is initially the project <abbr>POM</abbr>,
+     * but will be replaced by a new file generated by {@link ForModule} if module hierarchy is used.
+     * That file may be copied verbatim in the {@code META-INF/maven/} directory of the <abbr>JAR</abbr>.
+     */
+    private Path attachedPOM;
+
+    /**
+     * Creates an initially empty set of temporary metadata files.
+     *
+     * @param project the project for which to write metadata files
+     * @param buildDir the (usually) {@code ${baseDir}/target/} directory
+     */
+    MetadataFiles(Project project, Path buildDir) {
+        this.project = project;
+        this.buildDir = buildDir;
+        filesToDelete = new ArrayList<>();
+        attachedPOM = project.getPomPath();
+    }
+
+    /**
+     * Derives a <abbr>POM</abbr> as the intersection of the given {@code model} and {@code archive}.
+     *
+     * @param context the tool executor which is generating all archives
+     * @param archive the archive for which to generate a <abbr>POM</abbr>
+     * @param manifest manifest to use for deriving project name, or {@code null} if none
+     * @throws IOException if an error occurred while reading the {@code module-info.class} file
+     *         or while writing the <abbr>POM</abbr> file
+     */
+    void deriveModulePOM(ToolExecutor context, Archive archive, Manifest manifest) throws IOException {
+        var pom = context.pomDerivation.new ForModule(archive, manifest);
+        pom.writeModulePOM();
+        attachedPOM = pom.pomFile;
+        archive.pomFile = pom.pomFile;
+    }
+
+    /**
+     * Adds the given manifest in a temporary file.
+     * The file will be deleted when {@link #close()} is invoked.
+     *
+     * @param manifest the manifest to write
+     * @return the temporary manifest file
+     * @throws IOException if an error occurred while writing the file
+     */
+    public Path addManifest(final Manifest manifest) throws IOException {
+        Path file = baseDirectory().resolve(MANIFEST);
+        try (OutputStream out = Files.newOutputStream(file)) {
+            filesToDelete.add(file);
+            manifest.write(out);
+        }
+        return file;
+    }
+
+    /**
+     * {@return the root temporary directory for the files created by this class}
+     * The directory is created the first time that this method is invoked.
+     *
+     * @throws IOException if an error occurred while creating the temporary directory
+     */
+    private Path baseDirectory() throws IOException {
+        if (filesToDelete.isEmpty()) {
+            filesToDelete.add(Files.createTempDirectory(buildDir, "classes-"));
+        }
+        return filesToDelete.get(0);
+    }
+
+    /**
+     * Creates a new directory and adds it to the list of files to delete after the build.
+     *
+     * @param dir the existing directory where to create a sub-directory
+     * @param path path to the subdirectory to create
+     * @return the new directory
+     * @throws IOException if an error occurred while creating the subdirectory
+     */
+    private Path createDirectories(Path dir, String... path) throws IOException {
+        for (String subdir : path) {
+            dir = Files.createDirectory(dir.resolve(subdir));
+            filesToDelete.add(dir);
+        }
+        return dir;
+    }
+
+    /**
+     * Writes the {@code pom.xml} and {@code pom.properties} files.
+     * This method returns the base temporary directory followed by files that the "jar" tool will need to add
+     *
+     * @param archive archive configuration
+     * @param reproducible whether to enforce reproducible build
+     * @return arguments for the "jar" tool
+     * @throws IOException if an error occurred while writing the files
+     */
+    public List<Path> addPOM(final MavenArchiveConfiguration archive, final boolean reproducible) throws IOException {
+        final String groupId = project.getGroupId();
+        final String artifactId = project.getArtifactId();
+        final String version;
+        final ProducedArtifact pom = project.getPomArtifact();
+        if (pom.isSnapshot()) {
+            version = pom.getVersion().toString();
+        } else {
+            version = project.getVersion();
+        }
+        final Path baseDir = baseDirectory();
+        final Path mavenDir = createDirectories(baseDir, META_INF, MAVEN_DIR, groupId, artifactId);
+        final Path pomFile = linkOrCopy(attachedPOM, mavenDir.resolve("pom.xml"));
+        filesToDelete.add(pomFile); // Add soon for deleting this file even if an exception is thrown below.
+        /*
+         * Subset of above "pom.xml" file but written as a properties file.
+         * If reproducible build is enabled, we will need to reformat after
+         * writing for ensuring a deterministic order of entries.
+         */
+        final var properties = new Properties();
+        Path propertiesFile = archive.getPomPropertiesFile();
+        if (propertiesFile != null) {
+            try (InputStream in = Files.newInputStream(propertiesFile)) {
+                properties.load(in);
+            }
+        }
+        properties.setProperty("groupId", groupId);
+        properties.setProperty("artifactId", artifactId);
+        properties.setProperty("version", version);
+        propertiesFile = mavenDir.resolve("pom.properties");
+        try (BufferedWriter out = Files.newBufferedWriter(propertiesFile)) {
+            filesToDelete.add(propertiesFile); // Add soon for deleting this file even if an exception is thrown below.
+            properties.store(out, "Subset of pom.xml");
+        }
+        if (reproducible) {
+            // The encoding can be either UTF-8 or ISO-8859-1, as any non ASCII character
+            // is transformed into a \\uxxxx sequence anyway.
+            Files.writeString(
+                    propertiesFile,
+                    Files.lines(propertiesFile)
+                            .filter(line -> !line.startsWith("#"))
+                            .sorted()
+                            .collect(Collectors.joining("\n", "", "\n"))); // system independent new line.
+        }
+        return List.of(baseDir, Path.of(META_INF, MAVEN_DIR));
+    }
+
+    /**
+     * Creates a link to the given source if supported, or copies the file otherwise.
+     *
+     * @param source the source file to link or copy
+     * @param target the file to create
+     * @return the target file which should be deleted after the build
+     */
+    private static Path linkOrCopy(final Path source, final Path target) throws IOException {
+        try {
+            return Files.createLink(target, source);
+        } catch (UnsupportedOperationException e) {

Review Comment:
   **[I3 — Important] Cross-device hard links fail with `IOException`, not `UnsupportedOperationException`**
   
   On Linux and macOS, cross-filesystem hard links fail with an `IOException` ("Invalid cross-device link"), not `UnsupportedOperationException`. If the POM file and the temp directory are on different filesystems (e.g., Docker bind-mount), this causes a build failure.
   
   ```suggestion
           } catch (UnsupportedOperationException | IOException e) {
   ```
   
   The subsequent `Files.copy` will propagate its own `IOException` if the copy also fails, so real errors are not masked.



##########
src/main/java/org/apache/maven/plugins/jar/AbstractJarMojo.java:
##########
@@ -207,167 +205,208 @@ protected final Log getLog() {
     protected abstract String getType();
 
     /**
-     * Returns the JAR file to generate, based on an optional classifier.
+     * {@return the scope of dependencies}
+     * It should be {@link PathScope#MAIN_COMPILE} or {@link PathScope#TEST_COMPILE}.
+     * Note that we use compile scope rather than runtime scope because dependencies
+     * cannot appear in {@code requires} statement if they didn't had compile scope.
+     */
+    protected abstract PathScope getDependencyScope();
+
+    /**
+     * {@return the JAR tool to use for archiving the code}
      *
-     * @param basedir the output directory
-     * @param resultFinalName the name of the JAR file
-     * @param classifier an optional classifier
-     * @return the file to generate
+     * @throws MojoException if no JAR tool was found
+     *
+     * @since 4.0.0-beta-2
      */
-    protected Path getJarFile(Path basedir, String resultFinalName, String classifier) {
-        Objects.requireNonNull(basedir, "basedir is not allowed to be null");
-        Objects.requireNonNull(resultFinalName, "finalName is not allowed to be null");
-        String fileName = resultFinalName + (hasClassifier(classifier) ? '-' + classifier : "") + ".jar";
-        return basedir.resolve(fileName);
+    protected ToolProvider getJarTool() throws MojoException {
+        return ToolProvider.findFirst(toolId).orElseThrow(() -> new MojoException("No such \"" + toolId + "\" tool."));
     }
 
     /**
-     * Generates the JAR.
+     * Returns the output time stamp or, as a fallback, the {@code SOURCE_DATE_EPOCH} environment variable.
+     * If the time stamp is expressed in seconds, it is converted to ISO 8601 format. Otherwise it is returned as-is.
      *
-     * @return the path to the created archive file
-     * @throws MojoException in case of an error
+     * @return the time stamp in presumed ISO 8601 format, or {@code null} if none
+     *
+     * @since 4.0.0-beta-2
      */
-    public Path createArchive() throws MojoException {
-        Path basedir = outputDirectory != null
-                ? outputDirectory
-                : Path.of(project.getBuild().getDirectory());
-        String resultFinalName =
-                finalName != null ? finalName : project.getBuild().getFinalName();
-        Path jarFile = getJarFile(basedir, resultFinalName, getClassifier());
-
-        FileSetManager fileSetManager = new FileSetManager();
-        FileSet jarContentFileSet = new FileSet();
-        jarContentFileSet.setDirectory(getClassesDirectory().toAbsolutePath().toString());
-        jarContentFileSet.setIncludes(Arrays.asList(getIncludes()));
-        jarContentFileSet.setExcludes(Arrays.asList(getExcludes()));
-
-        String[] includedFiles = fileSetManager.getIncludedFiles(jarContentFileSet);
-
-        if (detectMultiReleaseJar
-                && Arrays.stream(includedFiles)
-                        .anyMatch(
-                                p -> p.startsWith("META-INF" + File.separatorChar + "versions" + File.separatorChar))) {
-            getLog().debug("Adding 'Multi-Release: true' manifest entry.");
-            archive.addManifestEntry(Attributes.Name.MULTI_RELEASE.toString(), "true");
+    protected String getOutputTimestamp() {
+        String time = nullIfAbsent(outputTimestamp);
+        if (time == null) {
+            time = nullIfAbsent(System.getenv("SOURCE_DATE_EPOCH"));
+            if (time == null) {
+                return null;
+            }
         }
+        if (Runtime.version().feature() < ToolExecutor.JDK_SUPPORT_DATE) {
+            log.warn("Reproducible build requires Java " + ToolExecutor.JDK_SUPPORT_DATE + " or later.");
+            return null;
+        }
+        for (int i = time.length(); --i >= 0; ) {
+            char c = time.charAt(i);
+            if ((c < '0' || c > '9') && (i != 0 || c != '-')) {
+                return time;
+            }
+        }
+        return Instant.ofEpochSecond(Long.parseLong(time)).toString();

Review Comment:
   **[I4 — Important] A lone `"-"` input causes `NumberFormatException`**
   
   The epoch-seconds detection loop allows `-` at position 0 (for negative epochs). But if the string is exactly `"-"`, the loop completes and `Long.parseLong("-")` throws `NumberFormatException` with an unhelpful stack trace.
   
   Consider adding a guard before this line:
   
   ```java
   if (time.length() == 1 && time.charAt(0) == '-') {
       return time; // Not a valid epoch-seconds value
   }
   ```
   
   Or wrap the `parseLong` in a try-catch to provide a clear error message.



##########
src/main/java/org/apache/maven/plugins/jar/MetadataFiles.java:
##########
@@ -0,0 +1,250 @@
+/*
+ * 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.jar;
+
+import java.io.BufferedWriter;
+import java.io.Closeable;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Properties;
+import java.util.jar.Manifest;
+import java.util.stream.Collectors;
+
+import org.apache.maven.api.ProducedArtifact;
+import org.apache.maven.api.Project;
+import org.apache.maven.shared.archiver.MavenArchiveConfiguration;
+
+/**
+ * Temporary metadata files generated by Maven before inclusion in the archive.
+ * Those files are created in a temporary {@code META-INF} directory when first needed.
+ * Those files are deleted after the build, unless the build failed or Maven was run in verbose mode.
+ */
+final class MetadataFiles implements Closeable {
+    /**
+     * The {@value} directory.
+     * This is part of <abbr>JAR</abbr> file specification.
+     */
+    static final String META_INF = "META-INF";
+
+    /**
+     * The {@value} file.
+     * This is part of <abbr>JAR</abbr> file specification.
+     */
+    static final String MANIFEST = "MANIFEST.MF";
+
+    /**
+     * The subdirectory where to add Maven-specific files.
+     */
+    static final String MAVEN_DIR = "maven";
+
+    /**
+     * The project for which to write metadata files.
+     */
+    private final Project project;
+
+    /**
+     * The output directory (usually {@code ${baseDir}/target/}).
+     */
+    private final Path buildDir;
+
+    /**
+     * All files and directories in the order that they were created.
+     * The first element of this list shall be the root temporary directory created by this class.
+     */
+    private final List<Path> filesToDelete;
+
+    /**
+     * The <abbr>POM</abbr> file to attach to the artifact. This is initially the project <abbr>POM</abbr>,
+     * but will be replaced by a new file generated by {@link ForModule} if module hierarchy is used.
+     * That file may be copied verbatim in the {@code META-INF/maven/} directory of the <abbr>JAR</abbr>.
+     */
+    private Path attachedPOM;
+
+    /**
+     * Creates an initially empty set of temporary metadata files.
+     *
+     * @param project the project for which to write metadata files
+     * @param buildDir the (usually) {@code ${baseDir}/target/} directory
+     */
+    MetadataFiles(Project project, Path buildDir) {
+        this.project = project;
+        this.buildDir = buildDir;
+        filesToDelete = new ArrayList<>();
+        attachedPOM = project.getPomPath();
+    }
+
+    /**
+     * Derives a <abbr>POM</abbr> as the intersection of the given {@code model} and {@code archive}.
+     *
+     * @param context the tool executor which is generating all archives
+     * @param archive the archive for which to generate a <abbr>POM</abbr>
+     * @param manifest manifest to use for deriving project name, or {@code null} if none
+     * @throws IOException if an error occurred while reading the {@code module-info.class} file
+     *         or while writing the <abbr>POM</abbr> file
+     */
+    void deriveModulePOM(ToolExecutor context, Archive archive, Manifest manifest) throws IOException {
+        var pom = context.pomDerivation.new ForModule(archive, manifest);
+        pom.writeModulePOM();
+        attachedPOM = pom.pomFile;
+        archive.pomFile = pom.pomFile;
+    }
+
+    /**
+     * Adds the given manifest in a temporary file.
+     * The file will be deleted when {@link #close()} is invoked.
+     *
+     * @param manifest the manifest to write
+     * @return the temporary manifest file
+     * @throws IOException if an error occurred while writing the file
+     */
+    public Path addManifest(final Manifest manifest) throws IOException {
+        Path file = baseDirectory().resolve(MANIFEST);
+        try (OutputStream out = Files.newOutputStream(file)) {
+            filesToDelete.add(file);
+            manifest.write(out);
+        }
+        return file;
+    }
+
+    /**
+     * {@return the root temporary directory for the files created by this class}
+     * The directory is created the first time that this method is invoked.
+     *
+     * @throws IOException if an error occurred while creating the temporary directory
+     */
+    private Path baseDirectory() throws IOException {
+        if (filesToDelete.isEmpty()) {
+            filesToDelete.add(Files.createTempDirectory(buildDir, "classes-"));
+        }
+        return filesToDelete.get(0);
+    }
+
+    /**
+     * Creates a new directory and adds it to the list of files to delete after the build.
+     *
+     * @param dir the existing directory where to create a sub-directory
+     * @param path path to the subdirectory to create
+     * @return the new directory
+     * @throws IOException if an error occurred while creating the subdirectory
+     */
+    private Path createDirectories(Path dir, String... path) throws IOException {
+        for (String subdir : path) {
+            dir = Files.createDirectory(dir.resolve(subdir));
+            filesToDelete.add(dir);
+        }
+        return dir;
+    }
+
+    /**
+     * Writes the {@code pom.xml} and {@code pom.properties} files.
+     * This method returns the base temporary directory followed by files that the "jar" tool will need to add
+     *
+     * @param archive archive configuration
+     * @param reproducible whether to enforce reproducible build
+     * @return arguments for the "jar" tool
+     * @throws IOException if an error occurred while writing the files
+     */
+    public List<Path> addPOM(final MavenArchiveConfiguration archive, final boolean reproducible) throws IOException {
+        final String groupId = project.getGroupId();
+        final String artifactId = project.getArtifactId();
+        final String version;
+        final ProducedArtifact pom = project.getPomArtifact();
+        if (pom.isSnapshot()) {
+            version = pom.getVersion().toString();
+        } else {
+            version = project.getVersion();
+        }
+        final Path baseDir = baseDirectory();
+        final Path mavenDir = createDirectories(baseDir, META_INF, MAVEN_DIR, groupId, artifactId);
+        final Path pomFile = linkOrCopy(attachedPOM, mavenDir.resolve("pom.xml"));
+        filesToDelete.add(pomFile); // Add soon for deleting this file even if an exception is thrown below.
+        /*
+         * Subset of above "pom.xml" file but written as a properties file.
+         * If reproducible build is enabled, we will need to reformat after
+         * writing for ensuring a deterministic order of entries.
+         */
+        final var properties = new Properties();
+        Path propertiesFile = archive.getPomPropertiesFile();
+        if (propertiesFile != null) {
+            try (InputStream in = Files.newInputStream(propertiesFile)) {
+                properties.load(in);
+            }
+        }
+        properties.setProperty("groupId", groupId);
+        properties.setProperty("artifactId", artifactId);
+        properties.setProperty("version", version);
+        propertiesFile = mavenDir.resolve("pom.properties");
+        try (BufferedWriter out = Files.newBufferedWriter(propertiesFile)) {
+            filesToDelete.add(propertiesFile); // Add soon for deleting this file even if an exception is thrown below.
+            properties.store(out, "Subset of pom.xml");
+        }
+        if (reproducible) {
+            // The encoding can be either UTF-8 or ISO-8859-1, as any non ASCII character
+            // is transformed into a \\uxxxx sequence anyway.
+            Files.writeString(
+                    propertiesFile,
+                    Files.lines(propertiesFile)
+                            .filter(line -> !line.startsWith("#"))
+                            .sorted()
+                            .collect(Collectors.joining("\n", "", "\n"))); // system independent new line.
+        }
+        return List.of(baseDir, Path.of(META_INF, MAVEN_DIR));
+    }
+
+    /**
+     * Creates a link to the given source if supported, or copies the file otherwise.
+     *
+     * @param source the source file to link or copy
+     * @param target the file to create
+     * @return the target file which should be deleted after the build
+     */
+    private static Path linkOrCopy(final Path source, final Path target) throws IOException {
+        try {
+            return Files.createLink(target, source);
+        } catch (UnsupportedOperationException e) {
+            return Files.copy(source, target);
+        }
+    }
+
+    /**
+     * Cancels the deletion of files. The files will stay present after the build.
+     * This is desired for allowing user to execute {@code jar} on the command-line,
+     * for example when the build failed.
+     */
+    public void cancelFileDeletion() {
+        filesToDelete.clear();
+    }
+
+    /**
+     * Deletes all temporary files and directories created by this class.
+     *
+     * @throws IOException if an error occurred while deleting a file or directory
+     */
+    @Override
+    public void close() throws IOException {
+        for (int i = filesToDelete.size(); --i >= 0; ) {
+            Files.delete(filesToDelete.get(i));

Review Comment:
   **[I2 — Important] `close()` stops at first delete failure, leaking remaining temp files**
   
   If `Files.delete()` throws on any file (e.g., a file is locked), all remaining files in the list will never be deleted. Consider accumulating the first exception and continuing, adding subsequent failures as suppressed exceptions:
   
   ```java
   @Override
   public void close() throws IOException {
       IOException failure = null;
       for (int i = filesToDelete.size(); --i >= 0; ) {
           try {
               Files.delete(filesToDelete.get(i));
           } catch (IOException e) {
               if (failure == null) {
                   failure = e;
               } else {
                   failure.addSuppressed(e);
               }
           }
       }
       if (failure != null) {
           throw failure;
       }
   }
   ```



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#issuecomment-5314396766

   @seregamorph : just added a commit which creates the `target` directory if it does not exist. Could you try again please?


-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3792341834


##########
src/main/java/org/apache/maven/plugins/jar/AbstractJarMojo.java:
##########
@@ -207,167 +205,199 @@ protected final Log getLog() {
     protected abstract String getType();
 
     /**
-     * Returns the JAR file to generate, based on an optional classifier.
+     * {@return the scope of dependencies}
+     * It should be {@link PathScope#MAIN_COMPILE} or {@link PathScope#TEST_COMPILE}.
+     * Note that we use compile scope rather than runtime scope because dependencies
+     * cannot appear in {@code requires} statement if they didn't had compile scope.
+     */
+    protected abstract PathScope getDependencyScope();
+
+    /**
+     * {@return the JAR tool to use for archiving the code}
      *
-     * @param basedir the output directory
-     * @param resultFinalName the name of the JAR file
-     * @param classifier an optional classifier
-     * @return the file to generate
+     * @throws MojoException if no JAR tool was found
+     *
+     * @since 4.0.0-beta-2
      */
-    protected Path getJarFile(Path basedir, String resultFinalName, String classifier) {
-        Objects.requireNonNull(basedir, "basedir is not allowed to be null");
-        Objects.requireNonNull(resultFinalName, "finalName is not allowed to be null");
-        String fileName = resultFinalName + (hasClassifier(classifier) ? '-' + classifier : "") + ".jar";
-        return basedir.resolve(fileName);
+    protected ToolProvider getJarTool() throws MojoException {
+        return ToolProvider.findFirst(toolId).orElseThrow(() -> new MojoException("No such \"" + toolId + "\" tool."));
     }
 
     /**
-     * Generates the JAR.
+     * Returns whether the specified Java version is supported.
      *
-     * @return the path to the created archive file
-     * @throws MojoException in case of an error
+     * @param release name of an {@link SourceVersion} enumeration constant
+     * @return whether the current environment support that version
      */
-    public Path createArchive() throws MojoException {
-        Path basedir = outputDirectory != null
-                ? outputDirectory
-                : Path.of(project.getBuild().getDirectory());
-        String resultFinalName =
-                finalName != null ? finalName : project.getBuild().getFinalName();
-        Path jarFile = getJarFile(basedir, resultFinalName, getClassifier());
-
-        FileSetManager fileSetManager = new FileSetManager();
-        FileSet jarContentFileSet = new FileSet();
-        jarContentFileSet.setDirectory(getClassesDirectory().toAbsolutePath().toString());
-        jarContentFileSet.setIncludes(Arrays.asList(getIncludes()));
-        jarContentFileSet.setExcludes(Arrays.asList(getExcludes()));
-
-        String[] includedFiles = fileSetManager.getIncludedFiles(jarContentFileSet);
-
-        if (detectMultiReleaseJar
-                && Arrays.stream(includedFiles)
-                        .anyMatch(
-                                p -> p.startsWith("META-INF" + File.separatorChar + "versions" + File.separatorChar))) {
-            getLog().debug("Adding 'Multi-Release: true' manifest entry.");
-            archive.addManifestEntry(Attributes.Name.MULTI_RELEASE.toString(), "true");
+    private static boolean isSupported(String release) {

Review Comment:
   I tried to address the issue with documentation saying that the `outputTimestamp` property (which provides the value of the `--date` option) is supported only with JDK 19 or later. It needed to be documented anyway.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "ascheman (via GitHub)" <gi...@apache.org>.
ascheman commented on PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#issuecomment-5327301051

   > @hboutemy: since reproducible build is supported only partially on Java 17 and 18, we were wondering if it should be a hard build failure if reproducible build is requested on Java 17 or 18. Currently, it is only a warning. If we make it a hard failure, since the `project.build.outputTimestamp` property has a default value in the super POM of all Maven 4 projects, the JAR plugin would fail by default for everyone using Java 17 or 18. A workaround is to opt-out reproducible build in the `pom.xml`:
   > 
   > ```
   >   <properties>
   >     <project.build.outputTimestamp/> <!-- For compatibility with Java 17 and 18. -->
   >   </properties>`
   > ```
   
   There are even more workarounds, i.e., fall back to the 3.x plugin or use a newer JDK (still setting source/target to 17), cf. https://github.com/apache/maven-jar-plugin/commit/0490a3f6e5a9dabf00a0731e5ba51cb267b3e37c (final documentation outstanding). 
   
   > At first, we though that silently producing a non-fully reproducible build on Java 17/18 would be damageable. On a second though, I now think that having all Maven 4 projects failing by default on Java 17/18 is worst. Do you have any opinion on this matter?
   
   In my opinion, we should rather break the build than _only issue a warning_. However, that would hit many people hard when switching to M4/m-jar-p 4.x while still using JDK 17/18.


-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#issuecomment-5332158647

   > If that proves to be true and we can't find a workaround, that's a blocker. Reproducible builds are the more important feature.
   
   I disagree that it is the most important feature. I think that they real feature you are asking for is a way to verify the integrity of a JAR (no malicious code). This is **semantic** reproducible builds, and something that we could provide.


-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3923341900


##########
src/main/java/org/apache/maven/plugins/jar/ToolExecutor.java:
##########
@@ -0,0 +1,551 @@
+/*
+ * 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.jar;
+
+import javax.lang.model.SourceVersion;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+import java.util.spi.ToolProvider;
+
+import org.apache.maven.api.Project;
+import org.apache.maven.api.Type;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.MojoException;
+import org.apache.maven.shared.archiver.MavenArchiveConfiguration;
+
+/**
+ * Writer of <abbr>JAR</abbr> files using the information collected by {@link FileCollector}.
+ * This class uses the {@code "jar"} tool provided with the <abbr>JDK</abbr>.
+ */
+final class ToolExecutor {
+    /**
+     * First JDK feature version whose {@code jar} tool can run {@code --validate} on archives
+     * that contain records. Earlier {@code jar} tools failed with "This feature requires ASM8"
+     * (JDK-8282446, fixed by JDK-8282508 in JDK 19 by not backported to a 17u or 18u update).
+     *
+     * @see <a href="https://bugs.openjdk.org/browse/JDK-8282446">JDK-8282446</a>
+     * @see <a href="https://bugs.openjdk.org/browse/JDK-8282508">JDK-8282508</a>
+     */
+    private static final int JDK_FIXING_JAR_VALIDATE = 19;
+
+    /**
+     * First JDK feature version whose {@code jar} tool support the {@code --date} option.
+     */
+    private static final int JDK_SUPPORT_DATE = 19;
+
+    /**
+     * The {@value} attribute. Its value is automatically generated by {@link Manifest},
+     * but may need to be replaced by another value if JDK-independent value is desired
+     * for strictly reproducible builds.
+     */
+    private static final String CREATED_BY = "Created-By";
+
+    /**
+     * The Maven project for which to create an archive.
+     */
+    final Project project;
+
+    /**
+     * {@code "jar"} or {@link "test-jar"}.
+     */
+    private final String artifactType;
+
+    /**
+     * The output directory where to write the <abbr>JAR</abbr> file.
+     * This is usually {@code ${baseDir}/target/}.
+     */
+    private final Path outputDirectory;
+
+    /**
+     * The <abbr>JAR</abbr> file name when package hierarchy is used.
+     * This is usually a file placed in the {@link ToolExecutor#outputDirectory} directory.
+     */
+    private final String finalName;
+
+    /**
+     * The classifier (e.g. "test"), or {@code null} if none.
+     */
+    private final String classifier;
+
+    /**
+     * Whether to validate the <abbr>JAR</abbr> file after its creation.
+     * If {@code null}, a value will be determined automatically based on heuristic rules.
+     */
+    private final Boolean validate;
+
+    /**
+     * The tool to use for creating the <abbr>JAR</abbr> files.
+     */
+    private final ToolProvider tool;
+
+    /**
+     * Where to send messages emitted by the "jar" tool.
+     */
+    private final PrintWriter messageWriter;
+
+    /**
+     * Where to send error messages emitted by the "jar" tool.
+     */
+    private final PrintWriter errorWriter;
+
+    /**
+     * Where the messages sent to {@link #messageWriter} are stored.
+     */
+    private final StringBuffer messages;
+
+    /**
+     * Where the messages sent to {@link #errorWriter} are stored.
+     */
+    private final StringBuffer errors;
+
+    /**
+     * A buffer for the arguments given to the "jar" tool, reused for each module.
+     * Each element of the list must be instances of either {@link String} or {@link Path}.
+     */
+    private final List<Object> arguments;
+
+    /**
+     * The paths to the created archive files.
+     * Map keys are module names or {@code null} if the project does not use module hierarchy.
+     * Values are (<var>type</var>, <var>path</var>) pairs associated with each module where
+     * <var>type</var> is {@code "pom"}, {@code "jar"} or {@code "test-jar"} and <var>path</var>
+     * is the path to the <abbr>POM</abbr> or <abbr>JAR</abbr> file.
+     */
+    private final Map<String, Map<String, Path>> result;
+
+    /**
+     * Mapper from Maven dependencies to Java modules, or {@code null} if the project does not use module hierarchy.
+     * This mapper is created only once for a Maven project and reused for each Java module to archive.
+     *
+     * <p>This field is not used directly by {@code ToolExecutor}. It is defined in this class for transferring
+     * this information from {@link AbstractJarMojo} to {@link PomDerivation.ForModule}.
+     * This is an internal mechanism that should not be public or protected.</p>
+     */
+    PomDerivation pomDerivation;
+
+    /**
+     * Manifest to merge with the manifest found in the files to archive.
+     * This is a manifest built from the {@code <archive>} plugin configuration.
+     * Can be {@code null} if there is noting to add to the existing manifests.
+     */
+    private final Manifest manifestFromPlugin;
+
+    /**
+     * The file from which {@link #manifestFromPlugin} has been read, or {@code null} if none.
+     * If non-null, reading that file must produce the same manifest as {@link #manifestFromPlugin}.
+     * It implies that this field must be {@code null} if {@link #manifestFromPlugin} is the result
+     * of merging elements specified in {@code <archive>} with a file specified in the plugin configuration.
+     */
+    private final Path manifestFile;
+
+    /**
+     * The archive configuration to use.
+     */
+    private final MavenArchiveConfiguration archiveConfiguration;
+
+    /**
+     * The timestamp in ISO-8601 extended offset date-time, or {@code null} if none.
+     * If user provided a value in seconds, it must have been converted to ISO-8601.
+     * This is used for reproducible builds.
+     */
+    private final String outputTimestamp;
+
+    /**
+     * Whether to force to build new <abbr>JAR</abbr> files even if none of the contents appear to have changed.
+     */
+    private final boolean forceCreation;
+
+    /**
+     * Where to send informative or error messages.
+     */
+    private final Log logger;
+
+    /**
+     * Creates a new writer.
+     *
+     * @param mojo the <abbr>MOJO</abbr> from which to get the configuration
+     * @param manifest manifest built from plugin configuration, or {@code null} if none
+     * @param archive the archive configuration
+     * @throws IOException if an error occurred while reading the manifest file
+     */
+    ToolExecutor(AbstractJarMojo mojo, Manifest manifest, MavenArchiveConfiguration archive) throws IOException {
+        project = mojo.project;
+        artifactType = mojo.getType();
+        outputDirectory = mojo.getOutputDirectory();
+        classifier = AbstractJarMojo.nullIfAbsent(mojo.getClassifier());
+        finalName =
+                (mojo.finalName != null) ? mojo.finalName : project.getBuild().getFinalName();
+        forceCreation = mojo.forceCreation;
+        outputTimestamp = mojo.getOutputTimestamp();
+        validate = mojo.getValidate();
+        logger = mojo.log;
+        tool = mojo.getJarTool();
+
+        var buffer = new StringWriter();
+        messages = buffer.getBuffer();
+        messageWriter = new PrintWriter(buffer);
+
+        buffer = new StringWriter();
+        errors = buffer.getBuffer();
+        errorWriter = new PrintWriter(buffer);
+
+        arguments = new ArrayList<>();
+        result = new LinkedHashMap<>();
+        archiveConfiguration = archive;
+
+        Path file = archive.getManifestFile();
+        if (file != null) {
+            try (InputStream in = Files.newInputStream(file)) {
+                // No need to wrap in `BufferedInputStream`.
+                if (manifest != null) {
+                    manifest.read(in);
+                    file = null; // Because the manifest is the result of a merge.
+                } else {
+                    manifest = new Manifest(in);
+                }
+            }
+        }
+        if (manifest != null) {
+            final Attributes mainAttributes = manifest.getMainAttributes();
+            if (mojo.detectMultiReleaseJar) {
+                mainAttributes.remove(Attributes.Name.MULTI_RELEASE);
+            }
+            if (isReproducible()) {
+                // If a "Created-By" attribute was generated by Maven Archiver, it is assumed JDK-independent.
+                // Otherwise, substitute by another value which does not depend on the JDK.
+                if (mainAttributes.getValue(CREATED_BY) == null) {
+                    mainAttributes.putValue(CREATED_BY, createdBy());
+                }
+            } else {
+                // If reproducible build was not requested, let the tool declares itself.
+                // This is a workaround until we port Maven archiver to this JAR plugin.
+                mainAttributes.remove(CREATED_BY);
+            }
+        }
+        manifestFromPlugin = manifest;
+        manifestFile = file;
+    }
+
+    /**
+     * Whether reproducible build was requested.
+     * In current version, the output time stamp is used as a sentinel value.
+     */
+    public boolean isReproducible() {
+        return outputTimestamp != null;
+    }
+
+    /**
+     * Returns the default {@value #CREATED_BY} value to use when strictly reproducible builds is requested.
+     * This value is ignored if the Maven Archiver or if user's configuration provided themselves a value.
+     *
+     * @return a JDK-independent {@value #CREATED_BY} value
+     */
+    private static String createdBy() {
+        String value = "Maven JAR Plugin";
+        String version = ToolExecutor.class.getPackage().getImplementationVersion();
+        if (version != null) {
+            value = value + ' ' + version;
+        }
+        return value;
+    }
+
+    /**
+     * Creates an initially empty archive for <abbr>JAR</abbr> file to generate.
+     * This method does not create the <abbr>JAR</abbr> file immediately,
+     * but collect information for creating the file later.
+     *
+     * @param  moduleName the module name if using module hierarchy, or {@code null} if using package hierarchy
+     * @param  version the target Java release, or {@code null} for the base version
+     * @param  directory the directory of the classes targeting the base Java release
+     */
+    Archive newArchive(final String moduleName, final Runtime.Version version, final Path directory) {
+        var sb = new StringBuilder(60);
+        if (moduleName != null) {
+            sb.append(moduleName).append('-').append(project.getVersion());
+        } else {
+            sb.append(finalName);
+        }
+        if (classifier != null) {
+            sb.append('-').append(classifier);
+        }
+        String filename = sb.append(".jar").toString();
+        return new Archive(outputDirectory.resolve(filename), moduleName, version, directory, forceCreation, logger);
+    }
+
+    /**
+     * Writes all <abbr>JAR</abbr> files, together with their derived <abbr>POM</abbr> files if applicable.
+     * The derived <abbr>POM</abbr> files are the intersections of the project <abbr>POM</abbr> with the
+     * content of {@code module-info.class} files.
+     *
+     * <h4>Prerequisites</h4>
+     * The {@link FileCollector#prune(boolean)} method should have been invoked once before to invoke this method.
+     *
+     * @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
+     * @throws MojoException if an error occurred during the execution of the "jar" tool
+     * @throws IOException if an error occurred while reading or writing a manifest file
+     */
+    @SuppressWarnings("ReturnOfCollectionOrArrayField")
+    public Map<String, Map<String, Path>> writeAllJARs(final FileCollector files) throws IOException {
+        Path ignored = files.handleOrphanFiles();
+        Path parentPOM = files.writeAllJARs(this);
+        if (ignored != null) {
+            logger.warn("Some files in \"" + relativize(outputDirectory, ignored)
+                    + "\" were ignored because they belong to no module.");
+        }
+        if (parentPOM != null) {
+            if (result.put(null, Map.of(Type.POM, parentPOM)) != null) {
+                throw new MojoException("Internal error."); // Should never happen.
+            }
+        }
+        return result;
+    }
+
+    /**
+     * Creates the <abbr>JAR</abbr> files for the specified set of files.
+     * If the operation fails, an error message may be available in the {@link #errors} buffer.
+     *
+     * @param files the result of scanning the build directory for listing the files or directories to archive
+     * @throws MojoException if an error occurred during the execution of the "jar" tool
+     * @throws IOException if an error occurred while reading or writing a manifest file
+     */
+    void writeSingleJAR(final FileCollector files, final Archive archive) throws IOException {
+        final Path relativePath = relativize(project.getRootDirectory(), archive.jarFile);
+        if (archive.isUpToDateJAR()) {
+            logger.info("Keep up-to-date JAR: \"" + relativePath + "\".");
+            archive.saveArtifactPaths(artifactType, result);
+            return;
+        }
+        logger.info("Building JAR: \"" + relativePath + "\".");
+        /*
+         * If `MANIFEST.MF` entries were specified by JAR plugin configuration,
+         * merge those entries with the content of `MANIFEST.MF` file found in
+         * the files to archive.
+         */
+        boolean writeTemporaryManifest = (manifestFromPlugin != null && manifestFile == null); // Check <archive>.
+        Manifest manifest = archive.mergeManifest(manifestFile, manifestFromPlugin);
+        if (manifest != manifestFromPlugin) {
+            writeTemporaryManifest |= (manifestFromPlugin != null); // Check if a merge of two manifests.
+        } else if (manifest != null) {
+            /*
+             * `setMainClass` below removes the Main-Class attribute, and `manifestFromPlugin` is
+             * shared across every module of a module hierarchy. Work on a per-module copy so that
+             * the (unspecified) directory iteration order does not decide which module keeps the
+             * main class: otherwise a non-owning module processed first consumes the attribute and
+             * the owning module never receives it.
+             */
+            manifest = new Manifest(manifest);
+        }
+        writeTemporaryManifest |= archive.setMainClass(manifest);
+        if (manifest != null) {
+            String name = manifest.getMainAttributes().getValue("Automatic-Module-Name");
+            if (name != null && !SourceVersion.isName(name)) {
+                throw new MojoException("Invalid automatic module name: \"" + name + "\".");
+            }
+        }
+        /*
+         * Creates temporary files for META-INF (if the existing file cannot be used directly)
+         * and for the Maven metadata (if requested). The temporary files are in the `target`
+         * directory and will be deleted, unless the build fails or is run in verbose mode.
+         */
+        try (MetadataFiles metadata = new MetadataFiles(project, outputDirectory)) {
+            if (writeTemporaryManifest) {
+                archive.setManifest(metadata.addManifest(manifest), true);
+            }
+            if (archive.moduleName != null) {
+                metadata.deriveModulePOM(this, archive, manifest);
+            }
+            if (archiveConfiguration.isAddMavenDescriptor()) {
+                archive.mavenFiles = metadata.addPOM(archiveConfiguration, isReproducible());
+            }
+            /*
+             * Prepare the arguments to send to the `jar` tool and log a message.
+             */
+            arguments.add("--create");
+            if (!archiveConfiguration.isCompress()) {
+                arguments.add("--no-compress");
+            }
+            if (outputTimestamp != null) {
+                if (Runtime.version().feature() >= JDK_SUPPORT_DATE) {

Review Comment:
   This is a about the JDK version which supports the `--date` option, so `DATE` needs to appear somewhere.



##########
src/main/java/org/apache/maven/plugins/jar/ToolExecutor.java:
##########
@@ -0,0 +1,551 @@
+/*
+ * 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.jar;
+
+import javax.lang.model.SourceVersion;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+import java.util.spi.ToolProvider;
+
+import org.apache.maven.api.Project;
+import org.apache.maven.api.Type;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.MojoException;
+import org.apache.maven.shared.archiver.MavenArchiveConfiguration;
+
+/**
+ * Writer of <abbr>JAR</abbr> files using the information collected by {@link FileCollector}.
+ * This class uses the {@code "jar"} tool provided with the <abbr>JDK</abbr>.
+ */
+final class ToolExecutor {
+    /**
+     * First JDK feature version whose {@code jar} tool can run {@code --validate} on archives
+     * that contain records. Earlier {@code jar} tools failed with "This feature requires ASM8"
+     * (JDK-8282446, fixed by JDK-8282508 in JDK 19 by not backported to a 17u or 18u update).
+     *
+     * @see <a href="https://bugs.openjdk.org/browse/JDK-8282446">JDK-8282446</a>
+     * @see <a href="https://bugs.openjdk.org/browse/JDK-8282508">JDK-8282508</a>
+     */
+    private static final int JDK_FIXING_JAR_VALIDATE = 19;
+
+    /**
+     * First JDK feature version whose {@code jar} tool support the {@code --date} option.
+     */
+    private static final int JDK_SUPPORT_DATE = 19;
+
+    /**
+     * The {@value} attribute. Its value is automatically generated by {@link Manifest},
+     * but may need to be replaced by another value if JDK-independent value is desired
+     * for strictly reproducible builds.
+     */
+    private static final String CREATED_BY = "Created-By";
+
+    /**
+     * The Maven project for which to create an archive.
+     */
+    final Project project;
+
+    /**
+     * {@code "jar"} or {@link "test-jar"}.
+     */
+    private final String artifactType;
+
+    /**
+     * The output directory where to write the <abbr>JAR</abbr> file.
+     * This is usually {@code ${baseDir}/target/}.
+     */
+    private final Path outputDirectory;
+
+    /**
+     * The <abbr>JAR</abbr> file name when package hierarchy is used.
+     * This is usually a file placed in the {@link ToolExecutor#outputDirectory} directory.
+     */
+    private final String finalName;
+
+    /**
+     * The classifier (e.g. "test"), or {@code null} if none.
+     */
+    private final String classifier;
+
+    /**
+     * Whether to validate the <abbr>JAR</abbr> file after its creation.
+     * If {@code null}, a value will be determined automatically based on heuristic rules.
+     */
+    private final Boolean validate;
+
+    /**
+     * The tool to use for creating the <abbr>JAR</abbr> files.
+     */
+    private final ToolProvider tool;
+
+    /**
+     * Where to send messages emitted by the "jar" tool.
+     */
+    private final PrintWriter messageWriter;
+
+    /**
+     * Where to send error messages emitted by the "jar" tool.
+     */
+    private final PrintWriter errorWriter;
+
+    /**
+     * Where the messages sent to {@link #messageWriter} are stored.
+     */
+    private final StringBuffer messages;

Review Comment:
   No. It is the buffer used by `java.io.StringWriter`, we don't have the choice. Another circumstance (not in this case) where we are forced to use `StringBuffer` even in a single thread is when using `java.text.Format`.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#issuecomment-5525104696

   Hello @elharo . I tried to address the new round of issues. Note: contrarily to what I said in comment, I had to remove the `title` attribute: it is not accepted by Javadoc. Apparently, Javadoc accepts only a small subset of HTML, which includes explicitly the following elements: `<abbr>`, `<acronym>`, `<cite>`, `<code>`, `<dfn>`, `<em>`, `<kbd>`, `<samp>`, `<var>`, `<strong>` (from Javadoc test suite). We know that some more are accepted such as `<i>`, but I did not saw them in the Javadoc tests that I looked at.


-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3921866746


##########
src/main/java/org/apache/maven/plugins/jar/Archive.java:
##########
@@ -0,0 +1,655 @@
+/*
+ * 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.jar;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.TreeMap;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.Type;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.MojoException;
+
+/**
+ * Files or root directories to archive for a single module.
+ * A single instance of {@code Archive} can contain many directories for different target Java releases.
+ * Many instances of {@code Archive} can exist when archiving a multi-modules project.
+ */
+final class Archive {
+    /**
+     * Path to the <abbr>POM</abbr> file generated for this archive, or {@code null} if none.
+     * This is non-null only if module source hierarchy is used, in which case the dependencies
+     * declared in this file are the intersection of the project dependencies and the content of
+     * the {@code module-info.class} file.
+     */
+    @Nullable
+    Path pomFile;
+
+    /**
+     * The <var>JAR</var> file to create. Can be an existing file,
+     * in which case the file creation can be skipped if the file is still up-to-date.
+     */
+    @Nonnull
+    final Path jarFile;
+
+    /**
+     * A helper class for checking whether an existing <abbr>JAR</abbr> file is still up-to-date.
+     * This is null if there is no existing JAR file, or if we determined that the file is outdated.
+     */
+    private TimestampCheck existingJAR;
+
+    /**
+     * Name of the module being archived when the project is using module hierarchy.
+     * This is {@code null} if the project is using package hierarchy, either because it is a classical
+     * class-path project or because it is a single module compiled without using the module hierarchy.
+     * When using module source hierarchy, {@code javac} guarantees that the module name in the output
+     * directory is the name of the parent directory of {@code module-info.class}.
+     */
+    @Nullable
+    final String moduleName;
+
+    /**
+     * Path to {@code META-INF/MANIFEST.MF}, or {@code null} if none.
+     * If non-null, this value will be given to the {@code --manifest} option.
+     * The use of this option is preferable to adding {@code MANIFEST.MF} as an ordinary file.
+     *
+     * @see #setManifest(Path, boolean)
+     * @see #mergeManifest(Path, Manifest)
+     */
+    @Nullable
+    private Path manifest;
+
+    /**
+     * The Maven generated {@code pom.xml} and {@code pom.properties} files, or {@code null} if none.
+     * This first item must be the base directory where the files are located.
+     */
+    @Nullable
+    List<Path> mavenFiles;
+
+    /**
+     * Fully-qualified name of the main class, or {@code null} if none.
+     * This is the value to provide to the {@code --main-class} option.
+     */
+    private String mainClass;
+
+    /**
+     * Files or root directories to store in the <abbr>JAR</abbr> file for each target Java release
+     * other than the base release. Keys are the target Java release with {@code null} for the base
+     * release.
+     */
+    @Nonnull
+    private final NavigableMap<Runtime.Version, FileSet> filesetForRelease;
+
+    /**
+     * Files or root directories to archive for a single target Java release of a single module.
+     * The {@link Archive} enclosing must contain at least one instance of {@code FileSet} for
+     * the base release, and an arbitrary amount of other instances for other target releases.
+     */
+    final class FileSet {
+        /**
+         * The root directory of all files or directories to archive.
+         * This is the value to pass to the {@code -C} tool option.
+         */
+        @Nonnull
+        final Path directory;
+
+        /**
+         * The files or directories to include in the <var>JAR</var> file.
+         * Can be absolute paths or paths relative to {@link #directory}.
+         * It usually contains only the files or directories directly in
+         * the root {@linkplain #directory}, not in sub-directories.
+         */
+        @Nonnull
+        final List<Path> files;
+
+        /**
+         * Creates an initially empty set of files or directories for a specific target Java release.
+         *
+         * @param directory the base directory of the files or directories to archive
+         */
+        private FileSet(Path directory) {
+            this.directory = directory;
+            this.files = new ArrayList<>();
+        }
+
+        /**
+         * 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.
+         * The caller should use that common directory for logging a warning message.
+         *
+         * @param base base directory found by previous invocations of this method, or {@code null} if none
+         * @return common directory of discarded files
+         */
+        private Path discardAllFiles(Path base) {
+            for (Path file : files) {
+                if (base == null) {
+                    base = file.getParent();
+                } else {
+                    while (!file.startsWith(base)) {
+                        base = base.getParent();
+                        if (base == null) {
+                            break;
+                        }
+                    }
+                }
+            }
+            files.clear();
+            return base;
+        }
+
+        /**
+         * Adds the given path to the list of files or directories to archive.
+         * If the given path is a directory, then all children will be included.
+         * Children to exclude, if any, should be managed by {@link ExcludedFiles}.
+         *
+         * @param item a file or directory to archive
+         * @param attributes the file's basic attributes
+         * @param isDirectory whether the file is a directory
+         */
+        void add(Path item, BasicFileAttributes attributes, boolean isDirectory) {
+            TimestampCheck tc = existingJAR;
+            if (tc != null && tc.isUpdated(item, attributes, isDirectory)) {
+                existingJAR = null; // Signal that the existing file is outdated.
+            }
+            files.add(item);
+        }
+
+        /**
+         * Adds to the given list the arguments to provide to the "jar" tool for this version.
+         * The elements added to the list will be instances of {@link String} or {@link Path}.
+         *
+         * <h4>Note about the {@code -C} option</h4>
+         * This method repeats the {@code -C} option before each file.
+         * Our tests suggest that the first file after the directory specified by the {@code -C} option must
+         * be relative to that directory and all files after the first one must be prefixed by the directory
+         * which was specified in the {@code -C} option. This behavior is not very intuitive and replying on
+         * it can be fragile. Furthermore, it seems that the relativized file needs to be the shortest one,
+         * otherwise the {@code jar} tool rejects files after the first one with "names do not match".
+         * Which file is first depends on the unspecified directory-iteration order.
+         * Repeating the {@code -C} option for each file seems safer.
+         *
+         * @param addTo the list to add the arguments as {@link String} or {@link Path} instances to
+         * @param version the target Java release, or {@code null} for the base version of the <abbr>JAR</abbr> file
+         * @throws IllegalArgumentException if a path cannot be made relative to the base directory
+         */
+        private void arguments(List<Object> addTo, Runtime.Version version) {
+            if (files.isEmpty()) {
+                return;
+            }
+            if (version != null) {
+                addTo.add("--release");
+                addTo.add(version);
+            }
+            Path previous = null;
+            for (Path file : files) {
+                if (previous != null && file.startsWith(previous)) {
+                    // Already added a parent directory.
+                    continue;
+                }
+                previous = file;
+                file = directory.relativize(file);
+                if (file.getNameCount() <= 1 && file.toString().isEmpty()) {
+                    /*
+                     * The `-C` directory itself (e.g. a "META-INF/versions/<n>" directory added as a whole).
+                     * An empty file argument is invalid for the `jar` tool (some implementations reject it,
+                     * others silently misbehave), so archive the whole directory content with ".".
+                     */
+                    file = Path.of(".");
+                }
+                addTo.add("-C");
+                addTo.add(directory);
+                addTo.add(file);
+            }
+        }
+
+        /**
+         * {@return a string representation for debugging purposes}
+         */
+        @Override
+        public String toString() {
+            return getClass().getSimpleName() + '[' + directory.getFileName() + ": " + files.size() + " files]";
+        }
+    }
+
+    /**
+     * Creates an initially empty set of files or directories.
+     *
+     * @param jarFile path to the <abbr>JAR</abbr> file to create
+     * @param moduleName the module name if using module hierarchy, or {@code null} if using package hierarchy
+     * @param version the target Java release, or {@code null} for the base version
+     * @param directory the directory of the classes targeting the base Java release
+     * @param forceCreation whether to force a new <abbr>JAR</abbr> file even if the content seems unchanged
+     * @param logger where to send a warning if an error occurred while checking an existing <abbr>JAR</abbr> file
+     */
+    @SuppressWarnings("checkstyle:NeedBraces")
+    Archive(
+            final Path jarFile,
+            final String moduleName,
+            final Runtime.Version version,
+            final Path directory,
+            final boolean forceCreation,
+            final Log logger) {
+        this.jarFile = jarFile;
+        this.moduleName = moduleName;
+        filesetForRelease = new TreeMap<>((v1, v2) -> {
+            if (v1 == v2) return 0;
+            if (v1 == null) return -1;
+            if (v2 == null) return +1;
+            return v1.compareTo(v2);
+        });
+        filesetForRelease.put(version, new FileSet(directory));
+        if (!forceCreation && Files.isRegularFile(jarFile)) {
+            try {
+                existingJAR = new TimestampCheck(jarFile, directory, logger);
+            } catch (IOException e) {
+                // Ignore, we will regenerate the JAR file.
+                logger.warn(e);
+            }
+        }
+    }
+
+    /**
+     * {@return the files or directories to store in the <abbr>JAR</abbr> file for targeting the base Java release}
+     *
+     * @throws NoSuchElementException should not happen unless {@link #prune(boolean)} has been invoked
+     */
+    FileSet baseRelease() {
+        Map.Entry<Runtime.Version, FileSet> entry = filesetForRelease.firstEntry();
+        String message = null;
+        if (entry != null) {
+            Runtime.Version version = entry.getKey();
+            if (version == null) {
+                return entry.getValue();
+            }
+            message = "Expected base version but found version " + version;
+        }
+        throw new NoSuchElementException(message);
+    }
+
+    /**
+     * Returns the {@code module-info.class} files. Conceptually, there is at most once such file per module.
+     * However, more than one file can exist if additional files are provided for additional Java releases.
+     * This method returns only the files that exist.
+     *
+     * @return all {@code module-info.class} files found for all target Java releases
+     */
+    public List<Path> moduleInfoFiles() {
+        var files = new ArrayList<Path>();
+        filesetForRelease.values().forEach((release) -> {
+            Path file = release.directory.resolve(FileCollector.MODULE_DESCRIPTOR_FILE_NAME);
+            if (Files.isRegularFile(file)) {
+                files.add(file);
+            }
+        });
+        return files;
+    }
+
+    /**
+     * Discards all files in this archive, normally because those files are not in any module.
+     * This method returns a common parent directory for all the files that were discarded.
+     * The caller should use that common directory for logging a warning message.
+     *
+     * @return common directory of discarded files, or {@code null} if none
+     */
+    Path discardAllFiles() {
+        Path base = null;
+        for (FileSet release : filesetForRelease.values()) {
+            base = release.discardAllFiles(base);
+        }
+        filesetForRelease.clear();
+        return base;
+    }
+
+    /**
+     * Removes all empty file sets 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}, then this method ensures that at least one file set
+     * remains even if that file set is empty.
+     *
+     * @param skipIfEmpty value of {@link AbstractJarMojo#skipIfEmpty}
+     */
+    public void prune(final boolean skipIfEmpty) {
+        FileSet keep = (skipIfEmpty || isEmpty())
+                ? null
+                : filesetForRelease.firstEntry().getValue();
+        filesetForRelease.values().removeIf((fs) -> fs.files.isEmpty());
+        Iterator<Map.Entry<Runtime.Version, FileSet>> it =
+                filesetForRelease.entrySet().iterator();
+        if (it.hasNext()) {
+            Map.Entry<Runtime.Version, FileSet> first = it.next();
+            if (first.getKey() == null) {
+                return; // Already contains an entry for the base version, nothing to do.
+            }
+            keep = first.getValue();
+            it.remove();
+        }
+        if (keep != null) {
+            filesetForRelease.put(null, keep);
+        }
+    }
+
+    /**
+     * {@return whether this archive has nothing to archive}
+     * This method can return {@code false} even when there is zero file to archive.
+     * It can happen if {@link AbstractJarMojo#skipIfEmpty} is {@code false}. In such case, the
+     * "empty" <abbr>JAR</abbr> file will still contain at {@code META-INF/MANIFEST.MF} file.
+     *
+     * <h4>Prerequisites</h4>
+     * The {@link #prune(boolean)} method should be invoked before this method for accurate result.

Review Comment:
   For avoiding to invoke `prune` twice when the caller already needed to invoke it anyway for other reasons. Also because `prune` takes a `boolean` argument, and we would have to propagate that argument in a few methods: `isEmpty` itself, then a few more methods which invoke `isEmpty`.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3921971343


##########
src/main/java/org/apache/maven/plugins/jar/Archive.java:
##########
@@ -0,0 +1,655 @@
+/*
+ * 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.jar;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.TreeMap;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.Type;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.MojoException;
+
+/**
+ * Files or root directories to archive for a single module.
+ * A single instance of {@code Archive} can contain many directories for different target Java releases.
+ * Many instances of {@code Archive} can exist when archiving a multi-modules project.
+ */
+final class Archive {
+    /**
+     * Path to the <abbr>POM</abbr> file generated for this archive, or {@code null} if none.
+     * This is non-null only if module source hierarchy is used, in which case the dependencies
+     * declared in this file are the intersection of the project dependencies and the content of
+     * the {@code module-info.class} file.
+     */
+    @Nullable
+    Path pomFile;
+
+    /**
+     * The <var>JAR</var> file to create. Can be an existing file,
+     * in which case the file creation can be skipped if the file is still up-to-date.
+     */
+    @Nonnull
+    final Path jarFile;
+
+    /**
+     * A helper class for checking whether an existing <abbr>JAR</abbr> file is still up-to-date.
+     * This is null if there is no existing JAR file, or if we determined that the file is outdated.
+     */
+    private TimestampCheck existingJAR;
+
+    /**
+     * Name of the module being archived when the project is using module hierarchy.
+     * This is {@code null} if the project is using package hierarchy, either because it is a classical
+     * class-path project or because it is a single module compiled without using the module hierarchy.
+     * When using module source hierarchy, {@code javac} guarantees that the module name in the output
+     * directory is the name of the parent directory of {@code module-info.class}.
+     */
+    @Nullable
+    final String moduleName;
+
+    /**
+     * Path to {@code META-INF/MANIFEST.MF}, or {@code null} if none.
+     * If non-null, this value will be given to the {@code --manifest} option.
+     * The use of this option is preferable to adding {@code MANIFEST.MF} as an ordinary file.
+     *
+     * @see #setManifest(Path, boolean)
+     * @see #mergeManifest(Path, Manifest)
+     */
+    @Nullable
+    private Path manifest;
+
+    /**
+     * The Maven generated {@code pom.xml} and {@code pom.properties} files, or {@code null} if none.
+     * This first item must be the base directory where the files are located.
+     */
+    @Nullable
+    List<Path> mavenFiles;
+
+    /**
+     * Fully-qualified name of the main class, or {@code null} if none.
+     * This is the value to provide to the {@code --main-class} option.
+     */
+    private String mainClass;
+
+    /**
+     * Files or root directories to store in the <abbr>JAR</abbr> file for each target Java release
+     * other than the base release. Keys are the target Java release with {@code null} for the base
+     * release.
+     */
+    @Nonnull
+    private final NavigableMap<Runtime.Version, FileSet> filesetForRelease;
+
+    /**
+     * Files or root directories to archive for a single target Java release of a single module.
+     * The {@link Archive} enclosing must contain at least one instance of {@code FileSet} for
+     * the base release, and an arbitrary amount of other instances for other target releases.
+     */
+    final class FileSet {
+        /**
+         * The root directory of all files or directories to archive.
+         * This is the value to pass to the {@code -C} tool option.
+         */
+        @Nonnull
+        final Path directory;
+
+        /**
+         * The files or directories to include in the <var>JAR</var> file.
+         * Can be absolute paths or paths relative to {@link #directory}.
+         * It usually contains only the files or directories directly in
+         * the root {@linkplain #directory}, not in sub-directories.
+         */
+        @Nonnull
+        final List<Path> files;
+
+        /**
+         * Creates an initially empty set of files or directories for a specific target Java release.
+         *
+         * @param directory the base directory of the files or directories to archive
+         */
+        private FileSet(Path directory) {
+            this.directory = directory;
+            this.files = new ArrayList<>();
+        }
+
+        /**
+         * 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.
+         * The caller should use that common directory for logging a warning message.
+         *
+         * @param base base directory found by previous invocations of this method, or {@code null} if none
+         * @return common directory of discarded files
+         */
+        private Path discardAllFiles(Path base) {
+            for (Path file : files) {
+                if (base == null) {
+                    base = file.getParent();
+                } else {
+                    while (!file.startsWith(base)) {
+                        base = base.getParent();
+                        if (base == null) {
+                            break;
+                        }
+                    }
+                }
+            }
+            files.clear();
+            return base;
+        }
+
+        /**
+         * Adds the given path to the list of files or directories to archive.
+         * If the given path is a directory, then all children will be included.
+         * Children to exclude, if any, should be managed by {@link ExcludedFiles}.
+         *
+         * @param item a file or directory to archive
+         * @param attributes the file's basic attributes
+         * @param isDirectory whether the file is a directory
+         */
+        void add(Path item, BasicFileAttributes attributes, boolean isDirectory) {
+            TimestampCheck tc = existingJAR;
+            if (tc != null && tc.isUpdated(item, attributes, isDirectory)) {
+                existingJAR = null; // Signal that the existing file is outdated.
+            }
+            files.add(item);
+        }
+
+        /**
+         * Adds to the given list the arguments to provide to the "jar" tool for this version.
+         * The elements added to the list will be instances of {@link String} or {@link Path}.
+         *
+         * <h4>Note about the {@code -C} option</h4>
+         * This method repeats the {@code -C} option before each file.
+         * Our tests suggest that the first file after the directory specified by the {@code -C} option must
+         * be relative to that directory and all files after the first one must be prefixed by the directory
+         * which was specified in the {@code -C} option. This behavior is not very intuitive and replying on
+         * it can be fragile. Furthermore, it seems that the relativized file needs to be the shortest one,
+         * otherwise the {@code jar} tool rejects files after the first one with "names do not match".
+         * Which file is first depends on the unspecified directory-iteration order.
+         * Repeating the {@code -C} option for each file seems safer.
+         *
+         * @param addTo the list to add the arguments as {@link String} or {@link Path} instances to
+         * @param version the target Java release, or {@code null} for the base version of the <abbr>JAR</abbr> file
+         * @throws IllegalArgumentException if a path cannot be made relative to the base directory
+         */
+        private void arguments(List<Object> addTo, Runtime.Version version) {
+            if (files.isEmpty()) {
+                return;
+            }
+            if (version != null) {
+                addTo.add("--release");
+                addTo.add(version);
+            }
+            Path previous = null;
+            for (Path file : files) {
+                if (previous != null && file.startsWith(previous)) {
+                    // Already added a parent directory.
+                    continue;
+                }
+                previous = file;
+                file = directory.relativize(file);
+                if (file.getNameCount() <= 1 && file.toString().isEmpty()) {
+                    /*
+                     * The `-C` directory itself (e.g. a "META-INF/versions/<n>" directory added as a whole).
+                     * An empty file argument is invalid for the `jar` tool (some implementations reject it,
+                     * others silently misbehave), so archive the whole directory content with ".".
+                     */
+                    file = Path.of(".");
+                }
+                addTo.add("-C");
+                addTo.add(directory);
+                addTo.add(file);
+            }
+        }
+
+        /**
+         * {@return a string representation for debugging purposes}
+         */
+        @Override
+        public String toString() {
+            return getClass().getSimpleName() + '[' + directory.getFileName() + ": " + files.size() + " files]";
+        }
+    }
+
+    /**
+     * Creates an initially empty set of files or directories.
+     *
+     * @param jarFile path to the <abbr>JAR</abbr> file to create
+     * @param moduleName the module name if using module hierarchy, or {@code null} if using package hierarchy
+     * @param version the target Java release, or {@code null} for the base version
+     * @param directory the directory of the classes targeting the base Java release
+     * @param forceCreation whether to force a new <abbr>JAR</abbr> file even if the content seems unchanged
+     * @param logger where to send a warning if an error occurred while checking an existing <abbr>JAR</abbr> file
+     */
+    @SuppressWarnings("checkstyle:NeedBraces")
+    Archive(
+            final Path jarFile,
+            final String moduleName,
+            final Runtime.Version version,
+            final Path directory,
+            final boolean forceCreation,
+            final Log logger) {
+        this.jarFile = jarFile;
+        this.moduleName = moduleName;
+        filesetForRelease = new TreeMap<>((v1, v2) -> {
+            if (v1 == v2) return 0;
+            if (v1 == null) return -1;
+            if (v2 == null) return +1;
+            return v1.compareTo(v2);
+        });
+        filesetForRelease.put(version, new FileSet(directory));
+        if (!forceCreation && Files.isRegularFile(jarFile)) {
+            try {
+                existingJAR = new TimestampCheck(jarFile, directory, logger);
+            } catch (IOException e) {
+                // Ignore, we will regenerate the JAR file.
+                logger.warn(e);
+            }
+        }
+    }
+
+    /**
+     * {@return the files or directories to store in the <abbr>JAR</abbr> file for targeting the base Java release}
+     *
+     * @throws NoSuchElementException should not happen unless {@link #prune(boolean)} has been invoked
+     */
+    FileSet baseRelease() {
+        Map.Entry<Runtime.Version, FileSet> entry = filesetForRelease.firstEntry();
+        String message = null;
+        if (entry != null) {
+            Runtime.Version version = entry.getKey();
+            if (version == null) {
+                return entry.getValue();
+            }
+            message = "Expected base version but found version " + version;
+        }
+        throw new NoSuchElementException(message);
+    }
+
+    /**
+     * Returns the {@code module-info.class} files. Conceptually, there is at most once such file per module.
+     * However, more than one file can exist if additional files are provided for additional Java releases.
+     * This method returns only the files that exist.
+     *
+     * @return all {@code module-info.class} files found for all target Java releases
+     */
+    public List<Path> moduleInfoFiles() {
+        var files = new ArrayList<Path>();
+        filesetForRelease.values().forEach((release) -> {
+            Path file = release.directory.resolve(FileCollector.MODULE_DESCRIPTOR_FILE_NAME);
+            if (Files.isRegularFile(file)) {
+                files.add(file);
+            }
+        });
+        return files;
+    }
+
+    /**
+     * Discards all files in this archive, normally because those files are not in any module.
+     * This method returns a common parent directory for all the files that were discarded.
+     * The caller should use that common directory for logging a warning message.
+     *
+     * @return common directory of discarded files, or {@code null} if none
+     */
+    Path discardAllFiles() {
+        Path base = null;
+        for (FileSet release : filesetForRelease.values()) {
+            base = release.discardAllFiles(base);
+        }
+        filesetForRelease.clear();
+        return base;
+    }
+
+    /**
+     * Removes all empty file sets 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}, then this method ensures that at least one file set
+     * remains even if that file set is empty.
+     *
+     * @param skipIfEmpty value of {@link AbstractJarMojo#skipIfEmpty}
+     */
+    public void prune(final boolean skipIfEmpty) {
+        FileSet keep = (skipIfEmpty || isEmpty())
+                ? null
+                : filesetForRelease.firstEntry().getValue();
+        filesetForRelease.values().removeIf((fs) -> fs.files.isEmpty());
+        Iterator<Map.Entry<Runtime.Version, FileSet>> it =
+                filesetForRelease.entrySet().iterator();
+        if (it.hasNext()) {
+            Map.Entry<Runtime.Version, FileSet> first = it.next();
+            if (first.getKey() == null) {
+                return; // Already contains an entry for the base version, nothing to do.
+            }
+            keep = first.getValue();
+            it.remove();
+        }
+        if (keep != null) {
+            filesetForRelease.put(null, keep);
+        }
+    }
+
+    /**
+     * {@return whether this archive has nothing to archive}
+     * This method can return {@code false} even when there is zero file to archive.
+     * It can happen if {@link AbstractJarMojo#skipIfEmpty} is {@code false}. In such case, the
+     * "empty" <abbr>JAR</abbr> file will still contain at {@code META-INF/MANIFEST.MF} file.
+     *
+     * <h4>Prerequisites</h4>
+     * The {@link #prune(boolean)} method should be invoked before this method for accurate result.
+     */
+    public boolean isEmpty() {
+        return filesetForRelease.isEmpty();
+    }
+
+    /**
+     * Checks whether the <abbr>JAR</abbr> file already exists and can be reused.
+     * This method verifies that the <abbr>JAR</abbr> file contains all the files to archive,
+     * contains no extra file, and no file to archive is newer than the <abbr>JAR</abbr> file.
+     *
+     * <p>This method can be invoked only once.
+     * If invoked more often, it returns {@code false} on all subsequent invocations.</p>
+     *
+     * @return whether the <abbr>JAR</abbr> file already exists and can be reused
+     */
+    public boolean isUpToDateJAR() {
+        final TimestampCheck tc = existingJAR;
+        if (tc == null) {
+            return false;
+        }
+        existingJAR = null; // Let GC do its job.
+        return tc.isUpToDateJAR(filesetForRelease.values());
+    }
+
+    /**
+     * Returns an initially empty set of files or directories for the specified target Java release.
+     *
+     * @param directory the base directory of the files to archive
+     * @param version the target Java release, or {@code null} for the base version
+     * @return container where to declare files and directories to archive
+     */
+    FileSet newTargetRelease(Path directory, Runtime.Version version) {
+        return filesetForRelease.computeIfAbsent(version, (key) -> new FileSet(directory));
+    }
+
+    /**
+     * Sets the {@code --main-class} option to the value of the {@code Main-Class} entry of the given manifest.
+     * As an extension, this method accepts the {@code module/classname} syntax (a syntax already used in some
+     * Java tools). If a module is specified, the main class is kept only if the module match. The intent is to
+     * allow users to specify on which module the main class applies when they use plugin configuration.
+     *
+     * <p>This method may modify the {@code content} manifest. Caller must ensure that the given manifest
+     * is not a shared instance. This method returns whether a change has actually been done.</p>
+     *
+     * @param content combination of existing {@code MANIFEST.MF} and manifest inferred from configuration, or null
+     * @return whether the given manifest has been modified by this method
+     */
+    boolean setMainClass(Manifest content) {
+        if (content == null || mainClass != null) {
+            return false;
+        }
+        // We need to remove the attribute, otherwise it will conflict with `--main-class`.
+        mainClass = (String) content.getMainAttributes().remove(Attributes.Name.MAIN_CLASS);
+        if (mainClass != null) {
+            int s = mainClass.indexOf('/');
+            if (s >= 0) {
+                if (mainClass.substring(0, s).strip().equals(moduleName)) {
+                    mainClass = mainClass.substring(s + 1).strip();
+                } else {
+                    mainClass = null; // Main class is defined for another module.
+                }
+            }
+        }
+        return mainClass != null;
+    }
+
+    /**
+     * Sets the {@code --manifest} option to the given value if that option was not already set.
+     *
+     * @param file path to the manifest file
+     * @param force whether to set the manifest even if already set
+     * @return whether the manifest has been set
+     */
+    boolean setManifest(Path file, boolean force) {
+        if (manifest == null || force) {
+            manifest = file;
+            return true;
+        }
+        return false;
+    }
+
+    /**
+     * Merges the manifest of this module with the manifest specified in plugin configuration.
+     * If both {@code file} and {@code content} are non-null, then {@code content} must be the
+     * result of reading {@code file}.
+     *
+     * <p>This method never modifies the given {@code content} object. If manifest are merged,
+     * a new {@link Manifest} instance is created. Therefore, caller can check whether this
+     * method returned a new instance as a way to recognize that a merge occurred.</p>
+     *
+     * <p>If a merge occurs, the content specified to {@link #setManifest(Path)} has precedence.
+     * It should be the {@code target/classes/META-INF/MANIFEST.MF} file (or modular equivalent).</p>
+     *
+     * @param  file     an additional manifest file, or {@code null}
+     * @param  content  the content of {@code file}, or a standalone manifest produced at runtime
+     * @return the merged manifest as a new instance if some changes were necessary
+     * @throws IOException if an error occurred while reading a manifest file
+     */
+    Manifest mergeManifest(Path file, Manifest content) throws IOException {
+        if (manifest == null) {
+            manifest = file;
+        } else if (file != null && Files.isSameFile(file, manifest)) {
+            // Nothing to merge because of the constraint that `content` must be the content of `file`.
+        } else {
+            try (InputStream in = Files.newInputStream(manifest)) {
+                // No need to wrap in `BufferedInputStream`.
+                if (content != null) {
+                    content = new Manifest(content);
+                    content.read(in);
+                } else {
+                    content = new Manifest(in);
+                }
+            }
+        }
+        return content;
+    }
+
+    /**
+     * Adds to the given list the arguments to provide to the "jar" tool for each version.
+     * Elements added to the list must be instances of {@link String} or {@link Path}.
+     * Callers should have added the following options (if applicable) before to invoke this method:
+     *
+     * <ul>
+     *   <li>{@code --create}</li>
+     *   <li>{@code --no-compress}</li>
+     *   <li>{@code --date} followed by the output time stamp</li>
+     *   <li>{@code --module-version} followed by module version</li>
+     *   <li>{@code --hash-modules} followed by patters of module names</li>
+     *   <li>{@code --module-path} followed by module path</li>
+     * </ul>
+     *
+     * This method adds the following options:
+     *
+     * <ul>
+     *   <li>{@code --file} followed by the path to the <abbr>JAR</abbr> file</li>
+     *   <li>{@code --manifest} followed by path to the manifest file</li>
+     *   <li>{@code --main-class} followed by fully qualified name class</li>
+     *   <li>{@code --release} followed by Java target release</li>
+     *   <li>{@code -C} followed by directory</li>
+     *   <li>files or directories to archive</li>
+     * </ul>
+     *
+     * @param addTo the list where to add the arguments as {@link String} or {@link Path} instances
+     */
+    void arguments(final List<Object> addTo) {
+        addTo.add("--file");
+        addTo.add(jarFile);
+        if (manifest != null) {
+            addTo.add("--manifest");
+            addTo.add(manifest);
+        }
+        if (mainClass != null) {
+            addTo.add("--main-class");
+            addTo.add(mainClass);
+        }
+        if (mavenFiles != null) {
+            addTo.add("-C");
+            addTo.addAll(mavenFiles);
+        }
+        for (Map.Entry<Runtime.Version, FileSet> entry : filesetForRelease.entrySet()) {
+            entry.getValue().arguments(addTo, entry.getKey());
+        }
+    }
+
+    /**
+     * Adds to the given list the arguments to provide to the "jar" tool for validating the <abbr>JAR</abbr> file.
+     * The file is validated only if requested or, in automatic mode, if the validation was not done implicitly at
+     * <abbr>JAR</abbr> creation time. Implicit validation happens if some {@code --release} options were used.
+     * If {@code true}, this method adds the following options:
+     *
+     * <ul>
+     *   <li>{@code --validate} operation mode</li>
+     *   <li>{@code --file} followed by the path to the <abbr>JAR</abbr> file</li>
+     * </ul>
+     *
+     * @param  validate whether to validate, or {@code null} for automatic based on heuristic rules
+     * @param  addTo the list to add the arguments as {@link String} or {@link Path} instances to
+     * @return whether a validation should be run
+     */
+    boolean validate(final Boolean validate, final List<Object> addTo) {
+        boolean effective;
+        if (validate != null) {
+            effective = validate;
+        } else {
+            // If at least one --release option was used, then validation was implicit.
+            effective = !filesetForRelease.keySet().stream().anyMatch(Objects::nonNull);
+        }
+        if (effective) {
+            addTo.add("--validate");
+            addTo.add("--file");
+            addTo.add(jarFile);
+        }
+        return effective;
+    }
+
+    /**
+     * Dumps the tool options together with the list of files into a debug file.
+     * This is invoked in case of compilation failure, or if debug is enabled.
+     * The arguments can be separated by spaces or by new line characters.

Review Comment:
   A line separator is a white space according Java but not according Unicode (if I remember right).



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3923470413


##########
src/main/java/org/apache/maven/plugins/jar/FileCollector.java:
##########
@@ -0,0 +1,541 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.PathMatcher;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Deque;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.services.PathMatcherFactory;
+
+/**
+ * Dispatch the files from the output directory into the <abbr>JAR</abbr> files to create.
+ * Instead of just archiving as-is the content of the output directory, this class separates
+ * the following subdirectories to the options listed below:
+ *
+ * <ul>
+ *   <li>The {@code META-INF/MANIFEST.MF} file will be given to the {@code --manifest} option.</li>
+ *   <li>Files in the following directories will be given to the {@code --release} option:
+ *     <ul>
+ *       <li>{@code META-INF/versions/}</li>
+ *       <li>{@code META-INF/versions-modular/<module>/}</li>
+ *       <li>{@code <module>/META-INF/versions/}</li>
+ *     </ul>
+ *   </li>
+ * </ul>
+ *
+ * The reason for using the options is that they allow the {@code jar} tool to perform additional verifications.
+ * For example, when using the {@code --release} option, {@code jar} verifies the <abbr>API</abbr> compatibility.
+ */
+final class FileCollector extends SimpleFileVisitor<Path> {
+    /**
+     * The file to check for deciding whether the <abbr>JAR</abbr> is modular.
+     */
+    static final String MODULE_DESCRIPTOR_FILE_NAME = "module-info.class";
+
+    /**
+     * The {@value} directory.
+     * This is part of <abbr>JAR</abbr> file specification.
+     */
+    private static final String VERSIONS = "versions";
+
+    /**
+     * The {@value} directory.
+     * This is Maven-specific.
+     */
+    private static final String VERSIONS_MODULAR = "versions-modular";
+
+    /**
+     * Context (logger, configuration) in which the <abbr>JAR</abbr> file are created.
+     */
+    private final ToolExecutor context;
+
+    /**
+     * Whether to detect multi-release <abbr>JAR</abbr> files.
+     * The default value is {@code true}.
+     *
+     * @see AbstractJarMojo#detectMultiReleaseJar
+     */
+    private final boolean detectMultiReleaseJar;
+
+    /**
+     * The root directory to traverse. It will be used for temporarily moving excluded files.
+     */
+    private final Path rootDirectory;
+
+    /**
+     * Combination of includes and excludes path matcher applied on files.
+     */
+    @Nonnull
+    private final PathMatcher fileMatcher;
+
+    /**
+     * Combination of includes and excludes path matcher applied on directories.
+     */
+    @Nonnull
+    private final PathMatcher directoryMatcher;
+
+    /**
+     * Files to exclude. These files will be moved to a temporary location
+     * for allowing {@link ToolExecutor} to specify whole directories to the {@code jar} tool.
+     * Specifying whole directories is preferable to enumerating the files because otherwise,
+     * the generated <abbr>JAR</abbr> file contains only entries for the files and is missing
+     * entries for the directories.
+     *
+     * <p>This field is {@code null} if it is not possible to have any excluded file
+     * (because there is no include/exclude filters).</p>
+     */
+    @Nullable
+    private final List<Path> excludedFiles;
+
+    /**
+     * Directories to exclude. This field serves the same purpose as {@link #excludedFiles},
+     * but where the sources a directories instead of files.
+     */
+    @Nullable
+    private final List<Path> excludedDirectories;
+
+    /**
+     * Files found in the output directory when package hierarchy is used.
+     * At most one of {@code packageHierarchy} and {@link #moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Archive packageHierarchy;
+
+    /**
+     * Files found in the output directory when module hierarchy is used. Keys are module names.
+     * At most one of {@link #packageHierarchy} and {@code moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Map<String, Archive> moduleHierarchy;
+
+    /**
+     * The current module being archived. This field is updated every times that {@code FileCollector}
+     * visits a new module directory.
+     */
+    @Nonnull
+    private Archive currentModule;
+
+    /**
+     * The module and target Java release currently being scanned. This field is updated every times that
+     * {@code FileCollector} visits a new module directory or in a new target Java release for a given module.
+     */
+    @Nonnull
+    private Archive.FileSet currentFilesToArchive;
+
+    /**
+     * The current target Java release, or {@code null} if none.
+     */
+    @Nullable
+    private Runtime.Version currentTargetVersion;
+
+    /**
+     * Identification of the kinds of directories being traversed.
+     * The length of this list is the depth in the directory hierarchy.
+     * The last element identifies the type of the current directory.
+     */
+    private final Deque<DirectoryRole> directoryRoles;
+
+    /**
+     * Whether to check when a file is the {@code MANIFEST.MF} file.
+     * This is allowed only when scanning the content of a {@code META-INF} directory.
+     */
+    private boolean checkForManifest;
+
+    /**
+     * Creates a new file collector.
+     *
+     * @param mojo the <abbr>MOJO</abbr> from which to get the configuration
+     * @param context context (logger, configuration) in which the <abbr>JAR</abbr> file are created
+     * @param directory the base directory of the files to archive
+     */
+    FileCollector(AbstractJarMojo mojo, ToolExecutor context, Path directory, PathMatcherFactory matcherFactory) {
+        this.context = context;
+        rootDirectory = directory;
+        detectMultiReleaseJar = mojo.detectMultiReleaseJar;
+        directoryRoles = new ArrayDeque<>();
+        fileMatcher = matcherFactory.createPathMatcher(directory, mojo.getIncludes(), mojo.getExcludes(), false);
+        directoryMatcher = matcherFactory.deriveDirectoryMatcher(fileMatcher);
+        if (matcherFactory.isIncludesAll(fileMatcher) && matcherFactory.isIncludesAll(directoryMatcher)) {
+            excludedFiles = null;
+            excludedDirectories = null;
+        } else {
+            excludedFiles = new ArrayList<>();
+            excludedDirectories = new ArrayList<>();
+        }
+        packageHierarchy = context.newArchive(null, null, directory);
+        moduleHierarchy = new LinkedHashMap<>();
+        resetToPackageHierarchy();
+    }
+
+    /**
+     * Resets this {@code FileCollector} to the state where a package hierarchy is presumed.
+     */
+    private void resetToPackageHierarchy() {
+        currentModule = packageHierarchy;
+        currentFilesToArchive = currentModule.baseRelease();
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a module.
+     * For an output generated by {@code javac} from a module source hierarchy,
+     * the directory name is guaranteed to be the module name.

Review Comment:
   Done.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3921556978


##########
src/main/java/org/apache/maven/plugins/jar/AbstractJarMojo.java:
##########
@@ -140,24 +144,52 @@ public abstract class AbstractJarMojo implements org.apache.maven.api.plugin.Moj
      * Timestamp for reproducible output archive entries.
      * This is either formatted as ISO 8601 extended offset date-time
      * (e.g. in UTC such as '2011-12-03T10:15:30Z' or with an offset '2019-10-05T20:37:42+06:00'),
-     * or as an integer representing seconds since the epoch
-     * (like <a href="https://reproducible-builds.org/docs/source-date-epoch/">SOURCE_DATE_EPOCH</a>).
+     * or as an integer representing seconds since the Java epoch (January 1st, 1970).
+     * If not configured or disabled,
+     * the <a href="https://reproducible-builds.org/docs/source-date-epoch/">SOURCE_DATE_EPOCH</a>
+     * environment variable is used as a fallback value,
+     * to ease forcing Reproducible Build externally when the build has not enabled it natively in <abbr>POM</abbr>.

Review Comment:
   Added `title` attribute for making `<abbr>` more useful.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3949390481


##########
src/test/java/org/apache/maven/plugins/jar/ArchiveTest.java:
##########
@@ -0,0 +1,257 @@
+/*
+ * 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.jar;
+
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Unit tests for {@link Archive}, focused on the two behaviours that are otherwise only
+ * exercised by integration tests whose outcome depends on the (unspecified) filesystem
+ * directory-iteration order, and therefore pass on some platforms while failing on others.
+ */
+class ArchiveTest {
+
+    /**
+     * Creates an {@code Archive} suitable for a unit test. {@code forceCreation = true} skips the
+     * existing-JAR timestamp check, so the (here {@code null}) logger is never dereferenced.
+     */
+    private static Archive archive(String moduleName, Runtime.Version version, Path directory) {
+        return new Archive(directory.resolve("out.jar"), moduleName, version, directory, true, null);
+    }
+
+    /**
+     * Creates a manifest with the main class attribute set to the given value.
+     *
+     * @param value value of the main class attribute
+     * @return a new manifest with the given attribute value
+     */
+    private static Manifest manifestWithMainClass(String value) {
+        Manifest m = new Manifest();
+        Attributes attributes = m.getMainAttributes();
+        attributes.put(Attributes.Name.MANIFEST_VERSION, "1.0");
+        attributes.put(Attributes.Name.MAIN_CLASS, value);
+        return m;
+    }
+
+    /**
+     * Returns the value of the main class attribute.
+     *
+     * @param m the manifest from which to get the value
+     * @return the main class attribute value, or {@code null} if none
+     */
+    private static Object mainClassOf(Manifest m) {
+        return m.getMainAttributes().get(Attributes.Name.MAIN_CLASS);
+    }
+
+    /**
+     * Verifies that {@link Archive#setMainClass(Manifest)} takes ownership for a module-qualified
+     * {@code "module/Class"} main class.
+     *
+     * The {@code "foo.bar/"} prefix in this test (the module name) is a Maven extension.
+     * The standard <abbr>JAR</abbr> specification accepts only the {@code "foo.MainFile"} class name.
+     */
+    @Test
+    void owningModuleClaimsMainClassAndRemovesItFromManifest() {
+        Archive owner = archive("foo.bar", null, Path.of("."));
+        Manifest m = manifestWithMainClass("foo.bar/foo.MainFile");
+        // The owner keeps the main class (emitted via --main-class) ...
+        assertTrue(owner.setMainClass(m));
+        // ... and the raw `module/Class` value is removed from the written manifest.
+        assertNull(mainClassOf(m));
+    }
+
+    /**
+     * Verifies that {@link Archive#setMainClass(Manifest)} does <em>not</em> take ownership of
+     * a module-qualified {@code "module/Class"} main class when the module name does not match.
+     * The {@code "foo.bar/"} prefix in this test (the module name) is a Maven extension.
+     * The standard <abbr>JAR</abbr> specification accepts only the {@code "foo.MainFile"} class name.
+     */
+    @Test
+    void nonOwningModuleRejectsMainClass() {
+        Archive nonOwner = archive("foo.bar.more", null, Path.of("."));
+        Manifest m = manifestWithMainClass("foo.bar/foo.MainFile");
+        assertFalse(nonOwner.setMainClass(m));
+        assertNull(mainClassOf(m));
+    }
+
+    /**
+     * Tests that which module keeps the main class does not depend on processing order.
+     * {@link ToolExecutor} gives each module a <em>copy</em> of the shared plugin manifest;
+     * this pins that the owning module (and only it) keeps the main class in either order,
+     * and that the shared manifest is never consumed.
+     */
+    @Test
+    void mainClassAssignmentIsIndependentOfModuleOrder() {
+        assertOwnership("foo.bar", "foo.bar.more", true); // owner processed first
+        assertOwnership("foo.bar.more", "foo.bar", false); // non-owner processed first
+    }
+
+    /**
+     * Helper method for {@link #mainClassAssignmentIsIndependentOfModuleOrder()}.
+     * Asserts that {@link Archive#setMainClass(Manifest)} returns {@code true}
+     * for the owner and {@code false} for the other module.
+     *
+     * <p>The {@code "foo.bar/"} prefix in this test (the module name) is a Maven extension.
+     * The standard <abbr>JAR</abbr> specification accepts only the {@code "foo.MainFile"} class name.
+     * This extension is used by the plugin for identifying in which <abbr>JAR</abbr> file to add this
+     * {@code Main-Class} manifest entry.</p>
+     */
+    private static void assertOwnership(String first, String second, boolean ownerIsFirst) {
+        final Path path = Path.of(".");
+        final Manifest shared = manifestWithMainClass("foo.bar/foo.MainFile");
+        final Manifest m1 = new Manifest(shared);
+        final Manifest m2 = new Manifest(shared);
+        assertEquals(ownerIsFirst, archive(first, null, path).setMainClass(m1));
+        assertEquals(!ownerIsFirst, archive(second, null, path).setMainClass(m2));
+        // Per-module copies must leave the shared plugin manifest untouched.
+        assertEquals("foo.bar/foo.MainFile", mainClassOf(shared));
+        assertNull(mainClassOf(m1));
+        assertNull(mainClassOf(m2));
+    }
+
+    /**
+     * Tests that {@code FileSet} association to target release is consistent regardless of creation order.
+     * Verifies that the base (version-less) release binds to the true {@code <module>} directory even
+     * when the {@link Archive} was first created from a {@code META-INF/versions-modular/<n>/<module>}
+     * directory (which happens when the file-tree walk visits the version directory first).
+     */
+    @Test
+    void baseReleaseBindingIsIndependentOfDirectoryOrder() {
+        final Path base = Path.of("classes", "foo.bar");
+        final Path v16 = Path.of("classes", "META-INF", "versions-modular", "16", "foo.bar");
+        final Runtime.Version r16 = Runtime.Version.parse("16");
+
+        // Version-directory first (the failing order): Archive seeded from v16, base registered later.
+        final Archive a = archive("foo.bar", r16, v16);
+        assertNotSame(a.newTargetRelease(v16, r16), a.newTargetRelease(base, null));
+        assertEquals(base, a.baseRelease().directory, "base must rebind to the version-less directory");
+
+        // Base-directory first: still correct.
+        final Archive b = archive("foo.bar", null, base);
+        assertNotSame(b.newTargetRelease(base, null), b.newTargetRelease(v16, r16));
+        assertEquals(base, b.baseRelease().directory);
+    }
+
+    /**
+     * Ensures that all path are relative.
+     *
+     * <h4>Historical note</h4>
+     * In our tests, it seems that the first <abbr>JAR</abbr> entry after the {@code -C} option
+     * must be relative, and only that file. Furthermore, it seems that this file must be the
+     * shortest. We tried to apply this heuristic rules in a branch, but it does not save a lot

Review Comment:
   file name. Done.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3949185167


##########
src/main/java/org/apache/maven/plugins/jar/FileCollector.java:
##########
@@ -0,0 +1,542 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.PathMatcher;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Deque;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.services.PathMatcherFactory;
+
+/**
+ * Dispatch the files from the output directory into the <abbr>JAR</abbr> files to create.
+ * Instead of just archiving as-is the content of the output directory, this class separates
+ * the following subdirectories to the options listed below:
+ *
+ * <ul>
+ *   <li>The {@code META-INF/MANIFEST.MF} file will be given to the {@code --manifest} option.</li>
+ *   <li>Files in the following directories will be given to the {@code --release} option:
+ *     <ul>
+ *       <li>{@code META-INF/versions/}</li>
+ *       <li>{@code META-INF/versions-modular/<module>/}</li>
+ *       <li>{@code <module>/META-INF/versions/}</li>
+ *     </ul>
+ *   </li>
+ * </ul>
+ *
+ * The reason for using the {@code --release} and {@code --manifest} options instead of adding explicitly
+ * the entries is because the options allow the {@code jar} tool to perform additional verifications.
+ * For example, when using the {@code --release} option, {@code jar} verifies the <abbr>API</abbr> compatibility.
+ */
+final class FileCollector extends SimpleFileVisitor<Path> {
+    /**
+     * The file to check for deciding whether the <abbr>JAR</abbr> is modular.
+     */
+    static final String MODULE_DESCRIPTOR_FILE_NAME = "module-info.class";
+
+    /**
+     * The {@value} directory.
+     * This is part of <abbr>JAR</abbr> file specification.
+     */
+    private static final String VERSIONS = "versions";
+
+    /**
+     * The {@value} directory.
+     * This is Maven-specific.
+     */
+    private static final String VERSIONS_MODULAR = "versions-modular";
+
+    /**
+     * Context (logger, configuration) in which the <abbr>JAR</abbr> file are created.
+     */
+    private final ToolExecutor context;
+
+    /**
+     * Whether to detect multi-release <abbr>JAR</abbr> files.
+     * The default value is {@code true}.
+     *
+     * @see AbstractJarMojo#detectMultiReleaseJar
+     */
+    private final boolean detectMultiReleaseJar;
+
+    /**
+     * The root directory to traverse. It will be used for temporarily moving excluded files.
+     */
+    private final Path rootDirectory;
+
+    /**
+     * Combination of includes and excludes path matcher applied on files.
+     */
+    @Nonnull
+    private final PathMatcher fileMatcher;
+
+    /**
+     * Combination of includes and excludes path matcher applied on directories.
+     */
+    @Nonnull
+    private final PathMatcher directoryMatcher;
+
+    /**
+     * Files to exclude. These files will be moved to a temporary location
+     * for allowing {@link ToolExecutor} to specify whole directories to the {@code jar} tool.
+     * Specifying whole directories is preferable to enumerating the files because otherwise,
+     * the generated <abbr>JAR</abbr> file contains only entries for the files and is missing
+     * entries for the directories.
+     *
+     * <p>This field is {@code null} if it is not possible to have any excluded file
+     * (because there is no include/exclude filters).</p>
+     */
+    @Nullable
+    private final List<Path> excludedFiles;
+
+    /**
+     * Directories to exclude. This field serves the same purpose as {@link #excludedFiles},
+     * but where the sources a directories instead of files.

Review Comment:
   Done.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "seregamorph (via GitHub)" <gi...@apache.org>.
seregamorph commented on PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#issuecomment-5339050198

   > If that proves to be true and we can't find a workaround, that's a blocker. Reproducible builds are the more important feature.
   
   💯 , this is very critical to have proper reproducible builds


-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "seregamorph (via GitHub)" <gi...@apache.org>.
seregamorph commented on PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#issuecomment-5339178857

   I'd duplicate my message from the mailing list there, for history.
   The current implementation of the plugin does not include the directory entries in the zip archive of JAR file.
   As a result, this breaks spring applications component scan which relies on it.
   The behavior should be preserved without any customization of the plugin configuration.
   This is a critical blocker.


-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3891877305


##########
src/main/java/org/apache/maven/plugins/jar/AbstractJarMojo.java:
##########
@@ -207,167 +205,208 @@ protected final Log getLog() {
     protected abstract String getType();
 
     /**
-     * Returns the JAR file to generate, based on an optional classifier.
+     * {@return the scope of dependencies}
+     * It should be {@link PathScope#MAIN_COMPILE} or {@link PathScope#TEST_COMPILE}.
+     * Note that we use compile scope rather than runtime scope because dependencies
+     * cannot appear in {@code requires} statement if they didn't had compile scope.
+     */
+    protected abstract PathScope getDependencyScope();
+
+    /**
+     * {@return the JAR tool to use for archiving the code}
      *
-     * @param basedir the output directory
-     * @param resultFinalName the name of the JAR file
-     * @param classifier an optional classifier
-     * @return the file to generate
+     * @throws MojoException if no JAR tool was found
+     *
+     * @since 4.0.0-beta-2
      */
-    protected Path getJarFile(Path basedir, String resultFinalName, String classifier) {
-        Objects.requireNonNull(basedir, "basedir is not allowed to be null");
-        Objects.requireNonNull(resultFinalName, "finalName is not allowed to be null");
-        String fileName = resultFinalName + (hasClassifier(classifier) ? '-' + classifier : "") + ".jar";
-        return basedir.resolve(fileName);
+    protected ToolProvider getJarTool() throws MojoException {
+        return ToolProvider.findFirst(toolId).orElseThrow(() -> new MojoException("No such \"" + toolId + "\" tool."));
     }
 
     /**
-     * Generates the JAR.
+     * Returns the output time stamp or, as a fallback, the {@code SOURCE_DATE_EPOCH} environment variable.
+     * If the time stamp is expressed in seconds, it is converted to ISO 8601 format. Otherwise it is returned as-is.
      *
-     * @return the path to the created archive file
-     * @throws MojoException in case of an error
+     * @return the time stamp in presumed ISO 8601 format, or {@code null} if none
+     *
+     * @since 4.0.0-beta-2
      */
-    public Path createArchive() throws MojoException {
-        Path basedir = outputDirectory != null
-                ? outputDirectory
-                : Path.of(project.getBuild().getDirectory());
-        String resultFinalName =
-                finalName != null ? finalName : project.getBuild().getFinalName();
-        Path jarFile = getJarFile(basedir, resultFinalName, getClassifier());
-
-        FileSetManager fileSetManager = new FileSetManager();
-        FileSet jarContentFileSet = new FileSet();
-        jarContentFileSet.setDirectory(getClassesDirectory().toAbsolutePath().toString());
-        jarContentFileSet.setIncludes(Arrays.asList(getIncludes()));
-        jarContentFileSet.setExcludes(Arrays.asList(getExcludes()));
-
-        String[] includedFiles = fileSetManager.getIncludedFiles(jarContentFileSet);
-
-        if (detectMultiReleaseJar
-                && Arrays.stream(includedFiles)
-                        .anyMatch(
-                                p -> p.startsWith("META-INF" + File.separatorChar + "versions" + File.separatorChar))) {
-            getLog().debug("Adding 'Multi-Release: true' manifest entry.");
-            archive.addManifestEntry(Attributes.Name.MULTI_RELEASE.toString(), "true");
+    protected String getOutputTimestamp() {
+        String time = nullIfAbsent(outputTimestamp);
+        if (time == null) {
+            time = nullIfAbsent(System.getenv("SOURCE_DATE_EPOCH"));
+            if (time == null) {
+                return null;
+            }
         }
+        if (Runtime.version().feature() < ToolExecutor.JDK_SUPPORT_DATE) {
+            log.warn("Reproducible build requires Java " + ToolExecutor.JDK_SUPPORT_DATE + " or later.");
+            return null;
+        }
+        for (int i = time.length(); --i >= 0; ) {
+            char c = time.charAt(i);
+            if ((c < '0' || c > '9') && (i != 0 || c != '-')) {
+                return time;
+            }
+        }
+        return Instant.ofEpochSecond(Long.parseLong(time)).toString();
+    }
 
-        // May give false positives if the files is named as module descriptor
-        // but is not in the root of the archive or in the versioned area
-        // (and hence not actually a module descriptor).
-        // That is fine since the modular Jar archiver will gracefully
-        // handle such case.
-        // And also such case is unlikely to happen as file ending
-        // with "module-info.class" is unlikely to be included in Jar file
-        // unless it is a module descriptor.
-        boolean containsModuleDescriptor =
-                Arrays.stream(includedFiles).anyMatch(p -> p.endsWith(MODULE_DESCRIPTOR_FILE_NAME));
-
-        String archiverName = containsModuleDescriptor ? "mjar" : "jar";
+    /**
+     * {@return the patterns of files to include, or an empty list if no include pattern was specified}
+     */
+    protected List<String> getIncludes() {
+        return asList(includes);
+    }
 
-        MavenArchiver archiver = new MavenArchiver();
-        archiver.setCreatedBy("Maven JAR Plugin", "org.apache.maven.plugins", "maven-jar-plugin");
-        archiver.setBuildJdkSpecDefaultEntry(archive.getManifest().isAddBuildEnvironmentEntries());
-        archiver.setArchiver((JarArchiver) archivers.get(archiverName));
-        archiver.setOutputFile(jarFile.toFile());
+    /**
+     * {@return the patterns of files to exclude, or an empty list if no exclude pattern was specified}
+     */
+    protected List<String> getExcludes() {
+        return asList(excludes);
+    }
 
-        // configure for Reproducible Builds based on outputTimestamp value
-        archiver.configureReproducibleBuild(outputTimestamp);
+    /**
+     * Returns the output directory and ensures that the directory exists.
+     * The returned directory will be either {@link #outputDirectory} if non-null,
+     * or {@link org.apache.maven.api.model.Build#getDirectory()} otherwise.
+     *
+     * <p>The directory is usually {@code target} and should always exist since it is usually the output
+     * of the compiler plugin. If nevertheless the directory does not exist, then this method creates it.
+     * However, this method does not try to create the parent directory, which should be the Maven sub-project.</p>
+     *
+     * @return the directory containing the generated <abbr>JAR</abbr> files.
+     * @throws IOException if the output directory did not existed and could not be created
+     */
+    protected Path getOutputDirectory() throws IOException {
+        Path dir = outputDirectory;
+        if (dir == null) {
+            dir = Path.of(project.getBuild().getDirectory());
+        }
+        if (Files.notExists(dir)) {
+            dir = Files.createDirectory(dir);
+        }
+        return dir;
+    }
 
-        archive.setForced(forceCreation);
+    /**
+     * Returns the given elements as a list if non-null.
+     *
+     * @param elements the elements, or {@code null}
+     * @return the elements as a list, or {@code null} if the given array was null
+     */
+    private static List<String> asList(String[] elements) {
+        return (elements == null) ? List.of() : Arrays.asList(elements);
+    }
 
-        try {
-            Path contentDirectory = getClassesDirectory();
-            if (!Files.exists(contentDirectory)) {
-                if (!forceCreation) {
-                    getLog().warn("JAR will be empty - no content was marked for inclusion!");
-                }
-            } else {
-                archiver.getArchiver().addDirectory(contentDirectory.toFile(), getIncludes(), getExcludes());
+    /**
+     * Generates the <abbr>JAR</abbr> files.
+     * Map keys are module names or {@code null} if the project does not use module hierarchy.
+     * Values are (<var>type</var>, <var>path</var>) pairs associated with each module where
+     * <var>type</var> is {@code "pom"}, {@code "jar"} or {@code "test-jar"} and <var>path</var>
+     * is the path to the <abbr>POM</abbr> or <abbr>JAR</abbr> file.
+     *
+     * <p>Note that a null key does not necessarily means that the <abbr>JAR</abbr> is not modular.
+     * It only means that the project was not compiled with module hierarchy,
+     * i.e. {@code target/classes/} subdirectories having module names.
+     * A project can be compiled with package hierarchy and still be modular.</p>
+     *
+     * @return the paths to the created archive files
+     * @throws IOException if an error occurred while walking the file tree
+     * @throws MojoException if an error occurred while writing a <abbr>JAR</abbr> file
+     */
+    public Map<String, Map<String, Path>> createArchives() throws IOException, MojoException {
+        final Path classesDirectory = getClassesDirectory();
+        final boolean notExists = Files.notExists(classesDirectory);
+        if (notExists) {
+            if (forceCreation) {
+                log.warn("No JAR created because no content was marked for inclusion.");
+            }
+            if (skipIfEmpty) {
+                log.info(String.format("Skipping packaging of the %s.", getType()));
+                return Map.of();
             }
-
-            archiver.createArchive(session, project, archive);
-
-            return jarFile;
-        } catch (Exception e) {
-            // TODO: improve error handling
-            throw new MojoException("Error assembling JAR", e);
         }
+        archive.setForced(forceCreation);
+        // TODO: we want a null manifest if there is no <archive> configuration.
+        final var archiver = new MavenArchiver();

Review Comment:
   The choice to use it or not is not always clear. It tend to use it when the type is clearly redundant: already one the same line, and even sometime in the variable name.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3892008061


##########
src/main/java/org/apache/maven/plugins/jar/FileCollector.java:
##########
@@ -0,0 +1,496 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.PathMatcher;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayDeque;
+import java.util.Deque;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.services.PathMatcherFactory;
+
+/**
+ * Dispatch the files in the output directory into the <abbr>JAR</abbr> files to create.
+ * Instead of just archiving as-is the content of the output directory, this class separates
+ * the following subdirectories to the options listed below:
+ *
+ * <ul>
+ *   <li>The {@code META-INF/MANIFEST.MF} file will be given to the {@code --manifest} option.</li>
+ *   <li>Files in the following directories will be given to the {@code --release} option:
+ *     <ul>
+ *       <li>{@code META-INF/versions/}</li>
+ *       <li>{@code META-INF/versions-modular/<module>/}</li>
+ *       <li>{@code <module>/META-INF/versions/}</li>
+ *     </ul>
+ *   </li>
+ * </ul>
+ *
+ * The reason for using the options is that they allow the {@code jar} tool to perform additional verifications.
+ * For example, when using the {@code --release} option, {@code jar} verifies the <abbr>API</abbr> compatibility.
+ */
+final class FileCollector extends SimpleFileVisitor<Path> {
+    /**
+     * The file to check for deciding whether the <abbr>JAR</abbr> is modular.
+     */
+    static final String MODULE_DESCRIPTOR_FILE_NAME = "module-info.class";
+
+    /**
+     * The {@value} directory.
+     * This is part of <abbr>JAR</abbr> file specification.
+     */
+    private static final String VERSIONS = "versions";
+
+    /**
+     * The {@value} directory.
+     * This is Maven-specific.
+     */
+    private static final String VERSIONS_MODULAR = "versions-modular";
+
+    /**
+     * Context (logger, configuration) in which the <abbr>JAR</abbr> file are created.
+     */
+    private final ToolExecutor context;
+
+    /**
+     * Whether to detect multi-release <abbr>JAR</abbr> files.
+     * The default value is {@code true}.
+     *
+     * @see AbstractJarMojo#detectMultiReleaseJar
+     */
+    private final boolean detectMultiReleaseJar;
+
+    /**
+     * Combination of includes and excludes path matcher applied on files.
+     */
+    @Nonnull
+    private final PathMatcher fileMatcher;
+
+    /**
+     * Combination of includes and excludes path matcher applied on directories.
+     */
+    @Nonnull
+    private final PathMatcher directoryMatcher;
+
+    /**
+     * Whether the matchers accept all files and there is no need to sort the files.
+     * In such case, we can declare whole directories to the {@code jar} tool instead
+     * of scanning the directory tree ourselves.
+     */
+    private final boolean addDirectories;
+
+    /**
+     * Files found in the output directory when package hierarchy is used.
+     * At most one of {@code packageHierarchy} and {@link #moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Archive packageHierarchy;
+
+    /**
+     * Files found in the output directory when module hierarchy is used. Keys are module names.
+     * At most one of {@link #packageHierarchy} and {@code moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Map<String, Archive> moduleHierarchy;
+
+    /**
+     * The current module being archived. This field is updated every times that {@code FileCollector}
+     * enters in a new module directory.
+     */
+    @Nonnull
+    private Archive currentModule;
+
+    /**
+     * The module and target Java release currently being scanned. This field is updated every times that
+     * {@code FileCollector} enters in a new module directory or in a new target Java release for a given module.
+     */
+    @Nonnull
+    private Archive.FileSet currentFilesToArchive;
+
+    /**
+     * The current target Java release, or {@code null} if none.
+     */
+    @Nullable
+    private Runtime.Version currentTargetVersion;
+
+    /**
+     * Identification of the kinds of directories being traversed.
+     * The length of this list is the depth in the directory hierarchy.
+     * The last element identifies the type of the current directory.
+     */
+    private final Deque<DirectoryRole> directoryRoles;
+
+    /**
+     * Whether to check when a file is the {@code MANIFEST.MF} file.
+     * This is allowed only when scanning the content of a {@code META-INF} directory.
+     */
+    private boolean checkForManifest;
+
+    /**
+     * Creates a new file collector.
+     *
+     * @param mojo the <abbr>MOJO</abbr> from which to get the configuration
+     * @param context context (logger, configuration) in which the <abbr>JAR</abbr> file are created
+     * @param directory the base directory of the files to archive
+     */
+    FileCollector(AbstractJarMojo mojo, ToolExecutor context, Path directory, PathMatcherFactory matcherFactory) {
+        this.context = context;
+        detectMultiReleaseJar = mojo.detectMultiReleaseJar;
+        directoryRoles = new ArrayDeque<>();
+        fileMatcher = matcherFactory.createPathMatcher(directory, mojo.getIncludes(), mojo.getExcludes(), false);
+        directoryMatcher = matcherFactory.deriveDirectoryMatcher(fileMatcher);
+        addDirectories = !context.isReproducible()
+                && matcherFactory.isIncludesAll(fileMatcher)
+                && matcherFactory.isIncludesAll(directoryMatcher);
+        packageHierarchy = context.newArchive(null, null, directory);
+        moduleHierarchy = new LinkedHashMap<>();
+        resetToPackageHierarchy();
+    }
+
+    /**
+     * Resets this {@code FileCollector} to the state where a package hierarchy is presumed.
+     */
+    private void resetToPackageHierarchy() {
+        currentModule = packageHierarchy;
+        currentFilesToArchive = currentModule.baseRelease();
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a module.
+     * For an output generated by {@code javac} from a module source hierarchy,
+     * the directory name is guaranteed to be the module name.
+     *
+     * @param directory a {@code "<module>"} or {@code "META-INF/versions-modular/<module>"} directory
+     */
+    private void enterModuleDirectory(final Path directory) {
+        String moduleName = directory.getFileName().toString();
+        currentModule = moduleHierarchy.computeIfAbsent(
+                moduleName, (name) -> context.newArchive(name, currentTargetVersion, directory));
+        currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a target Java version.
+     * The {@code useDirectly} argument tells whether the content of this directory will be specified directly
+     * as the content to add in the <abbr>JAR</abbr> file. This argument should be {@code false} when there is
+     * another directory level (the module names) to process before to add content.
+     *
+     * @param directory a {@code "META-INF/versions/<n>"} or {@code "META-INF/versions-modular/<n>"} directory
+     * @param useDirectly whether the directory is {@code "META-INF/versions/<n>"}
+     * @return whether to skip the directory because of invalid version number
+     */
+    private boolean enterVersionDirectory(final Path directory, final boolean useDirectly) {
+        try {
+            currentTargetVersion = Runtime.Version.parse(directory.getFileName().toString());
+        } catch (IllegalArgumentException e) {
+            context.warnInvalidVersion(directory, e);
+            return true;
+        }
+        if (useDirectly) {
+            currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+        }
+        return false;
+    }
+
+    /**
+     * Determines if the given directory should be scanned for files to archive.
+     * This method may also update {@link #currentFilesToArchive} if it detects
+     * that we are entering in a new module or a new target Java release.
+     *
+     * @param directory the directory which will be traversed
+     * @param attributes the directory's basic attributes
+     */
+    @Override
+    @SuppressWarnings("checkstyle:MissingSwitchDefault")
+    public FileVisitResult preVisitDirectory(final Path directory, final BasicFileAttributes attributes)
+            throws IOException {
+        DirectoryRole role;
+        if (directoryRoles.isEmpty()) {
+            role = DirectoryRole.ROOT;
+        } else {
+            if (!directoryMatcher.matches(directory)) {
+                return FileVisitResult.SKIP_SUBTREE;
+            }
+            checkForManifest = false;
+            role = directoryRoles.getLast();
+            switch (role) {
+                case ROOT:
+                    /*
+                     * Entering in any subdirectory of `target/classes` (or other directory to archive).
+                     * We need to handle `META-INF` and modules in a special way, and archive the rest.
+                     */
+                    if (directory.endsWith(MetadataFiles.META_INF)) {
+                        role = DirectoryRole.META_INF;
+                        checkForManifest = true;
+                    } else if (Files.isRegularFile(directory.resolve(MODULE_DESCRIPTOR_FILE_NAME))) {
+                        role = DirectoryRole.NAMED_MODULE;
+                        enterModuleDirectory(directory);
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case META_INF:
+                    /*
+                     * Entering in a subdirectory of `META-INF` or `<module>/META-INF`. We will need to handle
+                     * `MANIFEST.MF`, `versions` and `versions-modular` in a special way, and archive the rest.
+                     */
+                    if (detectMultiReleaseJar && directory.endsWith(VERSIONS)) {
+                        role = DirectoryRole.VERSIONS;
+                    } else if (directory.endsWith(VERSIONS_MODULAR)) {
+                        if (!detectMultiReleaseJar) {
+                            // Used asked for no multi-release JAR.
+                            return FileVisitResult.SKIP_SUBTREE;
+                        }
+                        role = DirectoryRole.VERSIONS_MODULAR;
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case VERSIONS:
+                    /*
+                     * Entering in a `META-INF/versions/<n>/` directory for a specific target Java release.
+                     * May also be a `<module>/META-INF/versions/<n>/` directory, even if the latter is not
+                     * the layout generated by Maven Compiler Plugin.
+                     */
+                    if (enterVersionDirectory(directory, true)) {
+                        // An error occurred while parsing the version number.
+                        return FileVisitResult.SKIP_SUBTREE;
+                    }
+                    role = DirectoryRole.RESOURCES;
+                    break;
+
+                case VERSIONS_MODULAR:
+                    /*
+                     * Entering in a `META-INF/versions-modular/<n>/` directory for a specific target Java release.
+                     * That directory contains all modules for the version.
+                     */
+                    resetToPackageHierarchy(); // No module in particular yet.
+                    if (enterVersionDirectory(directory, false)) {
+                        // An error occurred while parsing the version number.
+                        return FileVisitResult.SKIP_SUBTREE;
+                    }
+                    role = DirectoryRole.MODULES;
+                    break;
+
+                case MODULES:
+                    /*
+                     * Entering in a `META-INF/versions-modular/<n>/<module>` directory.
+                     */
+                    enterModuleDirectory(directory);
+                    role = DirectoryRole.NAMED_MODULE;
+                    break;
+
+                case NAMED_MODULE:
+                    /*
+                     * Entering in a `<module>` or `META-INF/versions-modular/<n>/<module>` subdirectory.
+                     * A module could have its own `META-INF` subdirectory, so we need to check again.
+                     */
+                    if (directory.endsWith(MetadataFiles.META_INF)) {
+                        role = DirectoryRole.META_INF;
+                        checkForManifest = true;
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+            }
+        }
+        /*
+         * Do not move this condition inside the `switch` block because `role` may have been modified.
+         * The `role` value is now the role of `directory`, not anymore the role of parent directory.
+         */
+        if (addDirectories && role == DirectoryRole.RESOURCES) {
+            currentFilesToArchive.add(directory, attributes, true);
+            /*
+             * Since we are skipping the whole directory, `postVisitDirectory(…)` will not be invoked.
+             * We must reset `currentFilesToArchive` and `currentTargetVersion` by an explicit call.
+             * This is important mostly after we added a whole `META-INF/versions/<n>` directory,
+             * otherwise base files visited afterwards (directory iteration order is unspecified)

Review Comment:
   Separated in two sentences.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "elharo (via GitHub)" <gi...@apache.org>.
elharo commented on PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#issuecomment-5395170442

   A different compiler version can easily choose to perform different optimizations; e.g. to unroll a loop or not, while remaining fully spec conformant. This produces different byte code, even when compiling for the same Java version. I'm not sure whether determining that two different versions of the byte code for a method produce the same output for the same inputs is equivalent to solving the halting problem, but it's certainly non-trivial and not something I want to rely on for reproducible builds.


-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#issuecomment-5395326768

   > A different compiler version can easily choose to perform different optimizations; e.g. to unroll a loop or not, while remaining fully spec conformant. 
   
   Yes, this is exactly why I think that strictly reproducible builds currently works only by chance. Doing semantically reproducible builds at the bytecode level would be challenging, but if we start with only the easy part (ignoring timestamp, compression and a few selected metadata such as `Created-By`), we have something working for the current state of the industry and we prepare the ground for more advanced comparisons in the future if the above-cited differences in bytecode are observed.


-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#issuecomment-5395103575

   Ok, I removed the _"on unspecified JDK"_ part. I think that the risk of controversy is almost certain.


-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3844265707


##########
src/main/java/org/apache/maven/plugins/jar/MetadataFiles.java:
##########
@@ -0,0 +1,250 @@
+/*
+ * 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.jar;
+
+import java.io.BufferedWriter;
+import java.io.Closeable;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Properties;
+import java.util.jar.Manifest;
+import java.util.stream.Collectors;
+
+import org.apache.maven.api.ProducedArtifact;
+import org.apache.maven.api.Project;
+import org.apache.maven.shared.archiver.MavenArchiveConfiguration;
+
+/**
+ * Temporary metadata files generated by Maven before inclusion in the archive.
+ * Those files are created in a temporary {@code META-INF} directory when first needed.
+ * Those files are deleted after the build, unless the build failed or Maven was run in verbose mode.
+ */
+final class MetadataFiles implements Closeable {
+    /**
+     * The {@value} directory.
+     * This is part of <abbr>JAR</abbr> file specification.
+     */
+    static final String META_INF = "META-INF";
+
+    /**
+     * The {@value} file.
+     * This is part of <abbr>JAR</abbr> file specification.
+     */
+    static final String MANIFEST = "MANIFEST.MF";
+
+    /**
+     * The subdirectory where to add Maven-specific files.
+     */
+    static final String MAVEN_DIR = "maven";
+
+    /**
+     * The project for which to write metadata files.
+     */
+    private final Project project;
+
+    /**
+     * The output directory (usually {@code ${baseDir}/target/}).
+     */
+    private final Path buildDir;
+
+    /**
+     * All files and directories in the order that they were created.
+     * The first element of this list shall be the root temporary directory created by this class.
+     */
+    private final List<Path> filesToDelete;
+
+    /**
+     * The <abbr>POM</abbr> file to attach to the artifact. This is initially the project <abbr>POM</abbr>,
+     * but will be replaced by a new file generated by {@link ForModule} if module hierarchy is used.
+     * That file may be copied verbatim in the {@code META-INF/maven/} directory of the <abbr>JAR</abbr>.
+     */
+    private Path attachedPOM;
+
+    /**
+     * Creates an initially empty set of temporary metadata files.
+     *
+     * @param project the project for which to write metadata files
+     * @param buildDir the (usually) {@code ${baseDir}/target/} directory
+     */
+    MetadataFiles(Project project, Path buildDir) {
+        this.project = project;
+        this.buildDir = buildDir;
+        filesToDelete = new ArrayList<>();
+        attachedPOM = project.getPomPath();
+    }
+
+    /**
+     * Derives a <abbr>POM</abbr> as the intersection of the given {@code model} and {@code archive}.
+     *
+     * @param context the tool executor which is generating all archives
+     * @param archive the archive for which to generate a <abbr>POM</abbr>
+     * @param manifest manifest to use for deriving project name, or {@code null} if none
+     * @throws IOException if an error occurred while reading the {@code module-info.class} file
+     *         or while writing the <abbr>POM</abbr> file
+     */
+    void deriveModulePOM(ToolExecutor context, Archive archive, Manifest manifest) throws IOException {
+        var pom = context.pomDerivation.new ForModule(archive, manifest);
+        pom.writeModulePOM();
+        attachedPOM = pom.pomFile;
+        archive.pomFile = pom.pomFile;
+    }
+
+    /**
+     * Adds the given manifest in a temporary file.
+     * The file will be deleted when {@link #close()} is invoked.
+     *
+     * @param manifest the manifest to write
+     * @return the temporary manifest file
+     * @throws IOException if an error occurred while writing the file
+     */
+    public Path addManifest(final Manifest manifest) throws IOException {
+        Path file = baseDirectory().resolve(MANIFEST);
+        try (OutputStream out = Files.newOutputStream(file)) {
+            filesToDelete.add(file);
+            manifest.write(out);
+        }
+        return file;
+    }
+
+    /**
+     * {@return the root temporary directory for the files created by this class}
+     * The directory is created the first time that this method is invoked.
+     *
+     * @throws IOException if an error occurred while creating the temporary directory
+     */
+    private Path baseDirectory() throws IOException {
+        if (filesToDelete.isEmpty()) {
+            filesToDelete.add(Files.createTempDirectory(buildDir, "classes-"));
+        }
+        return filesToDelete.get(0);
+    }
+
+    /**
+     * Creates a new directory and adds it to the list of files to delete after the build.
+     *
+     * @param dir the existing directory where to create a sub-directory
+     * @param path path to the subdirectory to create
+     * @return the new directory
+     * @throws IOException if an error occurred while creating the subdirectory
+     */
+    private Path createDirectories(Path dir, String... path) throws IOException {
+        for (String subdir : path) {
+            dir = Files.createDirectory(dir.resolve(subdir));
+            filesToDelete.add(dir);
+        }
+        return dir;
+    }
+
+    /**
+     * Writes the {@code pom.xml} and {@code pom.properties} files.
+     * This method returns the base temporary directory followed by files that the "jar" tool will need to add
+     *
+     * @param archive archive configuration
+     * @param reproducible whether to enforce reproducible build
+     * @return arguments for the "jar" tool
+     * @throws IOException if an error occurred while writing the files
+     */
+    public List<Path> addPOM(final MavenArchiveConfiguration archive, final boolean reproducible) throws IOException {
+        final String groupId = project.getGroupId();
+        final String artifactId = project.getArtifactId();
+        final String version;
+        final ProducedArtifact pom = project.getPomArtifact();
+        if (pom.isSnapshot()) {
+            version = pom.getVersion().toString();
+        } else {
+            version = project.getVersion();
+        }
+        final Path baseDir = baseDirectory();
+        final Path mavenDir = createDirectories(baseDir, META_INF, MAVEN_DIR, groupId, artifactId);
+        final Path pomFile = linkOrCopy(attachedPOM, mavenDir.resolve("pom.xml"));
+        filesToDelete.add(pomFile); // Add soon for deleting this file even if an exception is thrown below.
+        /*
+         * Subset of above "pom.xml" file but written as a properties file.
+         * If reproducible build is enabled, we will need to reformat after
+         * writing for ensuring a deterministic order of entries.
+         */
+        final var properties = new Properties();
+        Path propertiesFile = archive.getPomPropertiesFile();
+        if (propertiesFile != null) {
+            try (InputStream in = Files.newInputStream(propertiesFile)) {
+                properties.load(in);
+            }
+        }
+        properties.setProperty("groupId", groupId);
+        properties.setProperty("artifactId", artifactId);
+        properties.setProperty("version", version);
+        propertiesFile = mavenDir.resolve("pom.properties");
+        try (BufferedWriter out = Files.newBufferedWriter(propertiesFile)) {
+            filesToDelete.add(propertiesFile); // Add soon for deleting this file even if an exception is thrown below.
+            properties.store(out, "Subset of pom.xml");
+        }
+        if (reproducible) {
+            // The encoding can be either UTF-8 or ISO-8859-1, as any non ASCII character
+            // is transformed into a \\uxxxx sequence anyway.
+            Files.writeString(
+                    propertiesFile,
+                    Files.lines(propertiesFile)
+                            .filter(line -> !line.startsWith("#"))
+                            .sorted()
+                            .collect(Collectors.joining("\n", "", "\n"))); // system independent new line.
+        }
+        return List.of(baseDir, Path.of(META_INF, MAVEN_DIR));
+    }
+
+    /**
+     * Creates a link to the given source if supported, or copies the file otherwise.
+     *
+     * @param source the source file to link or copy
+     * @param target the file to create
+     * @return the target file which should be deleted after the build
+     */
+    private static Path linkOrCopy(final Path source, final Path target) throws IOException {
+        try {
+            return Files.createLink(target, source);
+        } catch (UnsupportedOperationException e) {
+            return Files.copy(source, target);
+        }
+    }
+
+    /**
+     * Cancels the deletion of files. The files will stay present after the build.
+     * This is desired for allowing user to execute {@code jar} on the command-line,
+     * for example when the build failed.
+     */
+    public void cancelFileDeletion() {
+        filesToDelete.clear();
+    }
+
+    /**
+     * Deletes all temporary files and directories created by this class.
+     *
+     * @throws IOException if an error occurred while deleting a file or directory
+     */
+    @Override
+    public void close() throws IOException {
+        for (int i = filesToDelete.size(); --i >= 0; ) {
+            Files.delete(filesToDelete.get(i));

Review Comment:
   Not really needed. These temporary files are in the build directory, so they are deleted when `mvn clean` is deleted even if the above code failed. Furthermore, the plugin intentionally left those files undeleted when the `jar` tool failed in order to allow users to debug. Stopping at the first failed attempt to delete a file would be consistent with this policy. I will rather add a comment explaining that in the javadoc of this method.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3844373364


##########
src/main/java/org/apache/maven/plugins/jar/AbstractJarMojo.java:
##########
@@ -207,167 +205,208 @@ protected final Log getLog() {
     protected abstract String getType();
 
     /**
-     * Returns the JAR file to generate, based on an optional classifier.
+     * {@return the scope of dependencies}
+     * It should be {@link PathScope#MAIN_COMPILE} or {@link PathScope#TEST_COMPILE}.
+     * Note that we use compile scope rather than runtime scope because dependencies
+     * cannot appear in {@code requires} statement if they didn't had compile scope.
+     */
+    protected abstract PathScope getDependencyScope();
+
+    /**
+     * {@return the JAR tool to use for archiving the code}
      *
-     * @param basedir the output directory
-     * @param resultFinalName the name of the JAR file
-     * @param classifier an optional classifier
-     * @return the file to generate
+     * @throws MojoException if no JAR tool was found
+     *
+     * @since 4.0.0-beta-2
      */
-    protected Path getJarFile(Path basedir, String resultFinalName, String classifier) {
-        Objects.requireNonNull(basedir, "basedir is not allowed to be null");
-        Objects.requireNonNull(resultFinalName, "finalName is not allowed to be null");
-        String fileName = resultFinalName + (hasClassifier(classifier) ? '-' + classifier : "") + ".jar";
-        return basedir.resolve(fileName);
+    protected ToolProvider getJarTool() throws MojoException {
+        return ToolProvider.findFirst(toolId).orElseThrow(() -> new MojoException("No such \"" + toolId + "\" tool."));
     }
 
     /**
-     * Generates the JAR.
+     * Returns the output time stamp or, as a fallback, the {@code SOURCE_DATE_EPOCH} environment variable.
+     * If the time stamp is expressed in seconds, it is converted to ISO 8601 format. Otherwise it is returned as-is.
      *
-     * @return the path to the created archive file
-     * @throws MojoException in case of an error
+     * @return the time stamp in presumed ISO 8601 format, or {@code null} if none
+     *
+     * @since 4.0.0-beta-2
      */
-    public Path createArchive() throws MojoException {
-        Path basedir = outputDirectory != null
-                ? outputDirectory
-                : Path.of(project.getBuild().getDirectory());
-        String resultFinalName =
-                finalName != null ? finalName : project.getBuild().getFinalName();
-        Path jarFile = getJarFile(basedir, resultFinalName, getClassifier());
-
-        FileSetManager fileSetManager = new FileSetManager();
-        FileSet jarContentFileSet = new FileSet();
-        jarContentFileSet.setDirectory(getClassesDirectory().toAbsolutePath().toString());
-        jarContentFileSet.setIncludes(Arrays.asList(getIncludes()));
-        jarContentFileSet.setExcludes(Arrays.asList(getExcludes()));
-
-        String[] includedFiles = fileSetManager.getIncludedFiles(jarContentFileSet);
-
-        if (detectMultiReleaseJar
-                && Arrays.stream(includedFiles)
-                        .anyMatch(
-                                p -> p.startsWith("META-INF" + File.separatorChar + "versions" + File.separatorChar))) {
-            getLog().debug("Adding 'Multi-Release: true' manifest entry.");
-            archive.addManifestEntry(Attributes.Name.MULTI_RELEASE.toString(), "true");
+    protected String getOutputTimestamp() {
+        String time = nullIfAbsent(outputTimestamp);
+        if (time == null) {
+            time = nullIfAbsent(System.getenv("SOURCE_DATE_EPOCH"));
+            if (time == null) {
+                return null;
+            }
         }
+        if (Runtime.version().feature() < ToolExecutor.JDK_SUPPORT_DATE) {
+            log.warn("Reproducible build requires Java " + ToolExecutor.JDK_SUPPORT_DATE + " or later.");
+            return null;
+        }
+        for (int i = time.length(); --i >= 0; ) {
+            char c = time.charAt(i);
+            if ((c < '0' || c > '9') && (i != 0 || c != '-')) {
+                return time;
+            }
+        }
+        return Instant.ofEpochSecond(Long.parseLong(time)).toString();

Review Comment:
   Applied the `try` … `catch` approach.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "rmannibucau (via GitHub)" <gi...@apache.org>.
rmannibucau commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3792629983


##########
src/main/java/org/apache/maven/plugins/jar/AbstractJarMojo.java:
##########
@@ -207,167 +205,199 @@ protected final Log getLog() {
     protected abstract String getType();
 
     /**
-     * Returns the JAR file to generate, based on an optional classifier.
+     * {@return the scope of dependencies}
+     * It should be {@link PathScope#MAIN_COMPILE} or {@link PathScope#TEST_COMPILE}.
+     * Note that we use compile scope rather than runtime scope because dependencies
+     * cannot appear in {@code requires} statement if they didn't had compile scope.
+     */
+    protected abstract PathScope getDependencyScope();
+
+    /**
+     * {@return the JAR tool to use for archiving the code}
      *
-     * @param basedir the output directory
-     * @param resultFinalName the name of the JAR file
-     * @param classifier an optional classifier
-     * @return the file to generate
+     * @throws MojoException if no JAR tool was found
+     *
+     * @since 4.0.0-beta-2
      */
-    protected Path getJarFile(Path basedir, String resultFinalName, String classifier) {
-        Objects.requireNonNull(basedir, "basedir is not allowed to be null");
-        Objects.requireNonNull(resultFinalName, "finalName is not allowed to be null");
-        String fileName = resultFinalName + (hasClassifier(classifier) ? '-' + classifier : "") + ".jar";
-        return basedir.resolve(fileName);
+    protected ToolProvider getJarTool() throws MojoException {
+        return ToolProvider.findFirst(toolId).orElseThrow(() -> new MojoException("No such \"" + toolId + "\" tool."));
     }
 
     /**
-     * Generates the JAR.
+     * Returns whether the specified Java version is supported.
      *
-     * @return the path to the created archive file
-     * @throws MojoException in case of an error
+     * @param release name of an {@link SourceVersion} enumeration constant
+     * @return whether the current environment support that version
      */
-    public Path createArchive() throws MojoException {
-        Path basedir = outputDirectory != null
-                ? outputDirectory
-                : Path.of(project.getBuild().getDirectory());
-        String resultFinalName =
-                finalName != null ? finalName : project.getBuild().getFinalName();
-        Path jarFile = getJarFile(basedir, resultFinalName, getClassifier());
-
-        FileSetManager fileSetManager = new FileSetManager();
-        FileSet jarContentFileSet = new FileSet();
-        jarContentFileSet.setDirectory(getClassesDirectory().toAbsolutePath().toString());
-        jarContentFileSet.setIncludes(Arrays.asList(getIncludes()));
-        jarContentFileSet.setExcludes(Arrays.asList(getExcludes()));
-
-        String[] includedFiles = fileSetManager.getIncludedFiles(jarContentFileSet);
-
-        if (detectMultiReleaseJar
-                && Arrays.stream(includedFiles)
-                        .anyMatch(
-                                p -> p.startsWith("META-INF" + File.separatorChar + "versions" + File.separatorChar))) {
-            getLog().debug("Adding 'Multi-Release: true' manifest entry.");
-            archive.addManifestEntry(Attributes.Name.MULTI_RELEASE.toString(), "true");
+    private static boolean isSupported(String release) {

Review Comment:
   wrong comment location?



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#issuecomment-5313564546

   > in this new implementation, is the `MANIFEST.MF` content still generated first by our usual tooling, then only added to the jar and tidied up by `jar` tool?
   
   Yes. The plugin is still using `MavenArchiver` and `MavenArchiveConfiguration` from the `org.apache.maven.shared.archiver` package. The plugin uses the archiver for getting an initial `META-INF.MF` file, then gives the path to that file to the `jar` tool using the `--manifest` option.
   
   Preparing a `MANIFEST.MF` is the only functionality of `MavenArchiver` that the new implementation is still using. We could bring that functionality in the plugin, which would remove the dependency to Archiver. But I keep that for a separated discussion later.


-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#issuecomment-5325568521

   > there are many other packaging plugins that benefit from Maven Archiver: war, etc... I'm not convinced. But we'll have a deeper discussion if you really still feel this is a good idea
   
   The other plugins would not be impacted if the JAR plugin become independent of Maven Archiver. The proposal is only to copy (in a modified form) in the JAR plugin the code that generate the `MANIFEST.MF`. The original code in Maven Archiver would be untouched. What to do with that code could be a separated discussion.


-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "pzygielo (via GitHub)" <gi...@apache.org>.
pzygielo commented on PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#issuecomment-5339253017

   > As a result, this breaks spring applications component scan which relies on it.
   
   Please link spring issue for reference. Directory entries are not required in a JAR/ZIP file.
   


-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "seregamorph (via GitHub)" <gi...@apache.org>.
seregamorph commented on PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#issuecomment-5341698144

   > I just wanted to note that directory entries are optional, so if spring relies on them to be present it would be better fixed there to work without it.
   
   Let me give some clarity here. While I actually don't argue regarding this reasoning, absolutely most of spring boot projects as for today are based on Spring Boot 2 and 3. And Spring Boot 2 and 3 will never receive a public updates anymore (there are only private for paid extended subscriptions), see https://spring.io/projects/spring-boot#support
   


-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#issuecomment-5343029789

   @jaikiran : just for information, I was not aware of [JDK-8276764](https://bugs.openjdk.org/browse/JDK-8276764). It makes `--change-dir` proposal less needed. Maybe there is no change needed in `jar` after all. We are exploring the options.


-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#issuecomment-5344934684

   This is an example of why I hate binary reproducible builds. I think that Docker and other environments should adapt to semantically equivalent builds, but I realize that it will not happen soon.
   
   I will need time for incorporating the changes and will try to do that Saturday. Some changes compared to the current commits were discussed on Slack. In particular, a more systematic approach may be desirable for the issue of missing directory entries.


-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#issuecomment-5353892455

   > postprocessing jar file to set timestamp should not be hard
   
   But is is worth the effort? It would be a hack needed for JDK 17 and 18 only. And since the file ordering issue (JDK-8276764) was fixed in JDK 18 only, even if we fix the timestamp the build would still non-reproducible on JDK 17. Therefore, setting the timestamp would be useful for only one specific JDK version: 18.


-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "seregamorph (via GitHub)" <gi...@apache.org>.
seregamorph commented on PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#issuecomment-5354997221

   IMO it's critical to support binary reproducibility for all JDKs since minimal 17, otherwise it'll be a regression.


-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#issuecomment-5355635326

   Thanks @jaikiran for the clarification. Then indeed, editing timestamps in a post-processing would work on both JDK 17 and 18.
   
   Whether we should do this post-processing is still uncertain to me. Not doing this post-processing would be a regression only for users wanting binary reproducible builds with the tools of JDK 17 or 18. Users who do not upgrade to a more recent Java version at least for building (even if they target a lower release with `--release`) may be conservative regarding their Maven upgrade too, in which case the 3.x plugins continue to work as today.


-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3949059924


##########
src/main/java/org/apache/maven/plugins/jar/DirectoryRole.java:
##########
@@ -0,0 +1,73 @@
+/*
+ * 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.jar;
+
+/**
+ * Directories that the archiver needs to handle in a special way.
+ */
+enum DirectoryRole {
+    /**
+     * The root directory. This is usually {@code "target/classes"}.
+     * The next locations can be {@link #META_INF}, {@link #NAMED_MODULE} or {@link #RESOURCES}.
+     */
+    ROOT,
+
+    /**
+     * The {@code "META-INF"} or {@code "<module>/META-INF"} directory.
+     * This is part of the <abbr>JAR</abbr> specification.
+     * The next locations can be {@link #VERSIONS} or {@link #VERSIONS_MODULAR}.
+     */
+    META_INF,
+
+    /**
+     * The {@code "META-INF/versions"} or {@code "<module>/META-INF/versions"} directory.
+     * This is part of the <abbr>JAR</abbr> specification, except the {@code <module>} prefix.
+     * The sub-directories are named according to Java releases such as "21".
+     * The next location can only be {@link #RESOURCES}.
+     */
+    VERSIONS,
+
+    /**
+     * The Maven-specific {@code "META-INF/versions-modular"} directory.
+     * {@code "<module>/META-INF/versions-modular"} is not forbidden, but does not make sense.
+     * The sub-directories are named according to Java releases such as "21".
+     * The next location can only be {@link #MODULES}.
+     */
+    VERSIONS_MODULAR,
+
+    /**
+     * The Maven-specific {@code "META-INF/versions-modular"} directory.

Review Comment:
   Indeed, it was a documentation issue. Replaced by "A directory other than the root directory which contains many modules. This is typically a `META-INF/versions-modular/<n>` directory containing all modules for Java version _n_."



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3949329116


##########
src/main/java/org/apache/maven/plugins/jar/ToolExecutor.java:
##########
@@ -0,0 +1,551 @@
+/*
+ * 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.jar;
+
+import javax.lang.model.SourceVersion;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+import java.util.spi.ToolProvider;
+
+import org.apache.maven.api.Project;
+import org.apache.maven.api.Type;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.MojoException;
+import org.apache.maven.shared.archiver.MavenArchiveConfiguration;
+
+/**
+ * Writer of <abbr>JAR</abbr> files using the information collected by {@link FileCollector}.
+ * This class uses the {@code "jar"} tool provided with the <abbr>JDK</abbr>.
+ */
+final class ToolExecutor {
+    /**
+     * First JDK feature version whose {@code jar} tool can run {@code --validate} on archives
+     * that contain records. Earlier {@code jar} tools failed with "This feature requires ASM8"
+     * (JDK-8282446, fixed by JDK-8282508 in JDK 19 by not backported to a 17u or 18u update).
+     *
+     * @see <a href="https://bugs.openjdk.org/browse/JDK-8282446">JDK-8282446</a>
+     * @see <a href="https://bugs.openjdk.org/browse/JDK-8282508">JDK-8282508</a>
+     */
+    private static final int JDK_FIXING_JAR_VALIDATE = 19;
+
+    /**
+     * First JDK feature version whose {@code jar} tool support the {@code --date} option.
+     */
+    private static final int JDK_SUPPORT_DATE = 19;
+
+    /**
+     * The {@value} attribute. Its value is automatically generated by {@link Manifest},
+     * but may need to be replaced by another value if JDK-independent value is desired
+     * for strictly reproducible builds.
+     */
+    private static final String CREATED_BY = "Created-By";
+
+    /**
+     * The Maven project for which to create an archive.
+     */
+    final Project project;
+
+    /**
+     * {@code "jar"} or {@link "test-jar"}.
+     */
+    private final String artifactType;
+
+    /**
+     * The output directory where to write the <abbr>JAR</abbr> file.
+     * This is usually {@code ${baseDir}/target/}.
+     */
+    private final Path outputDirectory;
+
+    /**
+     * The <abbr>JAR</abbr> file name when package hierarchy is used.
+     * This is usually a file placed in the {@link ToolExecutor#outputDirectory} directory.
+     */
+    private final String finalName;
+
+    /**
+     * The classifier (e.g. "test"), or {@code null} if none.
+     */
+    private final String classifier;
+
+    /**
+     * Whether to validate the <abbr>JAR</abbr> file after its creation.
+     * If {@code null}, a value will be determined automatically based on heuristic rules.
+     */
+    private final Boolean validate;
+
+    /**
+     * The tool to use for creating the <abbr>JAR</abbr> files.
+     */
+    private final ToolProvider tool;
+
+    /**
+     * Where to send messages emitted by the "jar" tool.
+     */
+    private final PrintWriter messageWriter;
+
+    /**
+     * Where to send error messages emitted by the "jar" tool.
+     */
+    private final PrintWriter errorWriter;
+
+    /**
+     * Where the messages sent to {@link #messageWriter} are stored.
+     */
+    private final StringBuffer messages;
+
+    /**
+     * Where the messages sent to {@link #errorWriter} are stored.
+     */
+    private final StringBuffer errors;
+
+    /**
+     * A buffer for the arguments given to the "jar" tool, reused for each module.
+     * Each element of the list must be instances of either {@link String} or {@link Path}.
+     */
+    private final List<Object> arguments;
+
+    /**
+     * The paths to the created archive files.
+     * Map keys are module names or {@code null} if the project does not use module hierarchy.
+     * Values are (<var>type</var>, <var>path</var>) pairs associated with each module where
+     * <var>type</var> is {@code "pom"}, {@code "jar"} or {@code "test-jar"} and <var>path</var>
+     * is the path to the <abbr>POM</abbr> or <abbr>JAR</abbr> file.
+     */
+    private final Map<String, Map<String, Path>> result;
+
+    /**
+     * Mapper from Maven dependencies to Java modules, or {@code null} if the project does not use module hierarchy.
+     * This mapper is created only once for a Maven project and reused for each Java module to archive.
+     *
+     * <p>This field is not used directly by {@code ToolExecutor}. It is defined in this class for transferring
+     * this information from {@link AbstractJarMojo} to {@link PomDerivation.ForModule}.
+     * This is an internal mechanism that should not be public or protected.</p>
+     */
+    PomDerivation pomDerivation;
+
+    /**
+     * Manifest to merge with the manifest found in the files to archive.
+     * This is a manifest built from the {@code <archive>} plugin configuration.
+     * Can be {@code null} if there is noting to add to the existing manifests.
+     */
+    private final Manifest manifestFromPlugin;
+
+    /**
+     * The file from which {@link #manifestFromPlugin} has been read, or {@code null} if none.
+     * If non-null, reading that file must produce the same manifest as {@link #manifestFromPlugin}.
+     * It implies that this field must be {@code null} if {@link #manifestFromPlugin} is the result
+     * of merging elements specified in {@code <archive>} with a file specified in the plugin configuration.
+     */
+    private final Path manifestFile;
+
+    /**
+     * The archive configuration to use.
+     */
+    private final MavenArchiveConfiguration archiveConfiguration;
+
+    /**
+     * The timestamp in ISO-8601 extended offset date-time, or {@code null} if none.
+     * If user provided a value in seconds, it must have been converted to ISO-8601.
+     * This is used for reproducible builds.
+     */
+    private final String outputTimestamp;
+
+    /**
+     * Whether to force to build new <abbr>JAR</abbr> files even if none of the contents appear to have changed.
+     */
+    private final boolean forceCreation;
+
+    /**
+     * Where to send informative or error messages.
+     */
+    private final Log logger;
+
+    /**
+     * Creates a new writer.
+     *
+     * @param mojo the <abbr>MOJO</abbr> from which to get the configuration
+     * @param manifest manifest built from plugin configuration, or {@code null} if none
+     * @param archive the archive configuration
+     * @throws IOException if an error occurred while reading the manifest file
+     */
+    ToolExecutor(AbstractJarMojo mojo, Manifest manifest, MavenArchiveConfiguration archive) throws IOException {
+        project = mojo.project;
+        artifactType = mojo.getType();
+        outputDirectory = mojo.getOutputDirectory();
+        classifier = AbstractJarMojo.nullIfAbsent(mojo.getClassifier());
+        finalName =
+                (mojo.finalName != null) ? mojo.finalName : project.getBuild().getFinalName();
+        forceCreation = mojo.forceCreation;
+        outputTimestamp = mojo.getOutputTimestamp();
+        validate = mojo.getValidate();
+        logger = mojo.log;
+        tool = mojo.getJarTool();
+
+        var buffer = new StringWriter();
+        messages = buffer.getBuffer();
+        messageWriter = new PrintWriter(buffer);
+
+        buffer = new StringWriter();
+        errors = buffer.getBuffer();
+        errorWriter = new PrintWriter(buffer);

Review Comment:
   `java.util.spi.ToolProvider` knows nothing about Maven loggers. `errorWriter` is where the tool reports the errors. Then, if `errorWriter` is non empty, the Maven JAR Plugin copies its content to the Maven logger.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux merged PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508


-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#issuecomment-5510519255

   @elharo : I tried to address the documentation issues. Are we okay for a merge?


-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "elharo (via GitHub)" <gi...@apache.org>.
elharo commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3915210018


##########
src/main/java/org/apache/maven/plugins/jar/AbstractJarMojo.java:
##########
@@ -140,24 +144,52 @@ public abstract class AbstractJarMojo implements org.apache.maven.api.plugin.Moj
      * Timestamp for reproducible output archive entries.
      * This is either formatted as ISO 8601 extended offset date-time
      * (e.g. in UTC such as '2011-12-03T10:15:30Z' or with an offset '2019-10-05T20:37:42+06:00'),
-     * or as an integer representing seconds since the epoch
-     * (like <a href="https://reproducible-builds.org/docs/source-date-epoch/">SOURCE_DATE_EPOCH</a>).
+     * or as an integer representing seconds since the Java epoch (January 1st, 1970).
+     * If not configured or disabled,
+     * the <a href="https://reproducible-builds.org/docs/source-date-epoch/">SOURCE_DATE_EPOCH</a>
+     * environment variable is used as a fallback value,
+     * to ease forcing Reproducible Build externally when the build has not enabled it natively in <abbr>POM</abbr>.

Review Comment:
   again, I really think you're overusing the abbr element



##########
src/main/java/org/apache/maven/plugins/jar/AbstractJarMojo.java:
##########
@@ -140,24 +144,52 @@ public abstract class AbstractJarMojo implements org.apache.maven.api.plugin.Moj
      * Timestamp for reproducible output archive entries.
      * This is either formatted as ISO 8601 extended offset date-time
      * (e.g. in UTC such as '2011-12-03T10:15:30Z' or with an offset '2019-10-05T20:37:42+06:00'),
-     * or as an integer representing seconds since the epoch
-     * (like <a href="https://reproducible-builds.org/docs/source-date-epoch/">SOURCE_DATE_EPOCH</a>).
+     * or as an integer representing seconds since the Java epoch (January 1st, 1970).
+     * If not configured or disabled,
+     * the <a href="https://reproducible-builds.org/docs/source-date-epoch/">SOURCE_DATE_EPOCH</a>
+     * environment variable is used as a fallback value,
+     * to ease forcing Reproducible Build externally when the build has not enabled it natively in <abbr>POM</abbr>.
+     *
+     * <p>This property is supported only in Java 19 or later.</p>
      *
      * @since 3.2.0
      */
     @Parameter(defaultValue = "${project.build.outputTimestamp}")
     protected String outputTimestamp;
 
     /**
-     * Whether to detect multi-release JAR files.
-     * If the JAR contains the {@code META-INF/versions} directory it will be detected as a multi-release JAR file
-     * ("MRJAR"), adding the {@code Multi-Release: true} attribute to the main section of the JAR {@code MANIFEST.MF}.
+     * Whether to detect multi-release <abbr>JAR</abbr> files.
+     * If the JAR contains the {@code META-INF/versions} directory, it is detected as a multi-release JAR file.

Review Comment:
   Note you're not using abbr on JAR in this line. It's fine without it 



##########
src/main/java/org/apache/maven/plugins/jar/Archive.java:
##########
@@ -0,0 +1,655 @@
+/*
+ * 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.jar;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.TreeMap;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.Type;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.MojoException;
+
+/**
+ * Files or root directories to archive for a single module.
+ * A single instance of {@code Archive} can contain many directories for different target Java releases.
+ * Many instances of {@code Archive} can exist when archiving a multi-modules project.
+ */
+final class Archive {
+    /**
+     * Path to the <abbr>POM</abbr> file generated for this archive, or {@code null} if none.
+     * This is non-null only if module source hierarchy is used, in which case the dependencies
+     * declared in this file are the intersection of the project dependencies and the content of
+     * the {@code module-info.class} file.
+     */
+    @Nullable
+    Path pomFile;
+
+    /**
+     * The <var>JAR</var> file to create. Can be an existing file,

Review Comment:
   var is not right here.



##########
src/main/java/org/apache/maven/plugins/jar/Archive.java:
##########
@@ -0,0 +1,655 @@
+/*
+ * 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.jar;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.TreeMap;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.Type;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.MojoException;
+
+/**
+ * Files or root directories to archive for a single module.
+ * A single instance of {@code Archive} can contain many directories for different target Java releases.
+ * Many instances of {@code Archive} can exist when archiving a multi-modules project.
+ */
+final class Archive {
+    /**
+     * Path to the <abbr>POM</abbr> file generated for this archive, or {@code null} if none.
+     * This is non-null only if module source hierarchy is used, in which case the dependencies
+     * declared in this file are the intersection of the project dependencies and the content of
+     * the {@code module-info.class} file.
+     */
+    @Nullable
+    Path pomFile;
+
+    /**
+     * The <var>JAR</var> file to create. Can be an existing file,
+     * in which case the file creation can be skipped if the file is still up-to-date.
+     */
+    @Nonnull
+    final Path jarFile;
+
+    /**
+     * A helper class for checking whether an existing <abbr>JAR</abbr> file is still up-to-date.
+     * This is null if there is no existing JAR file, or if we determined that the file is outdated.
+     */
+    private TimestampCheck existingJAR;
+
+    /**
+     * Name of the module being archived when the project is using module hierarchy.
+     * This is {@code null} if the project is using package hierarchy, either because it is a classical
+     * class-path project or because it is a single module compiled without using the module hierarchy.
+     * When using module source hierarchy, {@code javac} guarantees that the module name in the output
+     * directory is the name of the parent directory of {@code module-info.class}.
+     */
+    @Nullable
+    final String moduleName;
+
+    /**
+     * Path to {@code META-INF/MANIFEST.MF}, or {@code null} if none.
+     * If non-null, this value will be given to the {@code --manifest} option.
+     * The use of this option is preferable to adding {@code MANIFEST.MF} as an ordinary file.
+     *
+     * @see #setManifest(Path, boolean)
+     * @see #mergeManifest(Path, Manifest)
+     */
+    @Nullable
+    private Path manifest;
+
+    /**
+     * The Maven generated {@code pom.xml} and {@code pom.properties} files, or {@code null} if none.
+     * This first item must be the base directory where the files are located.
+     */
+    @Nullable
+    List<Path> mavenFiles;
+
+    /**
+     * Fully-qualified name of the main class, or {@code null} if none.
+     * This is the value to provide to the {@code --main-class} option.
+     */
+    private String mainClass;
+
+    /**
+     * Files or root directories to store in the <abbr>JAR</abbr> file for each target Java release
+     * other than the base release. Keys are the target Java release with {@code null} for the base
+     * release.
+     */
+    @Nonnull
+    private final NavigableMap<Runtime.Version, FileSet> filesetForRelease;
+
+    /**
+     * Files or root directories to archive for a single target Java release of a single module.
+     * The {@link Archive} enclosing must contain at least one instance of {@code FileSet} for
+     * the base release, and an arbitrary amount of other instances for other target releases.
+     */
+    final class FileSet {
+        /**
+         * The root directory of all files or directories to archive.
+         * This is the value to pass to the {@code -C} tool option.
+         */
+        @Nonnull
+        final Path directory;
+
+        /**
+         * The files or directories to include in the <var>JAR</var> file.

Review Comment:
   remove var



##########
src/main/java/org/apache/maven/plugins/jar/Archive.java:
##########
@@ -0,0 +1,655 @@
+/*
+ * 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.jar;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.TreeMap;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.Type;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.MojoException;
+
+/**
+ * Files or root directories to archive for a single module.
+ * A single instance of {@code Archive} can contain many directories for different target Java releases.
+ * Many instances of {@code Archive} can exist when archiving a multi-modules project.
+ */
+final class Archive {
+    /**
+     * Path to the <abbr>POM</abbr> file generated for this archive, or {@code null} if none.
+     * This is non-null only if module source hierarchy is used, in which case the dependencies
+     * declared in this file are the intersection of the project dependencies and the content of
+     * the {@code module-info.class} file.
+     */
+    @Nullable
+    Path pomFile;
+
+    /**
+     * The <var>JAR</var> file to create. Can be an existing file,
+     * in which case the file creation can be skipped if the file is still up-to-date.
+     */
+    @Nonnull
+    final Path jarFile;
+
+    /**
+     * A helper class for checking whether an existing <abbr>JAR</abbr> file is still up-to-date.
+     * This is null if there is no existing JAR file, or if we determined that the file is outdated.
+     */
+    private TimestampCheck existingJAR;
+
+    /**
+     * Name of the module being archived when the project is using module hierarchy.
+     * This is {@code null} if the project is using package hierarchy, either because it is a classical
+     * class-path project or because it is a single module compiled without using the module hierarchy.
+     * When using module source hierarchy, {@code javac} guarantees that the module name in the output
+     * directory is the name of the parent directory of {@code module-info.class}.
+     */
+    @Nullable
+    final String moduleName;
+
+    /**
+     * Path to {@code META-INF/MANIFEST.MF}, or {@code null} if none.
+     * If non-null, this value will be given to the {@code --manifest} option.
+     * The use of this option is preferable to adding {@code MANIFEST.MF} as an ordinary file.
+     *
+     * @see #setManifest(Path, boolean)
+     * @see #mergeManifest(Path, Manifest)
+     */
+    @Nullable
+    private Path manifest;
+
+    /**
+     * The Maven generated {@code pom.xml} and {@code pom.properties} files, or {@code null} if none.
+     * This first item must be the base directory where the files are located.
+     */
+    @Nullable
+    List<Path> mavenFiles;
+
+    /**
+     * Fully-qualified name of the main class, or {@code null} if none.
+     * This is the value to provide to the {@code --main-class} option.
+     */
+    private String mainClass;
+
+    /**
+     * Files or root directories to store in the <abbr>JAR</abbr> file for each target Java release
+     * other than the base release. Keys are the target Java release with {@code null} for the base
+     * release.
+     */
+    @Nonnull
+    private final NavigableMap<Runtime.Version, FileSet> filesetForRelease;
+
+    /**
+     * Files or root directories to archive for a single target Java release of a single module.
+     * The {@link Archive} enclosing must contain at least one instance of {@code FileSet} for
+     * the base release, and an arbitrary amount of other instances for other target releases.
+     */
+    final class FileSet {
+        /**
+         * The root directory of all files or directories to archive.
+         * This is the value to pass to the {@code -C} tool option.
+         */
+        @Nonnull
+        final Path directory;
+
+        /**
+         * The files or directories to include in the <var>JAR</var> file.
+         * Can be absolute paths or paths relative to {@link #directory}.
+         * It usually contains only the files or directories directly in
+         * the root {@linkplain #directory}, not in sub-directories.
+         */
+        @Nonnull
+        final List<Path> files;
+
+        /**
+         * Creates an initially empty set of files or directories for a specific target Java release.
+         *
+         * @param directory the base directory of the files or directories to archive
+         */
+        private FileSet(Path directory) {
+            this.directory = directory;
+            this.files = new ArrayList<>();
+        }
+
+        /**
+         * 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.
+         * The caller should use that common directory for logging a warning message.
+         *
+         * @param base base directory found by previous invocations of this method, or {@code null} if none
+         * @return common directory of discarded files
+         */
+        private Path discardAllFiles(Path base) {
+            for (Path file : files) {
+                if (base == null) {
+                    base = file.getParent();
+                } else {
+                    while (!file.startsWith(base)) {
+                        base = base.getParent();
+                        if (base == null) {
+                            break;
+                        }
+                    }
+                }
+            }
+            files.clear();
+            return base;
+        }
+
+        /**
+         * Adds the given path to the list of files or directories to archive.
+         * If the given path is a directory, then all children will be included.
+         * Children to exclude, if any, should be managed by {@link ExcludedFiles}.
+         *
+         * @param item a file or directory to archive
+         * @param attributes the file's basic attributes
+         * @param isDirectory whether the file is a directory
+         */
+        void add(Path item, BasicFileAttributes attributes, boolean isDirectory) {
+            TimestampCheck tc = existingJAR;

Review Comment:
   avoid abbreviations



##########
src/main/java/org/apache/maven/plugins/jar/Archive.java:
##########
@@ -0,0 +1,655 @@
+/*
+ * 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.jar;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.TreeMap;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.Type;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.MojoException;
+
+/**
+ * Files or root directories to archive for a single module.
+ * A single instance of {@code Archive} can contain many directories for different target Java releases.
+ * Many instances of {@code Archive} can exist when archiving a multi-modules project.
+ */
+final class Archive {
+    /**
+     * Path to the <abbr>POM</abbr> file generated for this archive, or {@code null} if none.
+     * This is non-null only if module source hierarchy is used, in which case the dependencies
+     * declared in this file are the intersection of the project dependencies and the content of
+     * the {@code module-info.class} file.
+     */
+    @Nullable
+    Path pomFile;
+
+    /**
+     * The <var>JAR</var> file to create. Can be an existing file,
+     * in which case the file creation can be skipped if the file is still up-to-date.
+     */
+    @Nonnull
+    final Path jarFile;
+
+    /**
+     * A helper class for checking whether an existing <abbr>JAR</abbr> file is still up-to-date.
+     * This is null if there is no existing JAR file, or if we determined that the file is outdated.
+     */
+    private TimestampCheck existingJAR;
+
+    /**
+     * Name of the module being archived when the project is using module hierarchy.
+     * This is {@code null} if the project is using package hierarchy, either because it is a classical
+     * class-path project or because it is a single module compiled without using the module hierarchy.
+     * When using module source hierarchy, {@code javac} guarantees that the module name in the output
+     * directory is the name of the parent directory of {@code module-info.class}.
+     */
+    @Nullable
+    final String moduleName;
+
+    /**
+     * Path to {@code META-INF/MANIFEST.MF}, or {@code null} if none.
+     * If non-null, this value will be given to the {@code --manifest} option.
+     * The use of this option is preferable to adding {@code MANIFEST.MF} as an ordinary file.
+     *
+     * @see #setManifest(Path, boolean)
+     * @see #mergeManifest(Path, Manifest)
+     */
+    @Nullable
+    private Path manifest;
+
+    /**
+     * The Maven generated {@code pom.xml} and {@code pom.properties} files, or {@code null} if none.
+     * This first item must be the base directory where the files are located.
+     */
+    @Nullable
+    List<Path> mavenFiles;
+
+    /**
+     * Fully-qualified name of the main class, or {@code null} if none.
+     * This is the value to provide to the {@code --main-class} option.
+     */
+    private String mainClass;
+
+    /**
+     * Files or root directories to store in the <abbr>JAR</abbr> file for each target Java release
+     * other than the base release. Keys are the target Java release with {@code null} for the base
+     * release.
+     */
+    @Nonnull
+    private final NavigableMap<Runtime.Version, FileSet> filesetForRelease;
+
+    /**
+     * Files or root directories to archive for a single target Java release of a single module.
+     * The {@link Archive} enclosing must contain at least one instance of {@code FileSet} for
+     * the base release, and an arbitrary amount of other instances for other target releases.
+     */
+    final class FileSet {
+        /**
+         * The root directory of all files or directories to archive.
+         * This is the value to pass to the {@code -C} tool option.
+         */
+        @Nonnull
+        final Path directory;
+
+        /**
+         * The files or directories to include in the <var>JAR</var> file.
+         * Can be absolute paths or paths relative to {@link #directory}.
+         * It usually contains only the files or directories directly in
+         * the root {@linkplain #directory}, not in sub-directories.
+         */
+        @Nonnull
+        final List<Path> files;
+
+        /**
+         * Creates an initially empty set of files or directories for a specific target Java release.
+         *
+         * @param directory the base directory of the files or directories to archive
+         */
+        private FileSet(Path directory) {
+            this.directory = directory;
+            this.files = new ArrayList<>();
+        }
+
+        /**
+         * 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.
+         * The caller should use that common directory for logging a warning message.
+         *
+         * @param base base directory found by previous invocations of this method, or {@code null} if none
+         * @return common directory of discarded files
+         */
+        private Path discardAllFiles(Path base) {
+            for (Path file : files) {
+                if (base == null) {
+                    base = file.getParent();
+                } else {
+                    while (!file.startsWith(base)) {
+                        base = base.getParent();
+                        if (base == null) {
+                            break;
+                        }
+                    }
+                }
+            }
+            files.clear();
+            return base;
+        }
+
+        /**
+         * Adds the given path to the list of files or directories to archive.
+         * If the given path is a directory, then all children will be included.
+         * Children to exclude, if any, should be managed by {@link ExcludedFiles}.
+         *
+         * @param item a file or directory to archive
+         * @param attributes the file's basic attributes
+         * @param isDirectory whether the file is a directory
+         */
+        void add(Path item, BasicFileAttributes attributes, boolean isDirectory) {
+            TimestampCheck tc = existingJAR;
+            if (tc != null && tc.isUpdated(item, attributes, isDirectory)) {
+                existingJAR = null; // Signal that the existing file is outdated.
+            }
+            files.add(item);
+        }
+
+        /**
+         * Adds to the given list the arguments to provide to the "jar" tool for this version.
+         * The elements added to the list will be instances of {@link String} or {@link Path}.
+         *
+         * <h4>Note about the {@code -C} option</h4>

Review Comment:
   I'd avoid headers in Javadoc. They may not render as expected



##########
src/main/java/org/apache/maven/plugins/jar/Archive.java:
##########
@@ -0,0 +1,655 @@
+/*
+ * 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.jar;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.TreeMap;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.Type;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.MojoException;
+
+/**
+ * Files or root directories to archive for a single module.
+ * A single instance of {@code Archive} can contain many directories for different target Java releases.
+ * Many instances of {@code Archive} can exist when archiving a multi-modules project.
+ */
+final class Archive {
+    /**
+     * Path to the <abbr>POM</abbr> file generated for this archive, or {@code null} if none.
+     * This is non-null only if module source hierarchy is used, in which case the dependencies
+     * declared in this file are the intersection of the project dependencies and the content of
+     * the {@code module-info.class} file.
+     */
+    @Nullable
+    Path pomFile;
+
+    /**
+     * The <var>JAR</var> file to create. Can be an existing file,
+     * in which case the file creation can be skipped if the file is still up-to-date.
+     */
+    @Nonnull
+    final Path jarFile;
+
+    /**
+     * A helper class for checking whether an existing <abbr>JAR</abbr> file is still up-to-date.
+     * This is null if there is no existing JAR file, or if we determined that the file is outdated.
+     */
+    private TimestampCheck existingJAR;
+
+    /**
+     * Name of the module being archived when the project is using module hierarchy.
+     * This is {@code null} if the project is using package hierarchy, either because it is a classical
+     * class-path project or because it is a single module compiled without using the module hierarchy.
+     * When using module source hierarchy, {@code javac} guarantees that the module name in the output
+     * directory is the name of the parent directory of {@code module-info.class}.
+     */
+    @Nullable
+    final String moduleName;
+
+    /**
+     * Path to {@code META-INF/MANIFEST.MF}, or {@code null} if none.
+     * If non-null, this value will be given to the {@code --manifest} option.
+     * The use of this option is preferable to adding {@code MANIFEST.MF} as an ordinary file.
+     *
+     * @see #setManifest(Path, boolean)
+     * @see #mergeManifest(Path, Manifest)
+     */
+    @Nullable
+    private Path manifest;
+
+    /**
+     * The Maven generated {@code pom.xml} and {@code pom.properties} files, or {@code null} if none.
+     * This first item must be the base directory where the files are located.
+     */
+    @Nullable
+    List<Path> mavenFiles;
+
+    /**
+     * Fully-qualified name of the main class, or {@code null} if none.
+     * This is the value to provide to the {@code --main-class} option.
+     */
+    private String mainClass;
+
+    /**
+     * Files or root directories to store in the <abbr>JAR</abbr> file for each target Java release
+     * other than the base release. Keys are the target Java release with {@code null} for the base
+     * release.
+     */
+    @Nonnull
+    private final NavigableMap<Runtime.Version, FileSet> filesetForRelease;
+
+    /**
+     * Files or root directories to archive for a single target Java release of a single module.
+     * The {@link Archive} enclosing must contain at least one instance of {@code FileSet} for
+     * the base release, and an arbitrary amount of other instances for other target releases.
+     */
+    final class FileSet {
+        /**
+         * The root directory of all files or directories to archive.
+         * This is the value to pass to the {@code -C} tool option.
+         */
+        @Nonnull
+        final Path directory;
+
+        /**
+         * The files or directories to include in the <var>JAR</var> file.
+         * Can be absolute paths or paths relative to {@link #directory}.
+         * It usually contains only the files or directories directly in
+         * the root {@linkplain #directory}, not in sub-directories.
+         */
+        @Nonnull
+        final List<Path> files;
+
+        /**
+         * Creates an initially empty set of files or directories for a specific target Java release.
+         *
+         * @param directory the base directory of the files or directories to archive
+         */
+        private FileSet(Path directory) {
+            this.directory = directory;
+            this.files = new ArrayList<>();
+        }
+
+        /**
+         * 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.
+         * The caller should use that common directory for logging a warning message.
+         *
+         * @param base base directory found by previous invocations of this method, or {@code null} if none
+         * @return common directory of discarded files
+         */
+        private Path discardAllFiles(Path base) {
+            for (Path file : files) {
+                if (base == null) {
+                    base = file.getParent();
+                } else {
+                    while (!file.startsWith(base)) {
+                        base = base.getParent();
+                        if (base == null) {
+                            break;
+                        }
+                    }
+                }
+            }
+            files.clear();
+            return base;
+        }
+
+        /**
+         * Adds the given path to the list of files or directories to archive.
+         * If the given path is a directory, then all children will be included.
+         * Children to exclude, if any, should be managed by {@link ExcludedFiles}.
+         *
+         * @param item a file or directory to archive
+         * @param attributes the file's basic attributes
+         * @param isDirectory whether the file is a directory
+         */
+        void add(Path item, BasicFileAttributes attributes, boolean isDirectory) {
+            TimestampCheck tc = existingJAR;
+            if (tc != null && tc.isUpdated(item, attributes, isDirectory)) {
+                existingJAR = null; // Signal that the existing file is outdated.
+            }
+            files.add(item);
+        }
+
+        /**
+         * Adds to the given list the arguments to provide to the "jar" tool for this version.
+         * The elements added to the list will be instances of {@link String} or {@link Path}.
+         *
+         * <h4>Note about the {@code -C} option</h4>
+         * This method repeats the {@code -C} option before each file.
+         * Our tests suggest that the first file after the directory specified by the {@code -C} option must
+         * be relative to that directory and all files after the first one must be prefixed by the directory
+         * which was specified in the {@code -C} option. This behavior is not very intuitive and replying on
+         * it can be fragile. Furthermore, it seems that the relativized file needs to be the shortest one,
+         * otherwise the {@code jar} tool rejects files after the first one with "names do not match".
+         * Which file is first depends on the unspecified directory-iteration order.
+         * Repeating the {@code -C} option for each file seems safer.
+         *
+         * @param addTo the list to add the arguments as {@link String} or {@link Path} instances to
+         * @param version the target Java release, or {@code null} for the base version of the <abbr>JAR</abbr> file
+         * @throws IllegalArgumentException if a path cannot be made relative to the base directory
+         */
+        private void arguments(List<Object> addTo, Runtime.Version version) {
+            if (files.isEmpty()) {
+                return;
+            }
+            if (version != null) {
+                addTo.add("--release");
+                addTo.add(version);
+            }
+            Path previous = null;
+            for (Path file : files) {
+                if (previous != null && file.startsWith(previous)) {
+                    // Already added a parent directory.
+                    continue;
+                }
+                previous = file;
+                file = directory.relativize(file);
+                if (file.getNameCount() <= 1 && file.toString().isEmpty()) {
+                    /*
+                     * The `-C` directory itself (e.g. a "META-INF/versions/<n>" directory added as a whole).
+                     * An empty file argument is invalid for the `jar` tool (some implementations reject it,
+                     * others silently misbehave), so archive the whole directory content with ".".
+                     */
+                    file = Path.of(".");
+                }
+                addTo.add("-C");
+                addTo.add(directory);
+                addTo.add(file);
+            }
+        }
+
+        /**
+         * {@return a string representation for debugging purposes}
+         */
+        @Override
+        public String toString() {
+            return getClass().getSimpleName() + '[' + directory.getFileName() + ": " + files.size() + " files]";
+        }
+    }
+
+    /**
+     * Creates an initially empty set of files or directories.
+     *
+     * @param jarFile path to the <abbr>JAR</abbr> file to create
+     * @param moduleName the module name if using module hierarchy, or {@code null} if using package hierarchy
+     * @param version the target Java release, or {@code null} for the base version
+     * @param directory the directory of the classes targeting the base Java release
+     * @param forceCreation whether to force a new <abbr>JAR</abbr> file even if the content seems unchanged
+     * @param logger where to send a warning if an error occurred while checking an existing <abbr>JAR</abbr> file
+     */
+    @SuppressWarnings("checkstyle:NeedBraces")
+    Archive(
+            final Path jarFile,
+            final String moduleName,
+            final Runtime.Version version,
+            final Path directory,
+            final boolean forceCreation,
+            final Log logger) {
+        this.jarFile = jarFile;
+        this.moduleName = moduleName;
+        filesetForRelease = new TreeMap<>((v1, v2) -> {
+            if (v1 == v2) return 0;
+            if (v1 == null) return -1;
+            if (v2 == null) return +1;
+            return v1.compareTo(v2);
+        });
+        filesetForRelease.put(version, new FileSet(directory));
+        if (!forceCreation && Files.isRegularFile(jarFile)) {
+            try {
+                existingJAR = new TimestampCheck(jarFile, directory, logger);
+            } catch (IOException e) {
+                // Ignore, we will regenerate the JAR file.
+                logger.warn(e);
+            }
+        }
+    }
+
+    /**
+     * {@return the files or directories to store in the <abbr>JAR</abbr> file for targeting the base Java release}
+     *
+     * @throws NoSuchElementException should not happen unless {@link #prune(boolean)} has been invoked
+     */
+    FileSet baseRelease() {
+        Map.Entry<Runtime.Version, FileSet> entry = filesetForRelease.firstEntry();
+        String message = null;
+        if (entry != null) {
+            Runtime.Version version = entry.getKey();
+            if (version == null) {
+                return entry.getValue();
+            }
+            message = "Expected base version but found version " + version;
+        }
+        throw new NoSuchElementException(message);
+    }
+
+    /**
+     * Returns the {@code module-info.class} files. Conceptually, there is at most once such file per module.

Review Comment:
   one such



##########
src/main/java/org/apache/maven/plugins/jar/Archive.java:
##########
@@ -0,0 +1,655 @@
+/*
+ * 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.jar;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.TreeMap;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.Type;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.MojoException;
+
+/**
+ * Files or root directories to archive for a single module.
+ * A single instance of {@code Archive} can contain many directories for different target Java releases.
+ * Many instances of {@code Archive} can exist when archiving a multi-modules project.
+ */
+final class Archive {
+    /**
+     * Path to the <abbr>POM</abbr> file generated for this archive, or {@code null} if none.
+     * This is non-null only if module source hierarchy is used, in which case the dependencies
+     * declared in this file are the intersection of the project dependencies and the content of
+     * the {@code module-info.class} file.
+     */
+    @Nullable
+    Path pomFile;
+
+    /**
+     * The <var>JAR</var> file to create. Can be an existing file,
+     * in which case the file creation can be skipped if the file is still up-to-date.
+     */
+    @Nonnull
+    final Path jarFile;
+
+    /**
+     * A helper class for checking whether an existing <abbr>JAR</abbr> file is still up-to-date.
+     * This is null if there is no existing JAR file, or if we determined that the file is outdated.
+     */
+    private TimestampCheck existingJAR;
+
+    /**
+     * Name of the module being archived when the project is using module hierarchy.
+     * This is {@code null} if the project is using package hierarchy, either because it is a classical
+     * class-path project or because it is a single module compiled without using the module hierarchy.
+     * When using module source hierarchy, {@code javac} guarantees that the module name in the output
+     * directory is the name of the parent directory of {@code module-info.class}.
+     */
+    @Nullable
+    final String moduleName;
+
+    /**
+     * Path to {@code META-INF/MANIFEST.MF}, or {@code null} if none.
+     * If non-null, this value will be given to the {@code --manifest} option.
+     * The use of this option is preferable to adding {@code MANIFEST.MF} as an ordinary file.
+     *
+     * @see #setManifest(Path, boolean)
+     * @see #mergeManifest(Path, Manifest)
+     */
+    @Nullable
+    private Path manifest;
+
+    /**
+     * The Maven generated {@code pom.xml} and {@code pom.properties} files, or {@code null} if none.
+     * This first item must be the base directory where the files are located.
+     */
+    @Nullable
+    List<Path> mavenFiles;
+
+    /**
+     * Fully-qualified name of the main class, or {@code null} if none.
+     * This is the value to provide to the {@code --main-class} option.
+     */
+    private String mainClass;
+
+    /**
+     * Files or root directories to store in the <abbr>JAR</abbr> file for each target Java release
+     * other than the base release. Keys are the target Java release with {@code null} for the base
+     * release.
+     */
+    @Nonnull
+    private final NavigableMap<Runtime.Version, FileSet> filesetForRelease;
+
+    /**
+     * Files or root directories to archive for a single target Java release of a single module.
+     * The {@link Archive} enclosing must contain at least one instance of {@code FileSet} for
+     * the base release, and an arbitrary amount of other instances for other target releases.
+     */
+    final class FileSet {
+        /**
+         * The root directory of all files or directories to archive.
+         * This is the value to pass to the {@code -C} tool option.
+         */
+        @Nonnull
+        final Path directory;
+
+        /**
+         * The files or directories to include in the <var>JAR</var> file.
+         * Can be absolute paths or paths relative to {@link #directory}.
+         * It usually contains only the files or directories directly in
+         * the root {@linkplain #directory}, not in sub-directories.
+         */
+        @Nonnull
+        final List<Path> files;
+
+        /**
+         * Creates an initially empty set of files or directories for a specific target Java release.
+         *
+         * @param directory the base directory of the files or directories to archive
+         */
+        private FileSet(Path directory) {
+            this.directory = directory;
+            this.files = new ArrayList<>();
+        }
+
+        /**
+         * 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.
+         * The caller should use that common directory for logging a warning message.
+         *
+         * @param base base directory found by previous invocations of this method, or {@code null} if none
+         * @return common directory of discarded files
+         */
+        private Path discardAllFiles(Path base) {
+            for (Path file : files) {
+                if (base == null) {
+                    base = file.getParent();
+                } else {
+                    while (!file.startsWith(base)) {
+                        base = base.getParent();
+                        if (base == null) {
+                            break;
+                        }
+                    }
+                }
+            }
+            files.clear();
+            return base;
+        }
+
+        /**
+         * Adds the given path to the list of files or directories to archive.
+         * If the given path is a directory, then all children will be included.
+         * Children to exclude, if any, should be managed by {@link ExcludedFiles}.
+         *
+         * @param item a file or directory to archive
+         * @param attributes the file's basic attributes
+         * @param isDirectory whether the file is a directory
+         */
+        void add(Path item, BasicFileAttributes attributes, boolean isDirectory) {
+            TimestampCheck tc = existingJAR;
+            if (tc != null && tc.isUpdated(item, attributes, isDirectory)) {
+                existingJAR = null; // Signal that the existing file is outdated.
+            }
+            files.add(item);
+        }
+
+        /**
+         * Adds to the given list the arguments to provide to the "jar" tool for this version.
+         * The elements added to the list will be instances of {@link String} or {@link Path}.
+         *
+         * <h4>Note about the {@code -C} option</h4>
+         * This method repeats the {@code -C} option before each file.
+         * Our tests suggest that the first file after the directory specified by the {@code -C} option must
+         * be relative to that directory and all files after the first one must be prefixed by the directory
+         * which was specified in the {@code -C} option. This behavior is not very intuitive and replying on
+         * it can be fragile. Furthermore, it seems that the relativized file needs to be the shortest one,
+         * otherwise the {@code jar} tool rejects files after the first one with "names do not match".
+         * Which file is first depends on the unspecified directory-iteration order.
+         * Repeating the {@code -C} option for each file seems safer.
+         *
+         * @param addTo the list to add the arguments as {@link String} or {@link Path} instances to
+         * @param version the target Java release, or {@code null} for the base version of the <abbr>JAR</abbr> file
+         * @throws IllegalArgumentException if a path cannot be made relative to the base directory
+         */
+        private void arguments(List<Object> addTo, Runtime.Version version) {
+            if (files.isEmpty()) {
+                return;
+            }
+            if (version != null) {
+                addTo.add("--release");
+                addTo.add(version);
+            }
+            Path previous = null;
+            for (Path file : files) {
+                if (previous != null && file.startsWith(previous)) {
+                    // Already added a parent directory.
+                    continue;
+                }
+                previous = file;
+                file = directory.relativize(file);
+                if (file.getNameCount() <= 1 && file.toString().isEmpty()) {
+                    /*
+                     * The `-C` directory itself (e.g. a "META-INF/versions/<n>" directory added as a whole).
+                     * An empty file argument is invalid for the `jar` tool (some implementations reject it,
+                     * others silently misbehave), so archive the whole directory content with ".".
+                     */
+                    file = Path.of(".");
+                }
+                addTo.add("-C");
+                addTo.add(directory);
+                addTo.add(file);
+            }
+        }
+
+        /**
+         * {@return a string representation for debugging purposes}
+         */
+        @Override
+        public String toString() {
+            return getClass().getSimpleName() + '[' + directory.getFileName() + ": " + files.size() + " files]";
+        }
+    }
+
+    /**
+     * Creates an initially empty set of files or directories.
+     *
+     * @param jarFile path to the <abbr>JAR</abbr> file to create
+     * @param moduleName the module name if using module hierarchy, or {@code null} if using package hierarchy
+     * @param version the target Java release, or {@code null} for the base version
+     * @param directory the directory of the classes targeting the base Java release
+     * @param forceCreation whether to force a new <abbr>JAR</abbr> file even if the content seems unchanged
+     * @param logger where to send a warning if an error occurred while checking an existing <abbr>JAR</abbr> file
+     */
+    @SuppressWarnings("checkstyle:NeedBraces")
+    Archive(
+            final Path jarFile,
+            final String moduleName,
+            final Runtime.Version version,
+            final Path directory,
+            final boolean forceCreation,
+            final Log logger) {
+        this.jarFile = jarFile;
+        this.moduleName = moduleName;
+        filesetForRelease = new TreeMap<>((v1, v2) -> {
+            if (v1 == v2) return 0;
+            if (v1 == null) return -1;
+            if (v2 == null) return +1;
+            return v1.compareTo(v2);
+        });
+        filesetForRelease.put(version, new FileSet(directory));
+        if (!forceCreation && Files.isRegularFile(jarFile)) {
+            try {
+                existingJAR = new TimestampCheck(jarFile, directory, logger);
+            } catch (IOException e) {
+                // Ignore, we will regenerate the JAR file.
+                logger.warn(e);
+            }
+        }
+    }
+
+    /**
+     * {@return the files or directories to store in the <abbr>JAR</abbr> file for targeting the base Java release}
+     *
+     * @throws NoSuchElementException should not happen unless {@link #prune(boolean)} has been invoked
+     */
+    FileSet baseRelease() {
+        Map.Entry<Runtime.Version, FileSet> entry = filesetForRelease.firstEntry();
+        String message = null;
+        if (entry != null) {
+            Runtime.Version version = entry.getKey();
+            if (version == null) {
+                return entry.getValue();
+            }
+            message = "Expected base version but found version " + version;
+        }
+        throw new NoSuchElementException(message);
+    }
+
+    /**
+     * Returns the {@code module-info.class} files. Conceptually, there is at most once such file per module.
+     * However, more than one file can exist if additional files are provided for additional Java releases.
+     * This method returns only the files that exist.
+     *
+     * @return all {@code module-info.class} files found for all target Java releases
+     */
+    public List<Path> moduleInfoFiles() {
+        var files = new ArrayList<Path>();
+        filesetForRelease.values().forEach((release) -> {
+            Path file = release.directory.resolve(FileCollector.MODULE_DESCRIPTOR_FILE_NAME);
+            if (Files.isRegularFile(file)) {
+                files.add(file);
+            }
+        });
+        return files;
+    }
+
+    /**
+     * Discards all files in this archive, normally because those files are not in any module.
+     * This method returns a common parent directory for all the files that were discarded.
+     * The caller should use that common directory for logging a warning message.
+     *
+     * @return common directory of discarded files, or {@code null} if none
+     */
+    Path discardAllFiles() {
+        Path base = null;
+        for (FileSet release : filesetForRelease.values()) {
+            base = release.discardAllFiles(base);
+        }
+        filesetForRelease.clear();
+        return base;
+    }
+
+    /**
+     * Removes all empty file sets 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}, then this method ensures that at least one file set
+     * remains even if that file set is empty.
+     *
+     * @param skipIfEmpty value of {@link AbstractJarMojo#skipIfEmpty}
+     */
+    public void prune(final boolean skipIfEmpty) {
+        FileSet keep = (skipIfEmpty || isEmpty())
+                ? null
+                : filesetForRelease.firstEntry().getValue();
+        filesetForRelease.values().removeIf((fs) -> fs.files.isEmpty());
+        Iterator<Map.Entry<Runtime.Version, FileSet>> it =
+                filesetForRelease.entrySet().iterator();
+        if (it.hasNext()) {
+            Map.Entry<Runtime.Version, FileSet> first = it.next();
+            if (first.getKey() == null) {
+                return; // Already contains an entry for the base version, nothing to do.
+            }
+            keep = first.getValue();
+            it.remove();
+        }
+        if (keep != null) {
+            filesetForRelease.put(null, keep);
+        }
+    }
+
+    /**
+     * {@return whether this archive has nothing to archive}
+     * This method can return {@code false} even when there is zero file to archive.
+     * It can happen if {@link AbstractJarMojo#skipIfEmpty} is {@code false}. In such case, the
+     * "empty" <abbr>JAR</abbr> file will still contain at {@code META-INF/MANIFEST.MF} file.
+     *
+     * <h4>Prerequisites</h4>

Review Comment:
   I'd drop the heading completely here



##########
src/main/java/org/apache/maven/plugins/jar/Archive.java:
##########
@@ -0,0 +1,655 @@
+/*
+ * 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.jar;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.TreeMap;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.Type;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.MojoException;
+
+/**
+ * Files or root directories to archive for a single module.
+ * A single instance of {@code Archive} can contain many directories for different target Java releases.
+ * Many instances of {@code Archive} can exist when archiving a multi-modules project.
+ */
+final class Archive {
+    /**
+     * Path to the <abbr>POM</abbr> file generated for this archive, or {@code null} if none.
+     * This is non-null only if module source hierarchy is used, in which case the dependencies
+     * declared in this file are the intersection of the project dependencies and the content of
+     * the {@code module-info.class} file.
+     */
+    @Nullable
+    Path pomFile;
+
+    /**
+     * The <var>JAR</var> file to create. Can be an existing file,
+     * in which case the file creation can be skipped if the file is still up-to-date.
+     */
+    @Nonnull
+    final Path jarFile;
+
+    /**
+     * A helper class for checking whether an existing <abbr>JAR</abbr> file is still up-to-date.
+     * This is null if there is no existing JAR file, or if we determined that the file is outdated.
+     */
+    private TimestampCheck existingJAR;
+
+    /**
+     * Name of the module being archived when the project is using module hierarchy.
+     * This is {@code null} if the project is using package hierarchy, either because it is a classical
+     * class-path project or because it is a single module compiled without using the module hierarchy.
+     * When using module source hierarchy, {@code javac} guarantees that the module name in the output
+     * directory is the name of the parent directory of {@code module-info.class}.
+     */
+    @Nullable
+    final String moduleName;
+
+    /**
+     * Path to {@code META-INF/MANIFEST.MF}, or {@code null} if none.
+     * If non-null, this value will be given to the {@code --manifest} option.
+     * The use of this option is preferable to adding {@code MANIFEST.MF} as an ordinary file.
+     *
+     * @see #setManifest(Path, boolean)
+     * @see #mergeManifest(Path, Manifest)
+     */
+    @Nullable
+    private Path manifest;
+
+    /**
+     * The Maven generated {@code pom.xml} and {@code pom.properties} files, or {@code null} if none.
+     * This first item must be the base directory where the files are located.
+     */
+    @Nullable
+    List<Path> mavenFiles;
+
+    /**
+     * Fully-qualified name of the main class, or {@code null} if none.
+     * This is the value to provide to the {@code --main-class} option.
+     */
+    private String mainClass;
+
+    /**
+     * Files or root directories to store in the <abbr>JAR</abbr> file for each target Java release
+     * other than the base release. Keys are the target Java release with {@code null} for the base
+     * release.
+     */
+    @Nonnull
+    private final NavigableMap<Runtime.Version, FileSet> filesetForRelease;
+
+    /**
+     * Files or root directories to archive for a single target Java release of a single module.
+     * The {@link Archive} enclosing must contain at least one instance of {@code FileSet} for
+     * the base release, and an arbitrary amount of other instances for other target releases.
+     */
+    final class FileSet {
+        /**
+         * The root directory of all files or directories to archive.
+         * This is the value to pass to the {@code -C} tool option.
+         */
+        @Nonnull
+        final Path directory;
+
+        /**
+         * The files or directories to include in the <var>JAR</var> file.
+         * Can be absolute paths or paths relative to {@link #directory}.
+         * It usually contains only the files or directories directly in
+         * the root {@linkplain #directory}, not in sub-directories.
+         */
+        @Nonnull
+        final List<Path> files;
+
+        /**
+         * Creates an initially empty set of files or directories for a specific target Java release.
+         *
+         * @param directory the base directory of the files or directories to archive
+         */
+        private FileSet(Path directory) {
+            this.directory = directory;
+            this.files = new ArrayList<>();
+        }
+
+        /**
+         * 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.
+         * The caller should use that common directory for logging a warning message.
+         *
+         * @param base base directory found by previous invocations of this method, or {@code null} if none
+         * @return common directory of discarded files
+         */
+        private Path discardAllFiles(Path base) {
+            for (Path file : files) {
+                if (base == null) {
+                    base = file.getParent();
+                } else {
+                    while (!file.startsWith(base)) {
+                        base = base.getParent();
+                        if (base == null) {
+                            break;
+                        }
+                    }
+                }
+            }
+            files.clear();
+            return base;
+        }
+
+        /**
+         * Adds the given path to the list of files or directories to archive.
+         * If the given path is a directory, then all children will be included.
+         * Children to exclude, if any, should be managed by {@link ExcludedFiles}.
+         *
+         * @param item a file or directory to archive
+         * @param attributes the file's basic attributes
+         * @param isDirectory whether the file is a directory
+         */
+        void add(Path item, BasicFileAttributes attributes, boolean isDirectory) {
+            TimestampCheck tc = existingJAR;
+            if (tc != null && tc.isUpdated(item, attributes, isDirectory)) {
+                existingJAR = null; // Signal that the existing file is outdated.
+            }
+            files.add(item);
+        }
+
+        /**
+         * Adds to the given list the arguments to provide to the "jar" tool for this version.
+         * The elements added to the list will be instances of {@link String} or {@link Path}.
+         *
+         * <h4>Note about the {@code -C} option</h4>
+         * This method repeats the {@code -C} option before each file.
+         * Our tests suggest that the first file after the directory specified by the {@code -C} option must
+         * be relative to that directory and all files after the first one must be prefixed by the directory
+         * which was specified in the {@code -C} option. This behavior is not very intuitive and replying on
+         * it can be fragile. Furthermore, it seems that the relativized file needs to be the shortest one,
+         * otherwise the {@code jar} tool rejects files after the first one with "names do not match".
+         * Which file is first depends on the unspecified directory-iteration order.
+         * Repeating the {@code -C} option for each file seems safer.
+         *
+         * @param addTo the list to add the arguments as {@link String} or {@link Path} instances to
+         * @param version the target Java release, or {@code null} for the base version of the <abbr>JAR</abbr> file
+         * @throws IllegalArgumentException if a path cannot be made relative to the base directory
+         */
+        private void arguments(List<Object> addTo, Runtime.Version version) {
+            if (files.isEmpty()) {
+                return;
+            }
+            if (version != null) {
+                addTo.add("--release");
+                addTo.add(version);
+            }
+            Path previous = null;
+            for (Path file : files) {
+                if (previous != null && file.startsWith(previous)) {
+                    // Already added a parent directory.
+                    continue;
+                }
+                previous = file;
+                file = directory.relativize(file);
+                if (file.getNameCount() <= 1 && file.toString().isEmpty()) {
+                    /*
+                     * The `-C` directory itself (e.g. a "META-INF/versions/<n>" directory added as a whole).
+                     * An empty file argument is invalid for the `jar` tool (some implementations reject it,
+                     * others silently misbehave), so archive the whole directory content with ".".
+                     */
+                    file = Path.of(".");
+                }
+                addTo.add("-C");
+                addTo.add(directory);
+                addTo.add(file);
+            }
+        }
+
+        /**
+         * {@return a string representation for debugging purposes}
+         */
+        @Override
+        public String toString() {
+            return getClass().getSimpleName() + '[' + directory.getFileName() + ": " + files.size() + " files]";
+        }
+    }
+
+    /**
+     * Creates an initially empty set of files or directories.
+     *
+     * @param jarFile path to the <abbr>JAR</abbr> file to create
+     * @param moduleName the module name if using module hierarchy, or {@code null} if using package hierarchy
+     * @param version the target Java release, or {@code null} for the base version
+     * @param directory the directory of the classes targeting the base Java release
+     * @param forceCreation whether to force a new <abbr>JAR</abbr> file even if the content seems unchanged
+     * @param logger where to send a warning if an error occurred while checking an existing <abbr>JAR</abbr> file
+     */
+    @SuppressWarnings("checkstyle:NeedBraces")
+    Archive(
+            final Path jarFile,
+            final String moduleName,
+            final Runtime.Version version,
+            final Path directory,
+            final boolean forceCreation,
+            final Log logger) {
+        this.jarFile = jarFile;
+        this.moduleName = moduleName;
+        filesetForRelease = new TreeMap<>((v1, v2) -> {
+            if (v1 == v2) return 0;
+            if (v1 == null) return -1;
+            if (v2 == null) return +1;
+            return v1.compareTo(v2);
+        });
+        filesetForRelease.put(version, new FileSet(directory));
+        if (!forceCreation && Files.isRegularFile(jarFile)) {
+            try {
+                existingJAR = new TimestampCheck(jarFile, directory, logger);
+            } catch (IOException e) {
+                // Ignore, we will regenerate the JAR file.
+                logger.warn(e);
+            }
+        }
+    }
+
+    /**
+     * {@return the files or directories to store in the <abbr>JAR</abbr> file for targeting the base Java release}
+     *
+     * @throws NoSuchElementException should not happen unless {@link #prune(boolean)} has been invoked
+     */
+    FileSet baseRelease() {
+        Map.Entry<Runtime.Version, FileSet> entry = filesetForRelease.firstEntry();
+        String message = null;
+        if (entry != null) {
+            Runtime.Version version = entry.getKey();
+            if (version == null) {
+                return entry.getValue();
+            }
+            message = "Expected base version but found version " + version;
+        }
+        throw new NoSuchElementException(message);
+    }
+
+    /**
+     * Returns the {@code module-info.class} files. Conceptually, there is at most once such file per module.
+     * However, more than one file can exist if additional files are provided for additional Java releases.
+     * This method returns only the files that exist.
+     *
+     * @return all {@code module-info.class} files found for all target Java releases
+     */
+    public List<Path> moduleInfoFiles() {
+        var files = new ArrayList<Path>();
+        filesetForRelease.values().forEach((release) -> {
+            Path file = release.directory.resolve(FileCollector.MODULE_DESCRIPTOR_FILE_NAME);
+            if (Files.isRegularFile(file)) {
+                files.add(file);
+            }
+        });
+        return files;
+    }
+
+    /**
+     * Discards all files in this archive, normally because those files are not in any module.
+     * This method returns a common parent directory for all the files that were discarded.
+     * The caller should use that common directory for logging a warning message.
+     *
+     * @return common directory of discarded files, or {@code null} if none
+     */
+    Path discardAllFiles() {
+        Path base = null;
+        for (FileSet release : filesetForRelease.values()) {
+            base = release.discardAllFiles(base);
+        }
+        filesetForRelease.clear();
+        return base;
+    }
+
+    /**
+     * Removes all empty file sets 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}, then this method ensures that at least one file set
+     * remains even if that file set is empty.
+     *
+     * @param skipIfEmpty value of {@link AbstractJarMojo#skipIfEmpty}
+     */
+    public void prune(final boolean skipIfEmpty) {
+        FileSet keep = (skipIfEmpty || isEmpty())
+                ? null
+                : filesetForRelease.firstEntry().getValue();
+        filesetForRelease.values().removeIf((fs) -> fs.files.isEmpty());
+        Iterator<Map.Entry<Runtime.Version, FileSet>> it =
+                filesetForRelease.entrySet().iterator();
+        if (it.hasNext()) {
+            Map.Entry<Runtime.Version, FileSet> first = it.next();
+            if (first.getKey() == null) {
+                return; // Already contains an entry for the base version, nothing to do.
+            }
+            keep = first.getValue();
+            it.remove();
+        }
+        if (keep != null) {
+            filesetForRelease.put(null, keep);
+        }
+    }
+
+    /**
+     * {@return whether this archive has nothing to archive}
+     * This method can return {@code false} even when there is zero file to archive.

Review Comment:
   there are no files to archive



##########
src/main/java/org/apache/maven/plugins/jar/Archive.java:
##########
@@ -0,0 +1,655 @@
+/*
+ * 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.jar;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.TreeMap;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.Type;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.MojoException;
+
+/**
+ * Files or root directories to archive for a single module.
+ * A single instance of {@code Archive} can contain many directories for different target Java releases.
+ * Many instances of {@code Archive} can exist when archiving a multi-modules project.
+ */
+final class Archive {
+    /**
+     * Path to the <abbr>POM</abbr> file generated for this archive, or {@code null} if none.
+     * This is non-null only if module source hierarchy is used, in which case the dependencies
+     * declared in this file are the intersection of the project dependencies and the content of
+     * the {@code module-info.class} file.
+     */
+    @Nullable
+    Path pomFile;
+
+    /**
+     * The <var>JAR</var> file to create. Can be an existing file,
+     * in which case the file creation can be skipped if the file is still up-to-date.
+     */
+    @Nonnull
+    final Path jarFile;
+
+    /**
+     * A helper class for checking whether an existing <abbr>JAR</abbr> file is still up-to-date.
+     * This is null if there is no existing JAR file, or if we determined that the file is outdated.
+     */
+    private TimestampCheck existingJAR;
+
+    /**
+     * Name of the module being archived when the project is using module hierarchy.
+     * This is {@code null} if the project is using package hierarchy, either because it is a classical
+     * class-path project or because it is a single module compiled without using the module hierarchy.
+     * When using module source hierarchy, {@code javac} guarantees that the module name in the output
+     * directory is the name of the parent directory of {@code module-info.class}.
+     */
+    @Nullable
+    final String moduleName;
+
+    /**
+     * Path to {@code META-INF/MANIFEST.MF}, or {@code null} if none.
+     * If non-null, this value will be given to the {@code --manifest} option.
+     * The use of this option is preferable to adding {@code MANIFEST.MF} as an ordinary file.
+     *
+     * @see #setManifest(Path, boolean)
+     * @see #mergeManifest(Path, Manifest)
+     */
+    @Nullable
+    private Path manifest;
+
+    /**
+     * The Maven generated {@code pom.xml} and {@code pom.properties} files, or {@code null} if none.
+     * This first item must be the base directory where the files are located.
+     */
+    @Nullable
+    List<Path> mavenFiles;
+
+    /**
+     * Fully-qualified name of the main class, or {@code null} if none.
+     * This is the value to provide to the {@code --main-class} option.
+     */
+    private String mainClass;
+
+    /**
+     * Files or root directories to store in the <abbr>JAR</abbr> file for each target Java release
+     * other than the base release. Keys are the target Java release with {@code null} for the base
+     * release.
+     */
+    @Nonnull
+    private final NavigableMap<Runtime.Version, FileSet> filesetForRelease;
+
+    /**
+     * Files or root directories to archive for a single target Java release of a single module.
+     * The {@link Archive} enclosing must contain at least one instance of {@code FileSet} for
+     * the base release, and an arbitrary amount of other instances for other target releases.
+     */
+    final class FileSet {
+        /**
+         * The root directory of all files or directories to archive.
+         * This is the value to pass to the {@code -C} tool option.
+         */
+        @Nonnull
+        final Path directory;
+
+        /**
+         * The files or directories to include in the <var>JAR</var> file.
+         * Can be absolute paths or paths relative to {@link #directory}.
+         * It usually contains only the files or directories directly in
+         * the root {@linkplain #directory}, not in sub-directories.
+         */
+        @Nonnull
+        final List<Path> files;
+
+        /**
+         * Creates an initially empty set of files or directories for a specific target Java release.
+         *
+         * @param directory the base directory of the files or directories to archive
+         */
+        private FileSet(Path directory) {
+            this.directory = directory;
+            this.files = new ArrayList<>();
+        }
+
+        /**
+         * 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.
+         * The caller should use that common directory for logging a warning message.
+         *
+         * @param base base directory found by previous invocations of this method, or {@code null} if none
+         * @return common directory of discarded files
+         */
+        private Path discardAllFiles(Path base) {
+            for (Path file : files) {
+                if (base == null) {
+                    base = file.getParent();
+                } else {
+                    while (!file.startsWith(base)) {
+                        base = base.getParent();
+                        if (base == null) {
+                            break;
+                        }
+                    }
+                }
+            }
+            files.clear();
+            return base;
+        }
+
+        /**
+         * Adds the given path to the list of files or directories to archive.
+         * If the given path is a directory, then all children will be included.
+         * Children to exclude, if any, should be managed by {@link ExcludedFiles}.
+         *
+         * @param item a file or directory to archive
+         * @param attributes the file's basic attributes
+         * @param isDirectory whether the file is a directory
+         */
+        void add(Path item, BasicFileAttributes attributes, boolean isDirectory) {
+            TimestampCheck tc = existingJAR;
+            if (tc != null && tc.isUpdated(item, attributes, isDirectory)) {
+                existingJAR = null; // Signal that the existing file is outdated.
+            }
+            files.add(item);
+        }
+
+        /**
+         * Adds to the given list the arguments to provide to the "jar" tool for this version.
+         * The elements added to the list will be instances of {@link String} or {@link Path}.
+         *
+         * <h4>Note about the {@code -C} option</h4>
+         * This method repeats the {@code -C} option before each file.
+         * Our tests suggest that the first file after the directory specified by the {@code -C} option must
+         * be relative to that directory and all files after the first one must be prefixed by the directory
+         * which was specified in the {@code -C} option. This behavior is not very intuitive and replying on
+         * it can be fragile. Furthermore, it seems that the relativized file needs to be the shortest one,
+         * otherwise the {@code jar} tool rejects files after the first one with "names do not match".
+         * Which file is first depends on the unspecified directory-iteration order.
+         * Repeating the {@code -C} option for each file seems safer.
+         *
+         * @param addTo the list to add the arguments as {@link String} or {@link Path} instances to
+         * @param version the target Java release, or {@code null} for the base version of the <abbr>JAR</abbr> file
+         * @throws IllegalArgumentException if a path cannot be made relative to the base directory
+         */
+        private void arguments(List<Object> addTo, Runtime.Version version) {
+            if (files.isEmpty()) {
+                return;
+            }
+            if (version != null) {
+                addTo.add("--release");
+                addTo.add(version);
+            }
+            Path previous = null;
+            for (Path file : files) {
+                if (previous != null && file.startsWith(previous)) {
+                    // Already added a parent directory.
+                    continue;
+                }
+                previous = file;
+                file = directory.relativize(file);
+                if (file.getNameCount() <= 1 && file.toString().isEmpty()) {
+                    /*
+                     * The `-C` directory itself (e.g. a "META-INF/versions/<n>" directory added as a whole).
+                     * An empty file argument is invalid for the `jar` tool (some implementations reject it,
+                     * others silently misbehave), so archive the whole directory content with ".".
+                     */
+                    file = Path.of(".");
+                }
+                addTo.add("-C");
+                addTo.add(directory);
+                addTo.add(file);
+            }
+        }
+
+        /**
+         * {@return a string representation for debugging purposes}
+         */
+        @Override
+        public String toString() {
+            return getClass().getSimpleName() + '[' + directory.getFileName() + ": " + files.size() + " files]";
+        }
+    }
+
+    /**
+     * Creates an initially empty set of files or directories.
+     *
+     * @param jarFile path to the <abbr>JAR</abbr> file to create
+     * @param moduleName the module name if using module hierarchy, or {@code null} if using package hierarchy
+     * @param version the target Java release, or {@code null} for the base version
+     * @param directory the directory of the classes targeting the base Java release
+     * @param forceCreation whether to force a new <abbr>JAR</abbr> file even if the content seems unchanged
+     * @param logger where to send a warning if an error occurred while checking an existing <abbr>JAR</abbr> file
+     */
+    @SuppressWarnings("checkstyle:NeedBraces")
+    Archive(
+            final Path jarFile,
+            final String moduleName,
+            final Runtime.Version version,
+            final Path directory,
+            final boolean forceCreation,
+            final Log logger) {
+        this.jarFile = jarFile;
+        this.moduleName = moduleName;
+        filesetForRelease = new TreeMap<>((v1, v2) -> {
+            if (v1 == v2) return 0;
+            if (v1 == null) return -1;
+            if (v2 == null) return +1;
+            return v1.compareTo(v2);
+        });
+        filesetForRelease.put(version, new FileSet(directory));
+        if (!forceCreation && Files.isRegularFile(jarFile)) {
+            try {
+                existingJAR = new TimestampCheck(jarFile, directory, logger);
+            } catch (IOException e) {
+                // Ignore, we will regenerate the JAR file.
+                logger.warn(e);
+            }
+        }
+    }
+
+    /**
+     * {@return the files or directories to store in the <abbr>JAR</abbr> file for targeting the base Java release}
+     *
+     * @throws NoSuchElementException should not happen unless {@link #prune(boolean)} has been invoked
+     */
+    FileSet baseRelease() {
+        Map.Entry<Runtime.Version, FileSet> entry = filesetForRelease.firstEntry();
+        String message = null;
+        if (entry != null) {
+            Runtime.Version version = entry.getKey();
+            if (version == null) {
+                return entry.getValue();
+            }
+            message = "Expected base version but found version " + version;
+        }
+        throw new NoSuchElementException(message);
+    }
+
+    /**
+     * Returns the {@code module-info.class} files. Conceptually, there is at most once such file per module.
+     * However, more than one file can exist if additional files are provided for additional Java releases.
+     * This method returns only the files that exist.
+     *
+     * @return all {@code module-info.class} files found for all target Java releases
+     */
+    public List<Path> moduleInfoFiles() {
+        var files = new ArrayList<Path>();
+        filesetForRelease.values().forEach((release) -> {
+            Path file = release.directory.resolve(FileCollector.MODULE_DESCRIPTOR_FILE_NAME);
+            if (Files.isRegularFile(file)) {
+                files.add(file);
+            }
+        });
+        return files;
+    }
+
+    /**
+     * Discards all files in this archive, normally because those files are not in any module.
+     * This method returns a common parent directory for all the files that were discarded.
+     * The caller should use that common directory for logging a warning message.
+     *
+     * @return common directory of discarded files, or {@code null} if none
+     */
+    Path discardAllFiles() {
+        Path base = null;
+        for (FileSet release : filesetForRelease.values()) {
+            base = release.discardAllFiles(base);
+        }
+        filesetForRelease.clear();
+        return base;
+    }
+
+    /**
+     * Removes all empty file sets 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}, then this method ensures that at least one file set
+     * remains even if that file set is empty.
+     *
+     * @param skipIfEmpty value of {@link AbstractJarMojo#skipIfEmpty}
+     */
+    public void prune(final boolean skipIfEmpty) {
+        FileSet keep = (skipIfEmpty || isEmpty())
+                ? null
+                : filesetForRelease.firstEntry().getValue();
+        filesetForRelease.values().removeIf((fs) -> fs.files.isEmpty());
+        Iterator<Map.Entry<Runtime.Version, FileSet>> it =
+                filesetForRelease.entrySet().iterator();
+        if (it.hasNext()) {
+            Map.Entry<Runtime.Version, FileSet> first = it.next();
+            if (first.getKey() == null) {
+                return; // Already contains an entry for the base version, nothing to do.
+            }
+            keep = first.getValue();
+            it.remove();
+        }
+        if (keep != null) {
+            filesetForRelease.put(null, keep);
+        }
+    }
+
+    /**
+     * {@return whether this archive has nothing to archive}
+     * This method can return {@code false} even when there is zero file to archive.
+     * It can happen if {@link AbstractJarMojo#skipIfEmpty} is {@code false}. In such case, the
+     * "empty" <abbr>JAR</abbr> file will still contain at {@code META-INF/MANIFEST.MF} file.
+     *
+     * <h4>Prerequisites</h4>
+     * The {@link #prune(boolean)} method should be invoked before this method for accurate result.
+     */
+    public boolean isEmpty() {
+        return filesetForRelease.isEmpty();
+    }
+
+    /**
+     * Checks whether the <abbr>JAR</abbr> file already exists and can be reused.
+     * This method verifies that the <abbr>JAR</abbr> file contains all the files to archive,
+     * contains no extra file, and no file to archive is newer than the <abbr>JAR</abbr> file.

Review Comment:
   no extra files



##########
src/main/java/org/apache/maven/plugins/jar/ExcludedFiles.java:
##########
@@ -0,0 +1,145 @@
+/*
+ * 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.jar;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardCopyOption;
+import java.util.List;
+
+/**
+ * A list of files to temporarily move outside the directory to package in a <abbr>JAR</abbr> archive.
+ * This is used for excluding files from the <abbr>JAR</abbr> archive according to include/exclude filters.
+ * We move these files for making possible to specify the whole directory to the {@code jar} tool.
+ * This approach is used instead of enumerating files in arguments given to the {@code jar} tool because
+ * such enumeration can not contain directory entries (otherwise the whole directory would be included).
+ * Some software such as Spring applications component scan relies on the presence of directory entries.

Review Comment:
   This sentence is unclear, rephrase



##########
src/main/java/org/apache/maven/plugins/jar/Archive.java:
##########
@@ -0,0 +1,655 @@
+/*
+ * 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.jar;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.TreeMap;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.Type;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.MojoException;
+
+/**
+ * Files or root directories to archive for a single module.
+ * A single instance of {@code Archive} can contain many directories for different target Java releases.
+ * Many instances of {@code Archive} can exist when archiving a multi-modules project.
+ */
+final class Archive {
+    /**
+     * Path to the <abbr>POM</abbr> file generated for this archive, or {@code null} if none.
+     * This is non-null only if module source hierarchy is used, in which case the dependencies
+     * declared in this file are the intersection of the project dependencies and the content of
+     * the {@code module-info.class} file.
+     */
+    @Nullable
+    Path pomFile;
+
+    /**
+     * The <var>JAR</var> file to create. Can be an existing file,
+     * in which case the file creation can be skipped if the file is still up-to-date.
+     */
+    @Nonnull
+    final Path jarFile;
+
+    /**
+     * A helper class for checking whether an existing <abbr>JAR</abbr> file is still up-to-date.
+     * This is null if there is no existing JAR file, or if we determined that the file is outdated.
+     */
+    private TimestampCheck existingJAR;
+
+    /**
+     * Name of the module being archived when the project is using module hierarchy.
+     * This is {@code null} if the project is using package hierarchy, either because it is a classical
+     * class-path project or because it is a single module compiled without using the module hierarchy.
+     * When using module source hierarchy, {@code javac} guarantees that the module name in the output
+     * directory is the name of the parent directory of {@code module-info.class}.
+     */
+    @Nullable
+    final String moduleName;
+
+    /**
+     * Path to {@code META-INF/MANIFEST.MF}, or {@code null} if none.
+     * If non-null, this value will be given to the {@code --manifest} option.
+     * The use of this option is preferable to adding {@code MANIFEST.MF} as an ordinary file.
+     *
+     * @see #setManifest(Path, boolean)
+     * @see #mergeManifest(Path, Manifest)
+     */
+    @Nullable
+    private Path manifest;
+
+    /**
+     * The Maven generated {@code pom.xml} and {@code pom.properties} files, or {@code null} if none.
+     * This first item must be the base directory where the files are located.
+     */
+    @Nullable
+    List<Path> mavenFiles;
+
+    /**
+     * Fully-qualified name of the main class, or {@code null} if none.
+     * This is the value to provide to the {@code --main-class} option.
+     */
+    private String mainClass;
+
+    /**
+     * Files or root directories to store in the <abbr>JAR</abbr> file for each target Java release
+     * other than the base release. Keys are the target Java release with {@code null} for the base
+     * release.
+     */
+    @Nonnull
+    private final NavigableMap<Runtime.Version, FileSet> filesetForRelease;
+
+    /**
+     * Files or root directories to archive for a single target Java release of a single module.
+     * The {@link Archive} enclosing must contain at least one instance of {@code FileSet} for
+     * the base release, and an arbitrary amount of other instances for other target releases.
+     */
+    final class FileSet {
+        /**
+         * The root directory of all files or directories to archive.
+         * This is the value to pass to the {@code -C} tool option.
+         */
+        @Nonnull
+        final Path directory;
+
+        /**
+         * The files or directories to include in the <var>JAR</var> file.
+         * Can be absolute paths or paths relative to {@link #directory}.
+         * It usually contains only the files or directories directly in
+         * the root {@linkplain #directory}, not in sub-directories.
+         */
+        @Nonnull
+        final List<Path> files;
+
+        /**
+         * Creates an initially empty set of files or directories for a specific target Java release.
+         *
+         * @param directory the base directory of the files or directories to archive
+         */
+        private FileSet(Path directory) {
+            this.directory = directory;
+            this.files = new ArrayList<>();
+        }
+
+        /**
+         * 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.
+         * The caller should use that common directory for logging a warning message.
+         *
+         * @param base base directory found by previous invocations of this method, or {@code null} if none
+         * @return common directory of discarded files
+         */
+        private Path discardAllFiles(Path base) {
+            for (Path file : files) {
+                if (base == null) {
+                    base = file.getParent();
+                } else {
+                    while (!file.startsWith(base)) {
+                        base = base.getParent();
+                        if (base == null) {
+                            break;
+                        }
+                    }
+                }
+            }
+            files.clear();
+            return base;
+        }
+
+        /**
+         * Adds the given path to the list of files or directories to archive.
+         * If the given path is a directory, then all children will be included.
+         * Children to exclude, if any, should be managed by {@link ExcludedFiles}.
+         *
+         * @param item a file or directory to archive
+         * @param attributes the file's basic attributes
+         * @param isDirectory whether the file is a directory
+         */
+        void add(Path item, BasicFileAttributes attributes, boolean isDirectory) {
+            TimestampCheck tc = existingJAR;
+            if (tc != null && tc.isUpdated(item, attributes, isDirectory)) {
+                existingJAR = null; // Signal that the existing file is outdated.
+            }
+            files.add(item);
+        }
+
+        /**
+         * Adds to the given list the arguments to provide to the "jar" tool for this version.
+         * The elements added to the list will be instances of {@link String} or {@link Path}.
+         *
+         * <h4>Note about the {@code -C} option</h4>
+         * This method repeats the {@code -C} option before each file.
+         * Our tests suggest that the first file after the directory specified by the {@code -C} option must
+         * be relative to that directory and all files after the first one must be prefixed by the directory
+         * which was specified in the {@code -C} option. This behavior is not very intuitive and replying on
+         * it can be fragile. Furthermore, it seems that the relativized file needs to be the shortest one,
+         * otherwise the {@code jar} tool rejects files after the first one with "names do not match".
+         * Which file is first depends on the unspecified directory-iteration order.
+         * Repeating the {@code -C} option for each file seems safer.
+         *
+         * @param addTo the list to add the arguments as {@link String} or {@link Path} instances to
+         * @param version the target Java release, or {@code null} for the base version of the <abbr>JAR</abbr> file
+         * @throws IllegalArgumentException if a path cannot be made relative to the base directory
+         */
+        private void arguments(List<Object> addTo, Runtime.Version version) {
+            if (files.isEmpty()) {
+                return;
+            }
+            if (version != null) {
+                addTo.add("--release");
+                addTo.add(version);
+            }
+            Path previous = null;
+            for (Path file : files) {
+                if (previous != null && file.startsWith(previous)) {
+                    // Already added a parent directory.
+                    continue;
+                }
+                previous = file;
+                file = directory.relativize(file);
+                if (file.getNameCount() <= 1 && file.toString().isEmpty()) {
+                    /*
+                     * The `-C` directory itself (e.g. a "META-INF/versions/<n>" directory added as a whole).
+                     * An empty file argument is invalid for the `jar` tool (some implementations reject it,
+                     * others silently misbehave), so archive the whole directory content with ".".
+                     */
+                    file = Path.of(".");
+                }
+                addTo.add("-C");
+                addTo.add(directory);
+                addTo.add(file);
+            }
+        }
+
+        /**
+         * {@return a string representation for debugging purposes}
+         */
+        @Override
+        public String toString() {
+            return getClass().getSimpleName() + '[' + directory.getFileName() + ": " + files.size() + " files]";
+        }
+    }
+
+    /**
+     * Creates an initially empty set of files or directories.
+     *
+     * @param jarFile path to the <abbr>JAR</abbr> file to create
+     * @param moduleName the module name if using module hierarchy, or {@code null} if using package hierarchy
+     * @param version the target Java release, or {@code null} for the base version
+     * @param directory the directory of the classes targeting the base Java release
+     * @param forceCreation whether to force a new <abbr>JAR</abbr> file even if the content seems unchanged
+     * @param logger where to send a warning if an error occurred while checking an existing <abbr>JAR</abbr> file
+     */
+    @SuppressWarnings("checkstyle:NeedBraces")
+    Archive(
+            final Path jarFile,
+            final String moduleName,
+            final Runtime.Version version,
+            final Path directory,
+            final boolean forceCreation,
+            final Log logger) {
+        this.jarFile = jarFile;
+        this.moduleName = moduleName;
+        filesetForRelease = new TreeMap<>((v1, v2) -> {
+            if (v1 == v2) return 0;
+            if (v1 == null) return -1;
+            if (v2 == null) return +1;
+            return v1.compareTo(v2);
+        });
+        filesetForRelease.put(version, new FileSet(directory));
+        if (!forceCreation && Files.isRegularFile(jarFile)) {
+            try {
+                existingJAR = new TimestampCheck(jarFile, directory, logger);
+            } catch (IOException e) {
+                // Ignore, we will regenerate the JAR file.
+                logger.warn(e);
+            }
+        }
+    }
+
+    /**
+     * {@return the files or directories to store in the <abbr>JAR</abbr> file for targeting the base Java release}
+     *
+     * @throws NoSuchElementException should not happen unless {@link #prune(boolean)} has been invoked
+     */
+    FileSet baseRelease() {
+        Map.Entry<Runtime.Version, FileSet> entry = filesetForRelease.firstEntry();
+        String message = null;
+        if (entry != null) {
+            Runtime.Version version = entry.getKey();
+            if (version == null) {
+                return entry.getValue();
+            }
+            message = "Expected base version but found version " + version;
+        }
+        throw new NoSuchElementException(message);
+    }
+
+    /**
+     * Returns the {@code module-info.class} files. Conceptually, there is at most once such file per module.
+     * However, more than one file can exist if additional files are provided for additional Java releases.
+     * This method returns only the files that exist.
+     *
+     * @return all {@code module-info.class} files found for all target Java releases
+     */
+    public List<Path> moduleInfoFiles() {
+        var files = new ArrayList<Path>();
+        filesetForRelease.values().forEach((release) -> {
+            Path file = release.directory.resolve(FileCollector.MODULE_DESCRIPTOR_FILE_NAME);
+            if (Files.isRegularFile(file)) {
+                files.add(file);
+            }
+        });
+        return files;
+    }
+
+    /**
+     * Discards all files in this archive, normally because those files are not in any module.
+     * This method returns a common parent directory for all the files that were discarded.
+     * The caller should use that common directory for logging a warning message.
+     *
+     * @return common directory of discarded files, or {@code null} if none
+     */
+    Path discardAllFiles() {
+        Path base = null;
+        for (FileSet release : filesetForRelease.values()) {
+            base = release.discardAllFiles(base);
+        }
+        filesetForRelease.clear();
+        return base;
+    }
+
+    /**
+     * Removes all empty file sets 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}, then this method ensures that at least one file set
+     * remains even if that file set is empty.
+     *
+     * @param skipIfEmpty value of {@link AbstractJarMojo#skipIfEmpty}
+     */
+    public void prune(final boolean skipIfEmpty) {
+        FileSet keep = (skipIfEmpty || isEmpty())
+                ? null
+                : filesetForRelease.firstEntry().getValue();
+        filesetForRelease.values().removeIf((fs) -> fs.files.isEmpty());
+        Iterator<Map.Entry<Runtime.Version, FileSet>> it =
+                filesetForRelease.entrySet().iterator();
+        if (it.hasNext()) {
+            Map.Entry<Runtime.Version, FileSet> first = it.next();
+            if (first.getKey() == null) {
+                return; // Already contains an entry for the base version, nothing to do.
+            }
+            keep = first.getValue();
+            it.remove();
+        }
+        if (keep != null) {
+            filesetForRelease.put(null, keep);
+        }
+    }
+
+    /**
+     * {@return whether this archive has nothing to archive}
+     * This method can return {@code false} even when there is zero file to archive.
+     * It can happen if {@link AbstractJarMojo#skipIfEmpty} is {@code false}. In such case, the
+     * "empty" <abbr>JAR</abbr> file will still contain at {@code META-INF/MANIFEST.MF} file.
+     *
+     * <h4>Prerequisites</h4>
+     * The {@link #prune(boolean)} method should be invoked before this method for accurate result.
+     */
+    public boolean isEmpty() {
+        return filesetForRelease.isEmpty();
+    }
+
+    /**
+     * Checks whether the <abbr>JAR</abbr> file already exists and can be reused.
+     * This method verifies that the <abbr>JAR</abbr> file contains all the files to archive,
+     * contains no extra file, and no file to archive is newer than the <abbr>JAR</abbr> file.
+     *
+     * <p>This method can be invoked only once.
+     * If invoked more often, it returns {@code false} on all subsequent invocations.</p>
+     *
+     * @return whether the <abbr>JAR</abbr> file already exists and can be reused
+     */
+    public boolean isUpToDateJAR() {
+        final TimestampCheck tc = existingJAR;
+        if (tc == null) {
+            return false;
+        }
+        existingJAR = null; // Let GC do its job.
+        return tc.isUpToDateJAR(filesetForRelease.values());
+    }
+
+    /**
+     * Returns an initially empty set of files or directories for the specified target Java release.
+     *
+     * @param directory the base directory of the files to archive
+     * @param version the target Java release, or {@code null} for the base version
+     * @return container where to declare files and directories to archive
+     */
+    FileSet newTargetRelease(Path directory, Runtime.Version version) {
+        return filesetForRelease.computeIfAbsent(version, (key) -> new FileSet(directory));
+    }
+
+    /**
+     * Sets the {@code --main-class} option to the value of the {@code Main-Class} entry of the given manifest.
+     * As an extension, this method accepts the {@code module/classname} syntax (a syntax already used in some
+     * Java tools). If a module is specified, the main class is kept only if the module match. The intent is to
+     * allow users to specify on which module the main class applies when they use plugin configuration.
+     *
+     * <p>This method may modify the {@code content} manifest. Caller must ensure that the given manifest
+     * is not a shared instance. This method returns whether a change has actually been done.</p>
+     *
+     * @param content combination of existing {@code MANIFEST.MF} and manifest inferred from configuration, or null
+     * @return whether the given manifest has been modified by this method
+     */
+    boolean setMainClass(Manifest content) {
+        if (content == null || mainClass != null) {
+            return false;
+        }
+        // We need to remove the attribute, otherwise it will conflict with `--main-class`.
+        mainClass = (String) content.getMainAttributes().remove(Attributes.Name.MAIN_CLASS);
+        if (mainClass != null) {
+            int s = mainClass.indexOf('/');
+            if (s >= 0) {
+                if (mainClass.substring(0, s).strip().equals(moduleName)) {
+                    mainClass = mainClass.substring(s + 1).strip();
+                } else {
+                    mainClass = null; // Main class is defined for another module.
+                }
+            }
+        }
+        return mainClass != null;
+    }
+
+    /**
+     * Sets the {@code --manifest} option to the given value if that option was not already set.
+     *
+     * @param file path to the manifest file
+     * @param force whether to set the manifest even if already set
+     * @return whether the manifest has been set
+     */
+    boolean setManifest(Path file, boolean force) {
+        if (manifest == null || force) {
+            manifest = file;
+            return true;
+        }
+        return false;
+    }
+
+    /**
+     * Merges the manifest of this module with the manifest specified in plugin configuration.
+     * If both {@code file} and {@code content} are non-null, then {@code content} must be the
+     * result of reading {@code file}.
+     *
+     * <p>This method never modifies the given {@code content} object. If manifest are merged,

Review Comment:
   manifests



##########
src/main/java/org/apache/maven/plugins/jar/Archive.java:
##########
@@ -0,0 +1,655 @@
+/*
+ * 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.jar;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.TreeMap;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.Type;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.MojoException;
+
+/**
+ * Files or root directories to archive for a single module.
+ * A single instance of {@code Archive} can contain many directories for different target Java releases.
+ * Many instances of {@code Archive} can exist when archiving a multi-modules project.
+ */
+final class Archive {
+    /**
+     * Path to the <abbr>POM</abbr> file generated for this archive, or {@code null} if none.
+     * This is non-null only if module source hierarchy is used, in which case the dependencies
+     * declared in this file are the intersection of the project dependencies and the content of
+     * the {@code module-info.class} file.
+     */
+    @Nullable
+    Path pomFile;
+
+    /**
+     * The <var>JAR</var> file to create. Can be an existing file,
+     * in which case the file creation can be skipped if the file is still up-to-date.
+     */
+    @Nonnull
+    final Path jarFile;
+
+    /**
+     * A helper class for checking whether an existing <abbr>JAR</abbr> file is still up-to-date.
+     * This is null if there is no existing JAR file, or if we determined that the file is outdated.
+     */
+    private TimestampCheck existingJAR;
+
+    /**
+     * Name of the module being archived when the project is using module hierarchy.
+     * This is {@code null} if the project is using package hierarchy, either because it is a classical
+     * class-path project or because it is a single module compiled without using the module hierarchy.
+     * When using module source hierarchy, {@code javac} guarantees that the module name in the output
+     * directory is the name of the parent directory of {@code module-info.class}.
+     */
+    @Nullable
+    final String moduleName;
+
+    /**
+     * Path to {@code META-INF/MANIFEST.MF}, or {@code null} if none.
+     * If non-null, this value will be given to the {@code --manifest} option.
+     * The use of this option is preferable to adding {@code MANIFEST.MF} as an ordinary file.
+     *
+     * @see #setManifest(Path, boolean)
+     * @see #mergeManifest(Path, Manifest)
+     */
+    @Nullable
+    private Path manifest;
+
+    /**
+     * The Maven generated {@code pom.xml} and {@code pom.properties} files, or {@code null} if none.
+     * This first item must be the base directory where the files are located.
+     */
+    @Nullable
+    List<Path> mavenFiles;
+
+    /**
+     * Fully-qualified name of the main class, or {@code null} if none.
+     * This is the value to provide to the {@code --main-class} option.
+     */
+    private String mainClass;
+
+    /**
+     * Files or root directories to store in the <abbr>JAR</abbr> file for each target Java release
+     * other than the base release. Keys are the target Java release with {@code null} for the base
+     * release.
+     */
+    @Nonnull
+    private final NavigableMap<Runtime.Version, FileSet> filesetForRelease;
+
+    /**
+     * Files or root directories to archive for a single target Java release of a single module.
+     * The {@link Archive} enclosing must contain at least one instance of {@code FileSet} for
+     * the base release, and an arbitrary amount of other instances for other target releases.
+     */
+    final class FileSet {
+        /**
+         * The root directory of all files or directories to archive.
+         * This is the value to pass to the {@code -C} tool option.
+         */
+        @Nonnull
+        final Path directory;
+
+        /**
+         * The files or directories to include in the <var>JAR</var> file.
+         * Can be absolute paths or paths relative to {@link #directory}.
+         * It usually contains only the files or directories directly in
+         * the root {@linkplain #directory}, not in sub-directories.
+         */
+        @Nonnull
+        final List<Path> files;
+
+        /**
+         * Creates an initially empty set of files or directories for a specific target Java release.
+         *
+         * @param directory the base directory of the files or directories to archive
+         */
+        private FileSet(Path directory) {
+            this.directory = directory;
+            this.files = new ArrayList<>();
+        }
+
+        /**
+         * 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.
+         * The caller should use that common directory for logging a warning message.
+         *
+         * @param base base directory found by previous invocations of this method, or {@code null} if none
+         * @return common directory of discarded files
+         */
+        private Path discardAllFiles(Path base) {
+            for (Path file : files) {
+                if (base == null) {
+                    base = file.getParent();
+                } else {
+                    while (!file.startsWith(base)) {
+                        base = base.getParent();
+                        if (base == null) {
+                            break;
+                        }
+                    }
+                }
+            }
+            files.clear();
+            return base;
+        }
+
+        /**
+         * Adds the given path to the list of files or directories to archive.
+         * If the given path is a directory, then all children will be included.
+         * Children to exclude, if any, should be managed by {@link ExcludedFiles}.
+         *
+         * @param item a file or directory to archive
+         * @param attributes the file's basic attributes
+         * @param isDirectory whether the file is a directory
+         */
+        void add(Path item, BasicFileAttributes attributes, boolean isDirectory) {
+            TimestampCheck tc = existingJAR;
+            if (tc != null && tc.isUpdated(item, attributes, isDirectory)) {
+                existingJAR = null; // Signal that the existing file is outdated.
+            }
+            files.add(item);
+        }
+
+        /**
+         * Adds to the given list the arguments to provide to the "jar" tool for this version.
+         * The elements added to the list will be instances of {@link String} or {@link Path}.
+         *
+         * <h4>Note about the {@code -C} option</h4>
+         * This method repeats the {@code -C} option before each file.
+         * Our tests suggest that the first file after the directory specified by the {@code -C} option must
+         * be relative to that directory and all files after the first one must be prefixed by the directory
+         * which was specified in the {@code -C} option. This behavior is not very intuitive and replying on
+         * it can be fragile. Furthermore, it seems that the relativized file needs to be the shortest one,
+         * otherwise the {@code jar} tool rejects files after the first one with "names do not match".
+         * Which file is first depends on the unspecified directory-iteration order.
+         * Repeating the {@code -C} option for each file seems safer.
+         *
+         * @param addTo the list to add the arguments as {@link String} or {@link Path} instances to
+         * @param version the target Java release, or {@code null} for the base version of the <abbr>JAR</abbr> file
+         * @throws IllegalArgumentException if a path cannot be made relative to the base directory
+         */
+        private void arguments(List<Object> addTo, Runtime.Version version) {
+            if (files.isEmpty()) {
+                return;
+            }
+            if (version != null) {
+                addTo.add("--release");
+                addTo.add(version);
+            }
+            Path previous = null;
+            for (Path file : files) {
+                if (previous != null && file.startsWith(previous)) {
+                    // Already added a parent directory.
+                    continue;
+                }
+                previous = file;
+                file = directory.relativize(file);
+                if (file.getNameCount() <= 1 && file.toString().isEmpty()) {
+                    /*
+                     * The `-C` directory itself (e.g. a "META-INF/versions/<n>" directory added as a whole).
+                     * An empty file argument is invalid for the `jar` tool (some implementations reject it,
+                     * others silently misbehave), so archive the whole directory content with ".".
+                     */
+                    file = Path.of(".");
+                }
+                addTo.add("-C");
+                addTo.add(directory);
+                addTo.add(file);
+            }
+        }
+
+        /**
+         * {@return a string representation for debugging purposes}
+         */
+        @Override
+        public String toString() {
+            return getClass().getSimpleName() + '[' + directory.getFileName() + ": " + files.size() + " files]";
+        }
+    }
+
+    /**
+     * Creates an initially empty set of files or directories.
+     *
+     * @param jarFile path to the <abbr>JAR</abbr> file to create
+     * @param moduleName the module name if using module hierarchy, or {@code null} if using package hierarchy
+     * @param version the target Java release, or {@code null} for the base version
+     * @param directory the directory of the classes targeting the base Java release
+     * @param forceCreation whether to force a new <abbr>JAR</abbr> file even if the content seems unchanged
+     * @param logger where to send a warning if an error occurred while checking an existing <abbr>JAR</abbr> file
+     */
+    @SuppressWarnings("checkstyle:NeedBraces")
+    Archive(
+            final Path jarFile,
+            final String moduleName,
+            final Runtime.Version version,
+            final Path directory,
+            final boolean forceCreation,
+            final Log logger) {
+        this.jarFile = jarFile;
+        this.moduleName = moduleName;
+        filesetForRelease = new TreeMap<>((v1, v2) -> {
+            if (v1 == v2) return 0;
+            if (v1 == null) return -1;
+            if (v2 == null) return +1;
+            return v1.compareTo(v2);
+        });
+        filesetForRelease.put(version, new FileSet(directory));
+        if (!forceCreation && Files.isRegularFile(jarFile)) {
+            try {
+                existingJAR = new TimestampCheck(jarFile, directory, logger);
+            } catch (IOException e) {
+                // Ignore, we will regenerate the JAR file.
+                logger.warn(e);
+            }
+        }
+    }
+
+    /**
+     * {@return the files or directories to store in the <abbr>JAR</abbr> file for targeting the base Java release}
+     *
+     * @throws NoSuchElementException should not happen unless {@link #prune(boolean)} has been invoked
+     */
+    FileSet baseRelease() {
+        Map.Entry<Runtime.Version, FileSet> entry = filesetForRelease.firstEntry();
+        String message = null;
+        if (entry != null) {
+            Runtime.Version version = entry.getKey();
+            if (version == null) {
+                return entry.getValue();
+            }
+            message = "Expected base version but found version " + version;
+        }
+        throw new NoSuchElementException(message);
+    }
+
+    /**
+     * Returns the {@code module-info.class} files. Conceptually, there is at most once such file per module.
+     * However, more than one file can exist if additional files are provided for additional Java releases.
+     * This method returns only the files that exist.
+     *
+     * @return all {@code module-info.class} files found for all target Java releases
+     */
+    public List<Path> moduleInfoFiles() {
+        var files = new ArrayList<Path>();
+        filesetForRelease.values().forEach((release) -> {
+            Path file = release.directory.resolve(FileCollector.MODULE_DESCRIPTOR_FILE_NAME);
+            if (Files.isRegularFile(file)) {
+                files.add(file);
+            }
+        });
+        return files;
+    }
+
+    /**
+     * Discards all files in this archive, normally because those files are not in any module.
+     * This method returns a common parent directory for all the files that were discarded.
+     * The caller should use that common directory for logging a warning message.
+     *
+     * @return common directory of discarded files, or {@code null} if none
+     */
+    Path discardAllFiles() {
+        Path base = null;
+        for (FileSet release : filesetForRelease.values()) {
+            base = release.discardAllFiles(base);
+        }
+        filesetForRelease.clear();
+        return base;
+    }
+
+    /**
+     * Removes all empty file sets 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}, then this method ensures that at least one file set
+     * remains even if that file set is empty.
+     *
+     * @param skipIfEmpty value of {@link AbstractJarMojo#skipIfEmpty}
+     */
+    public void prune(final boolean skipIfEmpty) {
+        FileSet keep = (skipIfEmpty || isEmpty())
+                ? null
+                : filesetForRelease.firstEntry().getValue();
+        filesetForRelease.values().removeIf((fs) -> fs.files.isEmpty());
+        Iterator<Map.Entry<Runtime.Version, FileSet>> it =
+                filesetForRelease.entrySet().iterator();
+        if (it.hasNext()) {
+            Map.Entry<Runtime.Version, FileSet> first = it.next();
+            if (first.getKey() == null) {
+                return; // Already contains an entry for the base version, nothing to do.
+            }
+            keep = first.getValue();
+            it.remove();
+        }
+        if (keep != null) {
+            filesetForRelease.put(null, keep);
+        }
+    }
+
+    /**
+     * {@return whether this archive has nothing to archive}
+     * This method can return {@code false} even when there is zero file to archive.
+     * It can happen if {@link AbstractJarMojo#skipIfEmpty} is {@code false}. In such case, the
+     * "empty" <abbr>JAR</abbr> file will still contain at {@code META-INF/MANIFEST.MF} file.
+     *
+     * <h4>Prerequisites</h4>
+     * The {@link #prune(boolean)} method should be invoked before this method for accurate result.
+     */
+    public boolean isEmpty() {
+        return filesetForRelease.isEmpty();
+    }
+
+    /**
+     * Checks whether the <abbr>JAR</abbr> file already exists and can be reused.
+     * This method verifies that the <abbr>JAR</abbr> file contains all the files to archive,
+     * contains no extra file, and no file to archive is newer than the <abbr>JAR</abbr> file.
+     *
+     * <p>This method can be invoked only once.
+     * If invoked more often, it returns {@code false} on all subsequent invocations.</p>
+     *
+     * @return whether the <abbr>JAR</abbr> file already exists and can be reused
+     */
+    public boolean isUpToDateJAR() {
+        final TimestampCheck tc = existingJAR;
+        if (tc == null) {
+            return false;
+        }
+        existingJAR = null; // Let GC do its job.
+        return tc.isUpToDateJAR(filesetForRelease.values());
+    }
+
+    /**
+     * Returns an initially empty set of files or directories for the specified target Java release.
+     *
+     * @param directory the base directory of the files to archive
+     * @param version the target Java release, or {@code null} for the base version
+     * @return container where to declare files and directories to archive
+     */
+    FileSet newTargetRelease(Path directory, Runtime.Version version) {
+        return filesetForRelease.computeIfAbsent(version, (key) -> new FileSet(directory));
+    }
+
+    /**
+     * Sets the {@code --main-class} option to the value of the {@code Main-Class} entry of the given manifest.
+     * As an extension, this method accepts the {@code module/classname} syntax (a syntax already used in some
+     * Java tools). If a module is specified, the main class is kept only if the module match. The intent is to
+     * allow users to specify on which module the main class applies when they use plugin configuration.
+     *
+     * <p>This method may modify the {@code content} manifest. Caller must ensure that the given manifest
+     * is not a shared instance. This method returns whether a change has actually been done.</p>
+     *
+     * @param content combination of existing {@code MANIFEST.MF} and manifest inferred from configuration, or null
+     * @return whether the given manifest has been modified by this method
+     */
+    boolean setMainClass(Manifest content) {
+        if (content == null || mainClass != null) {
+            return false;
+        }
+        // We need to remove the attribute, otherwise it will conflict with `--main-class`.
+        mainClass = (String) content.getMainAttributes().remove(Attributes.Name.MAIN_CLASS);
+        if (mainClass != null) {
+            int s = mainClass.indexOf('/');
+            if (s >= 0) {
+                if (mainClass.substring(0, s).strip().equals(moduleName)) {
+                    mainClass = mainClass.substring(s + 1).strip();
+                } else {
+                    mainClass = null; // Main class is defined for another module.
+                }
+            }
+        }
+        return mainClass != null;
+    }
+
+    /**
+     * Sets the {@code --manifest} option to the given value if that option was not already set.
+     *
+     * @param file path to the manifest file
+     * @param force whether to set the manifest even if already set
+     * @return whether the manifest has been set
+     */
+    boolean setManifest(Path file, boolean force) {
+        if (manifest == null || force) {
+            manifest = file;
+            return true;
+        }
+        return false;
+    }
+
+    /**
+     * Merges the manifest of this module with the manifest specified in plugin configuration.
+     * If both {@code file} and {@code content} are non-null, then {@code content} must be the
+     * result of reading {@code file}.
+     *
+     * <p>This method never modifies the given {@code content} object. If manifest are merged,
+     * a new {@link Manifest} instance is created. Therefore, caller can check whether this
+     * method returned a new instance as a way to recognize that a merge occurred.</p>
+     *
+     * <p>If a merge occurs, the content specified to {@link #setManifest(Path)} has precedence.
+     * It should be the {@code target/classes/META-INF/MANIFEST.MF} file (or modular equivalent).</p>
+     *
+     * @param  file     an additional manifest file, or {@code null}
+     * @param  content  the content of {@code file}, or a standalone manifest produced at runtime
+     * @return the merged manifest as a new instance if some changes were necessary
+     * @throws IOException if an error occurred while reading a manifest file
+     */
+    Manifest mergeManifest(Path file, Manifest content) throws IOException {
+        if (manifest == null) {
+            manifest = file;
+        } else if (file != null && Files.isSameFile(file, manifest)) {
+            // Nothing to merge because of the constraint that `content` must be the content of `file`.
+        } else {
+            try (InputStream in = Files.newInputStream(manifest)) {
+                // No need to wrap in `BufferedInputStream`.
+                if (content != null) {
+                    content = new Manifest(content);
+                    content.read(in);
+                } else {
+                    content = new Manifest(in);
+                }
+            }
+        }
+        return content;
+    }
+
+    /**
+     * Adds to the given list the arguments to provide to the "jar" tool for each version.
+     * Elements added to the list must be instances of {@link String} or {@link Path}.
+     * Callers should have added the following options (if applicable) before to invoke this method:
+     *
+     * <ul>
+     *   <li>{@code --create}</li>
+     *   <li>{@code --no-compress}</li>
+     *   <li>{@code --date} followed by the output time stamp</li>
+     *   <li>{@code --module-version} followed by module version</li>
+     *   <li>{@code --hash-modules} followed by patters of module names</li>
+     *   <li>{@code --module-path} followed by module path</li>
+     * </ul>
+     *
+     * This method adds the following options:
+     *
+     * <ul>
+     *   <li>{@code --file} followed by the path to the <abbr>JAR</abbr> file</li>
+     *   <li>{@code --manifest} followed by path to the manifest file</li>
+     *   <li>{@code --main-class} followed by fully qualified name class</li>
+     *   <li>{@code --release} followed by Java target release</li>
+     *   <li>{@code -C} followed by directory</li>
+     *   <li>files or directories to archive</li>
+     * </ul>
+     *
+     * @param addTo the list where to add the arguments as {@link String} or {@link Path} instances
+     */
+    void arguments(final List<Object> addTo) {
+        addTo.add("--file");
+        addTo.add(jarFile);
+        if (manifest != null) {
+            addTo.add("--manifest");
+            addTo.add(manifest);
+        }
+        if (mainClass != null) {
+            addTo.add("--main-class");
+            addTo.add(mainClass);
+        }
+        if (mavenFiles != null) {
+            addTo.add("-C");
+            addTo.addAll(mavenFiles);
+        }
+        for (Map.Entry<Runtime.Version, FileSet> entry : filesetForRelease.entrySet()) {
+            entry.getValue().arguments(addTo, entry.getKey());
+        }
+    }
+
+    /**
+     * Adds to the given list the arguments to provide to the "jar" tool for validating the <abbr>JAR</abbr> file.
+     * The file is validated only if requested or, in automatic mode, if the validation was not done implicitly at
+     * <abbr>JAR</abbr> creation time. Implicit validation happens if some {@code --release} options were used.
+     * If {@code true}, this method adds the following options:
+     *
+     * <ul>
+     *   <li>{@code --validate} operation mode</li>
+     *   <li>{@code --file} followed by the path to the <abbr>JAR</abbr> file</li>
+     * </ul>
+     *
+     * @param  validate whether to validate, or {@code null} for automatic based on heuristic rules
+     * @param  addTo the list to add the arguments as {@link String} or {@link Path} instances to
+     * @return whether a validation should be run
+     */
+    boolean validate(final Boolean validate, final List<Object> addTo) {
+        boolean effective;
+        if (validate != null) {
+            effective = validate;
+        } else {
+            // If at least one --release option was used, then validation was implicit.
+            effective = !filesetForRelease.keySet().stream().anyMatch(Objects::nonNull);
+        }
+        if (effective) {
+            addTo.add("--validate");
+            addTo.add("--file");
+            addTo.add(jarFile);
+        }
+        return effective;
+    }
+
+    /**
+     * Dumps the tool options together with the list of files into a debug file.
+     * This is invoked in case of compilation failure, or if debug is enabled.
+     * The arguments can be separated by spaces or by new line characters.

Review Comment:
   maybe just white space?



##########
src/main/java/org/apache/maven/plugins/jar/FileCollector.java:
##########
@@ -0,0 +1,541 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.PathMatcher;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Deque;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.services.PathMatcherFactory;
+
+/**
+ * Dispatch the files from the output directory into the <abbr>JAR</abbr> files to create.
+ * Instead of just archiving as-is the content of the output directory, this class separates
+ * the following subdirectories to the options listed below:
+ *
+ * <ul>
+ *   <li>The {@code META-INF/MANIFEST.MF} file will be given to the {@code --manifest} option.</li>
+ *   <li>Files in the following directories will be given to the {@code --release} option:
+ *     <ul>
+ *       <li>{@code META-INF/versions/}</li>
+ *       <li>{@code META-INF/versions-modular/<module>/}</li>
+ *       <li>{@code <module>/META-INF/versions/}</li>
+ *     </ul>
+ *   </li>
+ * </ul>
+ *
+ * The reason for using the options is that they allow the {@code jar} tool to perform additional verifications.

Review Comment:
   "The reason for using the options " is unclear. 



##########
src/main/java/org/apache/maven/plugins/jar/ExcludedFiles.java:
##########
@@ -0,0 +1,145 @@
+/*
+ * 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.jar;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardCopyOption;
+import java.util.List;
+
+/**
+ * A list of files to temporarily move outside the directory to package in a <abbr>JAR</abbr> archive.
+ * This is used for excluding files from the <abbr>JAR</abbr> archive according to include/exclude filters.
+ * We move these files for making possible to specify the whole directory to the {@code jar} tool.
+ * This approach is used instead of enumerating files in arguments given to the {@code jar} tool because
+ * such enumeration can not contain directory entries (otherwise the whole directory would be included).
+ * Some software such as Spring applications component scan relies on the presence of directory entries.
+ */
+final class ExcludedFiles implements Closeable {
+    /**
+     * The paths of files or directories to temporarily move in another directory.
+     */
+    private final Path[] original;
+
+    /**
+     * The paths where files or directories were moved.
+     * For each index <var>i</var>, the original path of {@code moved[i]} was {@code original[i]}.
+     */
+    private final Path[] moved;
+
+    /**
+     * Temporary directory which will contain the {@code moved} files.
+     * It should be a parent directory of {@link #original} files for
+     * increasing the chances that it is on the same file system.
+     */
+    private final Path temporaryDirectory;
+
+    /**
+     * Index of the first path which is a directory instead of a file.
+     * All paths before this index in the {@link #original} and {@link #moved} arrays are files.
+     * All paths at this index and after this index are directories.
+     */
+    private final int indexOfFirstDirectory;
+
+    /**
+     * Creates a new list of files to move in a temporary directory.
+     *
+     * @param directory the directory which was scanned for files to include in the <abbr>JAR</abbr>
+     * @param excludedFiles paths of files to temporarily move in another directory
+     * @param excludedDirectories paths of directories to temporarily move in another directory
+     * @throws IOException if an error occurred while creating the temporary directory.
+     */
+    ExcludedFiles(Path directory, List<Path> excludedFiles, List<Path> excludedDirectories) throws IOException {
+        indexOfFirstDirectory = excludedFiles.size();
+        final int nd = excludedDirectories.size();
+        original = excludedFiles.toArray(new Path[indexOfFirstDirectory + nd]);
+        System.arraycopy(excludedDirectories.toArray(), 0, original, indexOfFirstDirectory, nd);
+        moved = new Path[original.length];
+        temporaryDirectory = Files.createTempDirectory(directory, "excluded-");
+    }
+
+    /**
+     * Moves the files now. This method should be invoked inside the "try with resource" block.
+     *
+     * @throws IOException if an error occurred while moving a file.
+     */
+    public void move() throws IOException {
+        for (int i = 0; i < original.length; i++) {
+            final Path source = original[i];
+            String prefix = source.getFileName().toString();
+            String suffix = null;
+            Path target;
+            if (i < indexOfFirstDirectory) {
+                int s = prefix.lastIndexOf('.');
+                if (s > 0) {
+                    suffix = prefix.substring(s);
+                    prefix = prefix.substring(0, s);
+                }
+                target = Files.createTempFile(temporaryDirectory, prefix, suffix);
+            } else {
+                target = Files.createTempDirectory(temporaryDirectory, prefix);
+            }
+            try {
+                moved[i] = Files.move(source, target, StandardCopyOption.REPLACE_EXISTING);
+            } catch (IOException e) {
+                try {
+                    Files.delete(target);
+                } catch (IOException e2) {
+                    e.addSuppressed(e2);
+                }
+                throw e;
+            }
+        }
+    }
+
+    /**
+     * Moves the temporary files back to their original locations.
+     * This method can be invoked even if only a subset of the files were moved.
+     * The latter may happen if an error occurred in the middle of {@link #move()} execution.

Review Comment:
   may --> can



##########
src/main/java/org/apache/maven/plugins/jar/FileCollector.java:
##########
@@ -0,0 +1,541 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.PathMatcher;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Deque;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.services.PathMatcherFactory;
+
+/**
+ * Dispatch the files from the output directory into the <abbr>JAR</abbr> files to create.
+ * Instead of just archiving as-is the content of the output directory, this class separates
+ * the following subdirectories to the options listed below:
+ *
+ * <ul>
+ *   <li>The {@code META-INF/MANIFEST.MF} file will be given to the {@code --manifest} option.</li>
+ *   <li>Files in the following directories will be given to the {@code --release} option:
+ *     <ul>
+ *       <li>{@code META-INF/versions/}</li>
+ *       <li>{@code META-INF/versions-modular/<module>/}</li>
+ *       <li>{@code <module>/META-INF/versions/}</li>
+ *     </ul>
+ *   </li>
+ * </ul>
+ *
+ * The reason for using the options is that they allow the {@code jar} tool to perform additional verifications.
+ * For example, when using the {@code --release} option, {@code jar} verifies the <abbr>API</abbr> compatibility.
+ */
+final class FileCollector extends SimpleFileVisitor<Path> {
+    /**
+     * The file to check for deciding whether the <abbr>JAR</abbr> is modular.
+     */
+    static final String MODULE_DESCRIPTOR_FILE_NAME = "module-info.class";
+
+    /**
+     * The {@value} directory.
+     * This is part of <abbr>JAR</abbr> file specification.
+     */
+    private static final String VERSIONS = "versions";
+
+    /**
+     * The {@value} directory.
+     * This is Maven-specific.
+     */
+    private static final String VERSIONS_MODULAR = "versions-modular";
+
+    /**
+     * Context (logger, configuration) in which the <abbr>JAR</abbr> file are created.
+     */
+    private final ToolExecutor context;
+
+    /**
+     * Whether to detect multi-release <abbr>JAR</abbr> files.
+     * The default value is {@code true}.
+     *
+     * @see AbstractJarMojo#detectMultiReleaseJar
+     */
+    private final boolean detectMultiReleaseJar;
+
+    /**
+     * The root directory to traverse. It will be used for temporarily moving excluded files.
+     */
+    private final Path rootDirectory;
+
+    /**
+     * Combination of includes and excludes path matcher applied on files.
+     */
+    @Nonnull
+    private final PathMatcher fileMatcher;
+
+    /**
+     * Combination of includes and excludes path matcher applied on directories.
+     */
+    @Nonnull
+    private final PathMatcher directoryMatcher;
+
+    /**
+     * Files to exclude. These files will be moved to a temporary location
+     * for allowing {@link ToolExecutor} to specify whole directories to the {@code jar} tool.
+     * Specifying whole directories is preferable to enumerating the files because otherwise,
+     * the generated <abbr>JAR</abbr> file contains only entries for the files and is missing
+     * entries for the directories.
+     *
+     * <p>This field is {@code null} if it is not possible to have any excluded file
+     * (because there is no include/exclude filters).</p>
+     */
+    @Nullable
+    private final List<Path> excludedFiles;
+
+    /**
+     * Directories to exclude. This field serves the same purpose as {@link #excludedFiles},
+     * but where the sources a directories instead of files.
+     */
+    @Nullable
+    private final List<Path> excludedDirectories;
+
+    /**
+     * Files found in the output directory when package hierarchy is used.
+     * At most one of {@code packageHierarchy} and {@link #moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Archive packageHierarchy;
+
+    /**
+     * Files found in the output directory when module hierarchy is used. Keys are module names.
+     * At most one of {@link #packageHierarchy} and {@code moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Map<String, Archive> moduleHierarchy;
+
+    /**
+     * The current module being archived. This field is updated every times that {@code FileCollector}
+     * visits a new module directory.
+     */
+    @Nonnull
+    private Archive currentModule;
+
+    /**
+     * The module and target Java release currently being scanned. This field is updated every times that
+     * {@code FileCollector} visits a new module directory or in a new target Java release for a given module.
+     */
+    @Nonnull
+    private Archive.FileSet currentFilesToArchive;
+
+    /**
+     * The current target Java release, or {@code null} if none.
+     */
+    @Nullable
+    private Runtime.Version currentTargetVersion;
+
+    /**
+     * Identification of the kinds of directories being traversed.
+     * The length of this list is the depth in the directory hierarchy.
+     * The last element identifies the type of the current directory.
+     */
+    private final Deque<DirectoryRole> directoryRoles;
+
+    /**
+     * Whether to check when a file is the {@code MANIFEST.MF} file.
+     * This is allowed only when scanning the content of a {@code META-INF} directory.
+     */
+    private boolean checkForManifest;
+
+    /**
+     * Creates a new file collector.
+     *
+     * @param mojo the <abbr>MOJO</abbr> from which to get the configuration
+     * @param context context (logger, configuration) in which the <abbr>JAR</abbr> file are created
+     * @param directory the base directory of the files to archive
+     */
+    FileCollector(AbstractJarMojo mojo, ToolExecutor context, Path directory, PathMatcherFactory matcherFactory) {
+        this.context = context;
+        rootDirectory = directory;
+        detectMultiReleaseJar = mojo.detectMultiReleaseJar;
+        directoryRoles = new ArrayDeque<>();
+        fileMatcher = matcherFactory.createPathMatcher(directory, mojo.getIncludes(), mojo.getExcludes(), false);
+        directoryMatcher = matcherFactory.deriveDirectoryMatcher(fileMatcher);
+        if (matcherFactory.isIncludesAll(fileMatcher) && matcherFactory.isIncludesAll(directoryMatcher)) {
+            excludedFiles = null;
+            excludedDirectories = null;
+        } else {
+            excludedFiles = new ArrayList<>();
+            excludedDirectories = new ArrayList<>();
+        }
+        packageHierarchy = context.newArchive(null, null, directory);
+        moduleHierarchy = new LinkedHashMap<>();
+        resetToPackageHierarchy();
+    }
+
+    /**
+     * Resets this {@code FileCollector} to the state where a package hierarchy is presumed.
+     */
+    private void resetToPackageHierarchy() {
+        currentModule = packageHierarchy;
+        currentFilesToArchive = currentModule.baseRelease();
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a module.
+     * For an output generated by {@code javac} from a module source hierarchy,
+     * the directory name is guaranteed to be the module name.

Review Comment:
   is guaranteed to be the module name --> is the module name.



##########
src/main/java/org/apache/maven/plugins/jar/FileCollector.java:
##########
@@ -0,0 +1,541 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.PathMatcher;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Deque;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.services.PathMatcherFactory;
+
+/**
+ * Dispatch the files from the output directory into the <abbr>JAR</abbr> files to create.
+ * Instead of just archiving as-is the content of the output directory, this class separates
+ * the following subdirectories to the options listed below:
+ *
+ * <ul>
+ *   <li>The {@code META-INF/MANIFEST.MF} file will be given to the {@code --manifest} option.</li>
+ *   <li>Files in the following directories will be given to the {@code --release} option:
+ *     <ul>
+ *       <li>{@code META-INF/versions/}</li>
+ *       <li>{@code META-INF/versions-modular/<module>/}</li>
+ *       <li>{@code <module>/META-INF/versions/}</li>
+ *     </ul>
+ *   </li>
+ * </ul>
+ *
+ * The reason for using the options is that they allow the {@code jar} tool to perform additional verifications.
+ * For example, when using the {@code --release} option, {@code jar} verifies the <abbr>API</abbr> compatibility.
+ */
+final class FileCollector extends SimpleFileVisitor<Path> {
+    /**
+     * The file to check for deciding whether the <abbr>JAR</abbr> is modular.
+     */
+    static final String MODULE_DESCRIPTOR_FILE_NAME = "module-info.class";
+
+    /**
+     * The {@value} directory.
+     * This is part of <abbr>JAR</abbr> file specification.
+     */
+    private static final String VERSIONS = "versions";
+
+    /**
+     * The {@value} directory.
+     * This is Maven-specific.
+     */
+    private static final String VERSIONS_MODULAR = "versions-modular";
+
+    /**
+     * Context (logger, configuration) in which the <abbr>JAR</abbr> file are created.
+     */
+    private final ToolExecutor context;
+
+    /**
+     * Whether to detect multi-release <abbr>JAR</abbr> files.
+     * The default value is {@code true}.
+     *
+     * @see AbstractJarMojo#detectMultiReleaseJar
+     */
+    private final boolean detectMultiReleaseJar;
+
+    /**
+     * The root directory to traverse. It will be used for temporarily moving excluded files.
+     */
+    private final Path rootDirectory;
+
+    /**
+     * Combination of includes and excludes path matcher applied on files.
+     */
+    @Nonnull
+    private final PathMatcher fileMatcher;
+
+    /**
+     * Combination of includes and excludes path matcher applied on directories.
+     */
+    @Nonnull
+    private final PathMatcher directoryMatcher;
+
+    /**
+     * Files to exclude. These files will be moved to a temporary location
+     * for allowing {@link ToolExecutor} to specify whole directories to the {@code jar} tool.
+     * Specifying whole directories is preferable to enumerating the files because otherwise,
+     * the generated <abbr>JAR</abbr> file contains only entries for the files and is missing
+     * entries for the directories.
+     *
+     * <p>This field is {@code null} if it is not possible to have any excluded file
+     * (because there is no include/exclude filters).</p>
+     */
+    @Nullable
+    private final List<Path> excludedFiles;
+
+    /**
+     * Directories to exclude. This field serves the same purpose as {@link #excludedFiles},
+     * but where the sources a directories instead of files.
+     */
+    @Nullable
+    private final List<Path> excludedDirectories;
+
+    /**
+     * Files found in the output directory when package hierarchy is used.
+     * At most one of {@code packageHierarchy} and {@link #moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Archive packageHierarchy;
+
+    /**
+     * Files found in the output directory when module hierarchy is used. Keys are module names.
+     * At most one of {@link #packageHierarchy} and {@code moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Map<String, Archive> moduleHierarchy;
+
+    /**
+     * The current module being archived. This field is updated every times that {@code FileCollector}
+     * visits a new module directory.
+     */
+    @Nonnull
+    private Archive currentModule;
+
+    /**
+     * The module and target Java release currently being scanned. This field is updated every times that
+     * {@code FileCollector} visits a new module directory or in a new target Java release for a given module.
+     */
+    @Nonnull
+    private Archive.FileSet currentFilesToArchive;
+
+    /**
+     * The current target Java release, or {@code null} if none.
+     */
+    @Nullable
+    private Runtime.Version currentTargetVersion;
+
+    /**
+     * Identification of the kinds of directories being traversed.
+     * The length of this list is the depth in the directory hierarchy.
+     * The last element identifies the type of the current directory.
+     */
+    private final Deque<DirectoryRole> directoryRoles;
+
+    /**
+     * Whether to check when a file is the {@code MANIFEST.MF} file.
+     * This is allowed only when scanning the content of a {@code META-INF} directory.
+     */
+    private boolean checkForManifest;
+
+    /**
+     * Creates a new file collector.
+     *
+     * @param mojo the <abbr>MOJO</abbr> from which to get the configuration
+     * @param context context (logger, configuration) in which the <abbr>JAR</abbr> file are created
+     * @param directory the base directory of the files to archive
+     */
+    FileCollector(AbstractJarMojo mojo, ToolExecutor context, Path directory, PathMatcherFactory matcherFactory) {
+        this.context = context;
+        rootDirectory = directory;
+        detectMultiReleaseJar = mojo.detectMultiReleaseJar;
+        directoryRoles = new ArrayDeque<>();
+        fileMatcher = matcherFactory.createPathMatcher(directory, mojo.getIncludes(), mojo.getExcludes(), false);
+        directoryMatcher = matcherFactory.deriveDirectoryMatcher(fileMatcher);
+        if (matcherFactory.isIncludesAll(fileMatcher) && matcherFactory.isIncludesAll(directoryMatcher)) {
+            excludedFiles = null;
+            excludedDirectories = null;
+        } else {
+            excludedFiles = new ArrayList<>();
+            excludedDirectories = new ArrayList<>();
+        }
+        packageHierarchy = context.newArchive(null, null, directory);
+        moduleHierarchy = new LinkedHashMap<>();
+        resetToPackageHierarchy();
+    }
+
+    /**
+     * Resets this {@code FileCollector} to the state where a package hierarchy is presumed.
+     */
+    private void resetToPackageHierarchy() {
+        currentModule = packageHierarchy;
+        currentFilesToArchive = currentModule.baseRelease();
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a module.
+     * For an output generated by {@code javac} from a module source hierarchy,
+     * the directory name is guaranteed to be the module name.
+     *
+     * @param directory a {@code "<module>"} or {@code "META-INF/versions-modular/<module>"} directory
+     */
+    private void preVisitVersionDirectory(final Path directory) {
+        String moduleName = directory.getFileName().toString();
+        currentModule = moduleHierarchy.computeIfAbsent(
+                moduleName, (name) -> context.newArchive(name, currentTargetVersion, directory));
+        currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a target Java version.
+     * The {@code useDirectly} argument tells whether the content of this directory will be specified directly
+     * as the content to add in the <abbr>JAR</abbr> file. This argument should be {@code false} when there is
+     * another directory level (the module names) to process before to add content.
+     *
+     * @param directory a {@code "META-INF/versions/<n>"} or {@code "META-INF/versions-modular/<n>"} directory
+     * @param useDirectly whether the directory is {@code "META-INF/versions/<n>"}
+     * @return whether to skip the directory because of invalid version number
+     */
+    private boolean preVisitVersionDirectory(final Path directory, final boolean useDirectly) {
+        try {
+            currentTargetVersion = Runtime.Version.parse(directory.getFileName().toString());
+        } catch (IllegalArgumentException e) {
+            context.warnInvalidVersion(directory, e);
+            return true;
+        }
+        if (useDirectly) {
+            currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+        }
+        return false;
+    }
+
+    /**
+     * Determines if the given directory should be scanned for files to archive.
+     * This method may also update {@link #currentFilesToArchive} if it detects
+     * that we are visiting the content of a new module or a new target Java release.
+     *
+     * @param directory the directory which will be traversed
+     * @param attributes the directory's basic attributes
+     */
+    @Override
+    @SuppressWarnings("checkstyle:MissingSwitchDefault")
+    public FileVisitResult preVisitDirectory(final Path directory, final BasicFileAttributes attributes)
+            throws IOException {
+        DirectoryRole role;
+        if (directoryRoles.isEmpty()) {
+            role = DirectoryRole.ROOT;
+        } else {
+            if (!directoryMatcher.matches(directory)) {
+                excludedDirectories.add(directory); // Cannot be null if excluded directories may exist.
+                return FileVisitResult.SKIP_SUBTREE;
+            }
+            checkForManifest = false;
+            role = directoryRoles.getLast();
+            switch (role) {
+                case ROOT:
+                    /*
+                     * Visiting any subdirectory of `target/classes` (or other directory to archive).
+                     * We need to handle `META-INF` and modules in a special way, and archive the rest.
+                     */
+                    if (directory.endsWith(MetadataFiles.META_INF)) {
+                        role = DirectoryRole.META_INF;
+                        checkForManifest = true;
+                    } else if (Files.isRegularFile(directory.resolve(MODULE_DESCRIPTOR_FILE_NAME))) {
+                        role = DirectoryRole.NAMED_MODULE;
+                        preVisitVersionDirectory(directory);
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case META_INF:
+                    /*
+                     * Visiting a subdirectory of `META-INF` or `<module>/META-INF`. We will need to handle
+                     * `MANIFEST.MF`, `versions` and `versions-modular` in a special way, and archive the rest.
+                     */
+                    if (detectMultiReleaseJar && directory.endsWith(VERSIONS)) {
+                        role = DirectoryRole.VERSIONS;
+                    } else if (directory.endsWith(VERSIONS_MODULAR)) {
+                        if (!detectMultiReleaseJar) {
+                            // Used asked for no multi-release JAR.
+                            return FileVisitResult.SKIP_SUBTREE;
+                        }
+                        role = DirectoryRole.VERSIONS_MODULAR;
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case VERSIONS:
+                    /*
+                     * Visiting a `META-INF/versions/<n>/` directory for a specific target Java release.
+                     * Can also be a `<module>/META-INF/versions/<n>/` directory, even if the latter is not
+                     * the layout generated by Maven Compiler Plugin.
+                     */
+                    if (preVisitVersionDirectory(directory, true)) {
+                        // An error occurred while parsing the version number.
+                        return FileVisitResult.SKIP_SUBTREE;
+                    }
+                    role = DirectoryRole.RESOURCES;
+                    break;
+
+                case VERSIONS_MODULAR:
+                    /*
+                     * Visiting a `META-INF/versions-modular/<n>/` directory for a specific target Java release.
+                     * That directory contains all modules for the version.
+                     */
+                    resetToPackageHierarchy(); // No module in particular yet.
+                    if (preVisitVersionDirectory(directory, false)) {
+                        // An error occurred while parsing the version number.
+                        return FileVisitResult.SKIP_SUBTREE;
+                    }
+                    role = DirectoryRole.MODULES;
+                    break;
+
+                case MODULES:
+                    /*
+                     * Visiting a `META-INF/versions-modular/<n>/<module>` directory.
+                     */
+                    preVisitVersionDirectory(directory);
+                    role = DirectoryRole.NAMED_MODULE;
+                    break;
+
+                case NAMED_MODULE:
+                    /*
+                     * Visiting a `<module>` or `META-INF/versions-modular/<n>/<module>` subdirectory.
+                     * A module could have its own `META-INF` subdirectory, so we need to check again.
+                     */
+                    if (directory.endsWith(MetadataFiles.META_INF)) {
+                        role = DirectoryRole.META_INF;
+                        checkForManifest = true;
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+            }
+        }
+        /*
+         * Do not move this condition inside the `switch` block because `role` may have been modified.
+         * The `role` value is now the role of `directory`, not the role of parent directory.
+         */
+        if (role == DirectoryRole.RESOURCES) {
+            currentFilesToArchive.add(directory, attributes, true);
+            if (excludedFiles == null) {
+                /*
+                 * Since we are skipping the whole directory, `postVisitDirectory(…)` will not be invoked.
+                 * We must reset `currentFilesToArchive` and `currentTargetVersion` by an explicit call.
+                 * This is important mostly after we added a whole `META-INF/versions/<n>` directory.
+                 * Otherwise, since directory iteration order is unspecified, base files visited afterwards
+                 * would be added to this version's file set instead of the base release.
+                 */
+                resetToParentDirectoryState();
+                return FileVisitResult.SKIP_SUBTREE;
+            }
+        }
+        directoryRoles.addLast(role);
+        return FileVisitResult.CONTINUE;
+    }
+
+    /**
+     * Updates the {@code FileCollector} state after we finished scanning the contents of a directory.
+     * The fields to update depend on which directory has been visited (module, version, etc.).
+     *
+     * @param directory the directory which has been traversed
+     * @param error the error that occurred while traversing the directory, or {@code null} if none
+     */
+    @Override
+    public FileVisitResult postVisitDirectory(final Path directory, final IOException error) throws IOException {
+        if (error != null) {
+            throw error;
+        }
+        switch (directoryRoles.removeLast()) {
+            case ROOT:
+                break;
+
+            case NAMED_MODULE:
+                // Exited the directory of a single module.
+                resetToPackageHierarchy();
+                break;
+
+            default:
+                resetToParentDirectoryState();
+                break;
+        }
+        return FileVisitResult.CONTINUE;
+    }
+
+    /**
+     * Updates {@code FileCollector} to a state suitable for the parent of the directory that we finished to scan.
+     * Contrary to {@link #postVisitDirectory(Path, IOException)}, this method expects the last element of
+     * {@link #directoryRoles} to describe the parent directory, not the directory that we finished to visit.
+     */
+    @SuppressWarnings("checkstyle:MissingSwitchDefault")
+    private void resetToParentDirectoryState() {
+        switch (directoryRoles.getLast()) {
+            case VERSIONS:
+            case VERSIONS_MODULAR:
+                // Exited the directory for one target Java release.
+                currentFilesToArchive = currentModule.baseRelease();
+                currentTargetVersion = null;
+                break;
+
+            case META_INF:
+                checkForManifest = true;
+                break;
+        }
+    }
+
+    /**
+     * Archives a single file if accepted by the matcher.
+     *
+     * @param file the file
+     * @param attributes the file's basic attributes
+     */
+    @Override
+    public FileVisitResult visitFile(final Path file, final BasicFileAttributes attributes) {
+        if (fileMatcher.matches(file)) {
+            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.add(file, attributes, false);
+            }
+        } else {
+            excludedFiles.add(file); // Cannot be null if excluded files may exist.
+        }
+        return FileVisitResult.CONTINUE;
+    }
+
+    /**
+     * 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}
+     */
+    public void prune(boolean skipIfEmpty) {
+        boolean isModuleHierarchy = !moduleHierarchy.isEmpty();
+        moduleHierarchy.values().forEach((archive) -> archive.prune(skipIfEmpty));
+        moduleHierarchy.values().removeIf(Archive::isEmpty);
+        packageHierarchy.prune(isModuleHierarchy || skipIfEmpty);
+    }
+
+    /**
+     * Moves, copies, or ignores orphan files.
+     * An orphan file is a file which is not in any module when module hierarchy is used.
+     * For example, some Maven plugins may create files such as {@code META-INF/LICENSE},
+     * {@code META-INF/NOTICE} or {@code META-INF/DEPENDENCIES}. These files are not in
+     * the correct directory (they should be in a {@code "<module>/META-INF"} directory)
+     * because the plugin may not be aware of module hierarchy.
+     *
+     * <p>A possible strategy could be to copy the {@code LICENSE} and {@code NOTICE} files
+     * in each module, and ignore the {@code DEPENDENCIES} file because its content is not
+     * correct for a module. For now, we just log a warning and ignore.</p>
+     *
+     * <h4>Prerequisites</h4>
+     * The {@link #prune(boolean)} method should have been invoked once before invoking this method.
+     *
+     * @return if this method ignored some files, the root directory of those files
+     */
+    Path handleOrphanFiles() {
+        if (moduleHierarchy.isEmpty() || packageHierarchy.isEmpty()) {
+            // Classpath project or module-project without orphan files. Nothing to do.
+            return null;
+        }
+        // TODO: we may want to copy LICENSE and NOTICE files here.
+        return packageHierarchy.discardAllFiles();
+    }
+
+    /**
+     * 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())) {
+            return null;
+        }
+        return new ExcludedFiles(rootDirectory, excludedFiles, excludedDirectories);
+    }
+
+    /**
+     * Writes all <abbr>JAR</abbr> files.
+     * If the project is multi-module, this method returns the path to the generated parent <abbr>POM</abbr> file.
+     *
+     * <h4>Prerequisites</h4>
+     * The {@link #prune(boolean)} method should have been invoked once before to invoke this method.
+     *
+     * @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
+     * @throws IOException if an error occurred while reading or writing a manifest file
+     */
+    Path writeAllJARs(final ToolExecutor executor) throws IOException {
+        try (ExcludedFiles exclusion = exclusion()) {
+            if (exclusion != null) {
+                exclusion.move();
+            }
+            for (Archive module : moduleHierarchy.values()) {
+                executor.writeSingleJAR(this, module);
+            }
+            if (executor.pomDerivation != null) {
+                return executor.pomDerivation.writeParentPOM(packageHierarchy);
+            }
+            if (!packageHierarchy.isEmpty()) {
+                executor.writeSingleJAR(this, packageHierarchy);
+            }
+        }
+        return null;
+    }
+
+    /**
+     * {@return the paths to all root directories of modules in a module hierarchy}
+     * They are usually {@code target/classes/<module>} directories, but could also
+     * be sub-directories in the {@code META-INF/modular-versions/<n>/} directory.
+     * If the project does not use module hierarchy, this method returns an empty list.
+     *
+     * <h4>Ignored package hierarchy</h4>
+     * Note that an empty list does not mean that the <abbr>JAR</abbr> is not modular,
+     * as a modular <abbr>JAR</abbr> can also be built from package hierarchy. But we intentionally
+     * ignore the latter case because this method is used for deriving <abbr>POM</abbr> files, and
+     * we do not perform such derivation for projects organized in the Maven 3 way.
+     *
+     * <h4>Prerequisites</h4>

Review Comment:
   ditto



##########
src/main/java/org/apache/maven/plugins/jar/TimestampCheck.java:
##########
@@ -0,0 +1,261 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.nio.file.attribute.FileTime;
+import java.util.Collection;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+
+import org.apache.maven.api.plugin.Log;
+
+/**
+ * Checks file timestamps in order to determine if anything changed compared to an existing <abbr>JAR</abbr> file.
+ * This class may scan directories, but only if they have not already been visited by {@link FileCollector}.
+ * The latter can only occur if {@link FileCollector} has no {@code PathMatcher}.
+ * Therefore, this class uses no {@code PathMatcher}.
+ *
+ * <h2>Ignore files</h2>
+ * The {@code META-INF/MANIFEST.MF} file and the {@code META-INF/maven/} directory are ignored.
+ * See {@link #isIgnored(Path)} for the rational.
+ */
+final class TimestampCheck extends SimpleFileVisitor<Path> {
+    /**
+     * The base directory of archived files.
+     */
+    private final Path classesDir;
+
+    /**
+     * Path to the existing <abbr>JAR</abbr> file.
+     */
+    private final Path jarFile;
+
+    /**
+     * The last modified time of the <abbr>JAR</abbr> file.
+     */
+    private final FileTime jarFileTime;
+
+    /**
+     * Where to send non-fatal error messages.
+     */
+    private final Log logger;
+
+    /**
+     * Entries of the <abbr>JAR</abbr> file. Note that getting elements from this enumeration can be costly.
+     * Therefore, we only fetch elements when needed.
+     */
+    private Enumeration<? extends ZipEntry> entries;
+
+    /**
+     * Files found in the <abbr>JAR</abbr> file but not yet traversed by the file visitor.
+     * Files are added lazily when needed, and removed as soon as they have been traversed.
+     * Path are absolute (resolved with {@link #classesDir}).

Review Comment:
   Paths



##########
src/main/java/org/apache/maven/plugins/jar/PomDerivation.java:
##########
@@ -0,0 +1,529 @@
+/*
+ * 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.jar;
+
+import javax.xml.stream.XMLStreamException;
+
+import java.io.BufferedInputStream;
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.UncheckedIOException;
+import java.lang.module.ModuleDescriptor;
+import java.lang.module.ModuleFinder;
+import java.lang.module.ModuleReference;
+import java.net.URI;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.DependencyCoordinates;
+import org.apache.maven.api.JavaPathType;
+import org.apache.maven.api.Session;
+import org.apache.maven.api.Type;
+import org.apache.maven.api.model.Dependency;
+import org.apache.maven.api.model.Model;
+import org.apache.maven.api.model.Parent;
+import org.apache.maven.api.plugin.MojoException;
+import org.apache.maven.api.services.DependencyCoordinatesFactory;
+import org.apache.maven.api.services.DependencyCoordinatesFactoryRequest;
+import org.apache.maven.api.services.DependencyResolver;
+import org.apache.maven.api.services.DependencyResolverRequest;
+import org.apache.maven.api.services.DependencyResolverResult;
+import org.apache.maven.api.services.ModelBuilderException;
+import org.apache.maven.model.v4.MavenStaxWriter;
+
+/**
+ * A mapper from Maven model dependencies to Java module names.
+ * A single instance of this class is created for a Maven project,
+ * then shared by all {@link ForModule} instances (one per module to archive).
+ */
+final class PomDerivation {
+    /**
+     * Whether to expand the list of transitive dependencies in the generated <abbr>POM</abbr>.
+     */
+    private static final boolean EXPAND_TRANSITIVE = false;
+
+    /**
+     * Copy of {@link AbstractJarMojo#session}.
+     */
+    private final Session session;
+
+    /**
+     * The project model, which includes dependencies of all modules.
+     */
+    private final Model projectModel;
+
+    /**
+     * The factory to use for creating temporary {@link DependencyCoordinates} instances.
+     */
+    private final DependencyCoordinatesFactory coordinateFactory;
+
+    /**
+     * Provide module descriptors from module names.
+     * May be {@code null} if no {@code module-info} was found.
+     */
+    private final ModuleFinder moduleFinder;
+
+    /**
+     * Module references from paths to the <abbr>JAR</abbr> file or root directory.
+     */
+    private final Map<URI, ModuleReference> fromURI;
+
+    /**
+     * Module names associated with Maven dependencies.
+     * This map contains {@link DependencyCoordinates#getId()} as keys and module references as values.
+     * This is used to detect which dependencies are really used according to {@code module-info.class}.
+     *
+     * @todo The keys should be instances of {@link DependencyCoordinates}. Unfortunately, as of Maven 4.0.0-rc-5
+     *       that interface does not define the {@code equals} and {@code hashCode} contracts.
+     */
+    private final Map<String, ModuleReference> fromDependency;
+
+    /**
+     * Modules that are built by the project. Keys are module names.
+     */
+    private final Map<String, Dependency> builtModules;
+
+    /**
+     * Creates a new mapper from Maven dependency to module name.
+     *
+     * @param mojo the enclosing <abbr>MOJO</abbr>
+     * @param moduleRoots paths to root directories of each module to archive in a module hierarchy
+     * @throws IOException if an I/O error occurred while fetching dependencies
+     * @throws MavenException if an error occurred while fetching dependencies for a reason other than I/O.
+     */
+    PomDerivation(final AbstractJarMojo mojo, final List<Path> moduleRoots) throws IOException {
+        this.session = mojo.session;
+        projectModel = mojo.project.getModel();
+        coordinateFactory = session.getService(DependencyCoordinatesFactory.class);
+        DependencyResolver resolver = session.getService(DependencyResolver.class);
+        DependencyResolverResult result = resolver.resolve(DependencyResolverRequest.builder()
+                .session(session)
+                .project(mojo.project)
+                .requestType(DependencyResolverRequest.RequestType.RESOLVE)
+                .pathScope(mojo.getDependencyScope())
+                .pathTypeFilter(Set.of(JavaPathType.MODULES, JavaPathType.CLASSES))
+                .build());
+
+        rethrow(result);
+        final Map<org.apache.maven.api.Dependency, Path> dependencies = result.getDependencies();
+        final Path[] allModulePaths = toRealPaths(moduleRoots, dependencies.values());
+        fromURI = new HashMap<>(allModulePaths.length); // TODO: use newHashMap with JDK19.
+        moduleFinder = ModuleFinder.of(allModulePaths);
+        if (moduleFinder != null) {
+            for (ModuleReference reference : moduleFinder.findAll()) {
+                reference.location().ifPresent((location) -> fromURI.put(location, reference));
+            }
+        }
+        fromDependency = new HashMap<>(dependencies.size()); // TODO: use newHashMap with JDK19.
+        for (Map.Entry<org.apache.maven.api.Dependency, Path> entry : dependencies.entrySet()) {
+            Path modulePath = entry.getValue().toRealPath();
+            ModuleReference reference = fromURI.get(modulePath.toUri());
+            if (reference != null) {
+                DependencyCoordinates coordinates = entry.getKey().toCoordinates();
+                String id = coordinates.getId();
+                ModuleReference old = fromDependency.putIfAbsent(id, reference);
+                if (old == null) {
+                    coordinates = withoutVersion(coordinates);
+                    id = coordinates.getId();
+                    old = fromDependency.putIfAbsent(id, reference);
+                }
+                if (old != null && !old.equals(reference)) {
+                    mojo.log.warn("The \"" + id + "\" dependency is declared twice with different module names: \""
+                            + old.descriptor().name() + "\" and \""
+                            + reference.descriptor().name() + "\".");
+                }
+            }
+        }
+        builtModules = new HashMap<>(moduleRoots.size()); // TODO: use newHashMap with JDK19.
+        for (Path root : moduleRoots) {
+            root = root.toRealPath();
+            ModuleReference reference = fromURI.get(root.toUri());
+            if (reference != null) { // Actually a null value would be a bug, but be tolerant.
+                String moduleName = reference.descriptor().name();
+                builtModules.put(
+                        moduleName,
+                        Dependency.newBuilder()
+                                .groupId(projectModel.getGroupId())
+                                .artifactId(moduleName)
+                                .version(projectModel.getVersion())
+                                .type(Type.MODULAR_JAR)
+                                .build());
+            }
+        }
+    }
+
+    /**
+     * Rebuilds the given dependency coordinates without version.
+     *
+     * Note: I'm not sure if it is necessary. This is done in case version numbers are not resolved
+     * in the dependencies of the model returned by {@code Project.getModel()}, or are not resolved
+     * in the same way as what we get from {@link DependencyResolver}.
+     */
+    private DependencyCoordinates withoutVersion(DependencyCoordinates coordinates) {
+        return coordinateFactory.create(DependencyCoordinatesFactoryRequest.builder()
+                .session(session)
+                .groupId(coordinates.getGroupId())
+                .artifactId(coordinates.getArtifactId())
+                .extension(coordinates.getExtension())
+                .classifier(coordinates.getClassifier())
+                .build());
+    }
+
+    /**
+     * If the resolver failed, propagates its exception.
+     *
+     * @param result the resolver result
+     * @throws IOException if the result contains an I/O error
+     */
+    private static void rethrow(DependencyResolverResult result) throws IOException {
+        Exception exception = null;
+        for (Exception cause : result.getExceptions()) {
+            if (cause instanceof UncheckedIOException e) {
+                cause = e.getCause();
+            }
+            if (exception != null) {
+                exception.addSuppressed(cause);
+            } else if (cause instanceof RuntimeException || cause instanceof IOException) {
+                exception = cause;
+            } else {
+                exception = new MojoException("Cannot collect the runtime dependencies.", cause);
+            }
+        }
+        if (exception != null) {
+            if (exception instanceof IOException e) {
+                throw e;
+            } else {
+                throw (RuntimeException) exception; // A ClassCastException here would be a bug in above loop.
+            }
+        }
+    }
+
+    /**
+     * Returns the real paths of the given collections, in iteration order and without duplicated values.
+     */
+    private static Path[] toRealPaths(Collection<Path> moduleRoots, Collection<Path> dependencies) throws IOException {
+        // TODO: use newLinkedHashSet(int) after we are allowed to compile for JDK19.
+        final var paths = new LinkedHashSet<Path>(moduleRoots.size() + dependencies.size());
+        for (Path path : moduleRoots) {
+            paths.add(path.toRealPath());
+        }
+        for (Path path : dependencies) {
+            paths.add(path.toRealPath());
+        }
+        return paths.toArray(Path[]::new);
+    }
+
+    /**
+     * Returns the module descriptor for the {@code module-info.class} at the given path.
+     *
+     * @param moduleInfo path to a {@code module-info.class} file
+     * @return module descriptor for the specified file
+     * @throws IOException if an error occurred while reading the file
+     */
+    private ModuleDescriptor findModuleDescriptor(Path moduleInfo) throws IOException {
+        Path directory = moduleInfo.toRealPath().getParent();
+        ModuleReference reference = fromURI.get(directory.toUri());
+        if (reference != null) {
+            return reference.descriptor();
+        }
+        try (InputStream in = new BufferedInputStream(Files.newInputStream(moduleInfo))) {
+            return ModuleDescriptor.read(in);
+        }
+    }
+
+    /**
+     * Returns the module descriptor for the specified Maven dependency.
+     *
+     * @param dependency dependency for which to get the module descriptor
+     * @return Java module descriptor for the given Maven dependency
+     */
+    private Optional<ModuleDescriptor> findModuleDescriptor(Dependency dependency) {
+        DependencyCoordinates coordinates = coordinateFactory.create(session, dependency);
+        ModuleReference reference = fromDependency.get(coordinates.getId());
+        if (reference == null) {
+            coordinates = withoutVersion(coordinates);
+            reference = fromDependency.get(coordinates.getId());
+            if (reference == null) {
+                return Optional.empty();
+            }
+        }
+        return Optional.of(reference.descriptor());
+    }
+
+    /**
+     * Returns the module descriptor for the specified module name.
+     *
+     * @param moduleName name of the module for which to get the descriptor
+     * @return module descriptor for the specified module name
+     */
+    private Optional<ModuleDescriptor> findModuleDescriptor(String moduleName) {
+        if (moduleFinder == null) {
+            return Optional.empty();
+        }
+        return moduleFinder.find(moduleName).map(ModuleReference::descriptor);
+    }
+
+    /**
+     * Derives a <abbr>POM</abbr> as the intersection of the consumer <abbr>POM</abbr>
+     * and the dependencies required by {@code module-info}.
+     */
+    final class ForModule {
+        /**
+         * Value of the {@code <name>} element in the derived <abbr>POM</abbr>, or {@code null} if none.
+         */
+        private String name;
+
+        /**
+         * Name of the module for which to derive a <abbr>POM</abbr> file.
+         */
+        private final String moduleName;
+
+        /**
+         * Whether a dependency is optional or required only at runtime.
+         */
+        private enum Modifier {
+            OPTIONAL,
+            RUNTIME
+        }
+
+        /**
+         * The required dependencies as Java module names, including transitive dependencies.
+         * Values tell whether the dependency is optional or should have runtime scope.
+         */
+        private final Map<String, EnumSet<Modifier>> requires;
+
+        /**
+         * Path to the <abbr>POM</abbr> file written by this class.
+         */
+        final Path pomFile;
+
+        /**
+         * Creates a new <abbr>POM</abbr> generator for the given archive.
+         *
+         * @param archive the archive for which to generate a <abbr>POM</abbr>
+         * @param manifest manifest to use for deriving project name, or {@code null} if none
+         * @throws IOException if an error occurred while reading the {@code module-info.class} file
+         */
+        ForModule(final Archive archive, final Manifest manifest) throws IOException {
+            moduleName = archive.moduleName;
+            pomFile = derivePathToPOM(archive.jarFile);
+            requires = new LinkedHashMap<>();
+            for (Path file : archive.moduleInfoFiles()) {
+                addDependencies(findModuleDescriptor(file), EnumSet.noneOf(Modifier.class));
+            }
+            if (manifest != null) {
+                name = (String) manifest.getMainAttributes().get(Attributes.Name.IMPLEMENTATION_TITLE);
+                if (name == null) {
+                    name = (String) manifest.getMainAttributes().get(Attributes.Name.SPECIFICATION_TITLE);
+                }
+            }
+        }
+
+        /**
+         * Add the dependencies of the given module, including transitive dependencies.
+         * If the same dependency is added twice with different optional flags,
+         * the {@code false} value (i.e., mandatory dependency) has precedence.
+         *
+         * @param descriptor description of the module for which to add dependencies
+         * @param parentModifiers modifiers of the parent module for which this method adds dependencies
+         */
+        private void addDependencies(final ModuleDescriptor descriptor, final EnumSet<Modifier> parentModifiers) {
+            for (ModuleDescriptor.Requires r : descriptor.requires()) {
+                final EnumSet<Modifier> modifiers = parentModifiers.clone();
+                if (r.modifiers().contains(ModuleDescriptor.Requires.Modifier.STATIC)) {
+                    modifiers.add(Modifier.OPTIONAL);
+                }
+                if (!r.modifiers().contains(ModuleDescriptor.Requires.Modifier.TRANSITIVE)) {
+                    modifiers.add(Modifier.RUNTIME);
+                }
+                EnumSet<Modifier> current = requires.computeIfAbsent(r.name(), (key) -> modifiers);
+                if (EXPAND_TRANSITIVE && (current == modifiers || current.retainAll(modifiers))) {
+                    // Transitive dependencies if not already added or if it needs to update modifiers.
+                    findModuleDescriptor(r.name()).ifPresent((td) -> addDependencies(td, modifiers));
+                }
+            }
+        }
+
+        /**
+         * Derives a <abbr>POM</abbr> file for the archive specified ad construction time.
+         *
+         * @throws IOException if an error occurred while writing the <abbr>POM</abbr> file
+         *
+         * @see #writeParentPOM(Archive)
+         */
+        void writeModulePOM() throws IOException {
+            try {
+                writePOM(deriveModulePOM(), pomFile);
+            } catch (ModelBuilderException | XMLStreamException e) {
+                throw new MojoException("Cannot derive a POM file for the \"" + moduleName + "\" module.", e);
+            }
+        }
+
+        /**
+         * Derives the module <abbr>POM</abbr> file as the intersection of the project <abbr>POM</abbr> and the archive.
+         *
+         * @return intersection of {@link #projectModel} and {@code module-info.class}
+         * @throws ModelBuilderException if an error occurred while building the model
+         */
+        private Model deriveModulePOM() throws ModelBuilderException {
+            Model.Builder builder = Model.newBuilder()
+                    .modelVersion("4.0.0")
+                    .groupId(projectModel.getGroupId())
+                    .artifactId(moduleName)
+                    .version(projectModel.getVersion())
+                    .parent(Parent.newBuilder()
+                            .groupId(projectModel.getGroupId())
+                            .artifactId(projectModel.getArtifactId())
+                            .version(projectModel.getVersion())
+                            .build());
+            if (name != null) {
+                builder = builder.name(name);
+            }
+            /*
+             * Filter the dependencies by keeping only the one declared in a `requires` statement of the
+             * `module-info.class` of the module that we are archiving. Also adjust the `<optional>` and
+             * `<scope>` values. The dependencies that we found are removed from the `requires` map as a
+             * way to make sure that we do not add them twice. In principle, the map should become empty
+             * at the end of this loop.
+             */
+            final List<Dependency> dependencies = projectModel.getDependencies();
+            if (dependencies != null) {
+                final var filteredDependencies = new ArrayList<Dependency>(dependencies.size());
+                for (var iterator = requires.entrySet().iterator(); iterator.hasNext(); ) {
+                    Map.Entry<String, EnumSet<Modifier>> entry = iterator.next();
+                    Dependency dependency = builtModules.get(entry.getKey());
+                    if (dependency != null) {
+                        filteredDependencies.add(amend(dependency, entry.getValue()));
+                        iterator.remove();
+                    }
+                }
+                for (Dependency dependency : dependencies) {
+                    String dependencyModuleName = findModuleDescriptor(dependency)
+                            .map(ModuleDescriptor::name)
+                            .orElse(null);
+                    /*
+                     * If `dependencyModuleName` is null, then the dependency scope is "test" or some other scope
+                     * that resolver has chosen to exclude. Note that this is true even for JAR on the classpath,
+                     * because we stored the automatic module name in `PomDerivation`. Next, if `modifiers` is null,
+                     * then the dependency has compile or runtime scope but is not used by the module to archive.
+                     */
+                    if (dependencyModuleName != null) {
+                        EnumSet<Modifier> modifiers = requires.remove(dependencyModuleName);
+                        if (modifiers != null) {
+                            filteredDependencies.add(amend(dependency, modifiers));
+                        }
+                    }
+                }
+                builder.dependencies(filteredDependencies);
+            }
+            /*
+             * Replace the `<name>` element by the equivalent value defined in MANIFEST.MF.
+             * We do this replacement because the `<name>` of the project model applies to all modules,
+             * while the MANIFEST.MF has more chances to be specific to the module that we are archiving.
+             */
+            return builder.build();
+        }
+
+        /**
+         * Modifies the optional and scope elements of the given dependency according to the given modifiers.
+         *
+         * @param dependency the dependency to amend
+         * @param modifiers the modifiers to apply
+         * @return the amended dependency
+         */
+        private static Dependency amend(Dependency dependency, EnumSet<Modifier> modifiers) {
+            String scope = modifiers.contains(Modifier.RUNTIME) ? "runtime" : null;
+            if (!Objects.equals(scope, dependency.getScope())) {
+                dependency = dependency.withScope(scope);
+            }
+            boolean optional = modifiers.contains(Modifier.OPTIONAL);
+            if (Boolean.parseBoolean(dependency.getOptional()) != optional) {
+                dependency = dependency.withOptional(Boolean.toString(optional));
+            }
+            return dependency;
+        }
+    }
+
+    /**
+     * Writes the parent <abbr>POM</abbr> file as the project file but without the dependencies.
+     * The dependencies are removed because they will declared on a module-by-module basis.
+     *
+     * @param packageHierarchy value of {@link FileCollector#packageHierarchy}
+     * @return path to the file that has been written
+     * @throws IOException if an I/O error occurred while writing the model
+     *
+     * @see ForModule#writeModulePOM()
+     */
+    Path writeParentPOM(final Archive packageHierarchy) throws IOException {
+        Path pomFile = derivePathToPOM(packageHierarchy.jarFile);
+        Model.Builder builder = Model.newBuilder(projectModel, true);
+        builder = builder.root(false).modules(null).subprojects(null);
+        builder = builder.dependencies(null).build(null).reporting(null).distributionManagement(null);
+        builder = builder.preserveModelVersion(false).modelVersion("4.0.0");
+        try {
+            writePOM(builder.build(), pomFile);
+        } catch (ModelBuilderException | XMLStreamException e) {
+            throw new MojoException("Cannot write the parent POM.", e);
+        }
+        return pomFile;
+    }
+
+    /**
+     * Derives the path to the <abbr>POM</abbr> file to generate.
+     *
+     * @param jarFile path to the <abbr>JAR</abbr> file (the file does not need to exist)
+     * @return path to the <abbr>POM</abbr> file to generate
+     */
+    private static Path derivePathToPOM(final Path jarFile) {
+        String filename = jarFile.getFileName().toString();
+        filename = filename.substring(0, filename.lastIndexOf('.') + 1) + "pom";
+        return jarFile.resolveSibling(filename);
+    }
+
+    /**
+     * Writes the given model in the given file.
+     *
+     * @param model the model to write
+     * @param file the destination file
+     * @throws IOException if an I/O error occurred while writing the model
+     * @throws XMLStreamException if a XML error occurred while writing the model
+     */
+    private static void writePOM(Model model, Path file) throws IOException, XMLStreamException {
+        try (BufferedWriter out = Files.newBufferedWriter(file)) {
+            var sw = new MavenStaxWriter();

Review Comment:
   sw --> staxWriter (I first read this as string writer)



##########
src/main/java/org/apache/maven/plugins/jar/TimestampCheck.java:
##########
@@ -0,0 +1,261 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.nio.file.attribute.FileTime;
+import java.util.Collection;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+
+import org.apache.maven.api.plugin.Log;
+
+/**
+ * Checks file timestamps in order to determine if anything changed compared to an existing <abbr>JAR</abbr> file.
+ * This class may scan directories, but only if they have not already been visited by {@link FileCollector}.
+ * The latter can only occur if {@link FileCollector} has no {@code PathMatcher}.
+ * Therefore, this class uses no {@code PathMatcher}.
+ *
+ * <h2>Ignore files</h2>
+ * The {@code META-INF/MANIFEST.MF} file and the {@code META-INF/maven/} directory are ignored.
+ * See {@link #isIgnored(Path)} for the rational.
+ */
+final class TimestampCheck extends SimpleFileVisitor<Path> {
+    /**
+     * The base directory of archived files.
+     */
+    private final Path classesDir;
+
+    /**
+     * Path to the existing <abbr>JAR</abbr> file.
+     */
+    private final Path jarFile;
+
+    /**
+     * The last modified time of the <abbr>JAR</abbr> file.
+     */
+    private final FileTime jarFileTime;
+
+    /**
+     * Where to send non-fatal error messages.
+     */
+    private final Log logger;
+
+    /**
+     * Entries of the <abbr>JAR</abbr> file. Note that getting elements from this enumeration can be costly.
+     * Therefore, we only fetch elements when needed.
+     */
+    private Enumeration<? extends ZipEntry> entries;
+
+    /**
+     * Files found in the <abbr>JAR</abbr> file but not yet traversed by the file visitor.
+     * Files are added lazily when needed, and removed as soon as they have been traversed.
+     * Path are absolute (resolved with {@link #classesDir}).
+     * For each entry, the associated value is whether the path is a directory.
+     */
+    private final Map<Path, Boolean> filesInJAR;
+
+    /**
+     * Some of the files in the build directory. This list contains only the files for which we have already
+     * verified the timestamp. We store them in a separate list for avoiding to check the timestamp twice.

Review Comment:
   for avoiding to check --> to avoid checking



##########
src/main/java/org/apache/maven/plugins/jar/Archive.java:
##########
@@ -0,0 +1,655 @@
+/*
+ * 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.jar;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.TreeMap;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.Type;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.MojoException;
+
+/**
+ * Files or root directories to archive for a single module.
+ * A single instance of {@code Archive} can contain many directories for different target Java releases.
+ * Many instances of {@code Archive} can exist when archiving a multi-modules project.
+ */
+final class Archive {
+    /**
+     * Path to the <abbr>POM</abbr> file generated for this archive, or {@code null} if none.
+     * This is non-null only if module source hierarchy is used, in which case the dependencies
+     * declared in this file are the intersection of the project dependencies and the content of
+     * the {@code module-info.class} file.
+     */
+    @Nullable
+    Path pomFile;
+
+    /**
+     * The <var>JAR</var> file to create. Can be an existing file,
+     * in which case the file creation can be skipped if the file is still up-to-date.
+     */
+    @Nonnull
+    final Path jarFile;
+
+    /**
+     * A helper class for checking whether an existing <abbr>JAR</abbr> file is still up-to-date.
+     * This is null if there is no existing JAR file, or if we determined that the file is outdated.
+     */
+    private TimestampCheck existingJAR;
+
+    /**
+     * Name of the module being archived when the project is using module hierarchy.
+     * This is {@code null} if the project is using package hierarchy, either because it is a classical
+     * class-path project or because it is a single module compiled without using the module hierarchy.
+     * When using module source hierarchy, {@code javac} guarantees that the module name in the output
+     * directory is the name of the parent directory of {@code module-info.class}.
+     */
+    @Nullable
+    final String moduleName;
+
+    /**
+     * Path to {@code META-INF/MANIFEST.MF}, or {@code null} if none.
+     * If non-null, this value will be given to the {@code --manifest} option.
+     * The use of this option is preferable to adding {@code MANIFEST.MF} as an ordinary file.
+     *
+     * @see #setManifest(Path, boolean)
+     * @see #mergeManifest(Path, Manifest)
+     */
+    @Nullable
+    private Path manifest;
+
+    /**
+     * The Maven generated {@code pom.xml} and {@code pom.properties} files, or {@code null} if none.
+     * This first item must be the base directory where the files are located.
+     */
+    @Nullable
+    List<Path> mavenFiles;
+
+    /**
+     * Fully-qualified name of the main class, or {@code null} if none.
+     * This is the value to provide to the {@code --main-class} option.
+     */
+    private String mainClass;
+
+    /**
+     * Files or root directories to store in the <abbr>JAR</abbr> file for each target Java release
+     * other than the base release. Keys are the target Java release with {@code null} for the base
+     * release.
+     */
+    @Nonnull
+    private final NavigableMap<Runtime.Version, FileSet> filesetForRelease;
+
+    /**
+     * Files or root directories to archive for a single target Java release of a single module.
+     * The {@link Archive} enclosing must contain at least one instance of {@code FileSet} for
+     * the base release, and an arbitrary amount of other instances for other target releases.
+     */
+    final class FileSet {
+        /**
+         * The root directory of all files or directories to archive.
+         * This is the value to pass to the {@code -C} tool option.
+         */
+        @Nonnull
+        final Path directory;
+
+        /**
+         * The files or directories to include in the <var>JAR</var> file.
+         * Can be absolute paths or paths relative to {@link #directory}.
+         * It usually contains only the files or directories directly in
+         * the root {@linkplain #directory}, not in sub-directories.
+         */
+        @Nonnull
+        final List<Path> files;
+
+        /**
+         * Creates an initially empty set of files or directories for a specific target Java release.
+         *
+         * @param directory the base directory of the files or directories to archive
+         */
+        private FileSet(Path directory) {
+            this.directory = directory;
+            this.files = new ArrayList<>();
+        }
+
+        /**
+         * 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.
+         * The caller should use that common directory for logging a warning message.
+         *
+         * @param base base directory found by previous invocations of this method, or {@code null} if none
+         * @return common directory of discarded files
+         */
+        private Path discardAllFiles(Path base) {
+            for (Path file : files) {
+                if (base == null) {
+                    base = file.getParent();
+                } else {
+                    while (!file.startsWith(base)) {
+                        base = base.getParent();
+                        if (base == null) {
+                            break;
+                        }
+                    }
+                }
+            }
+            files.clear();
+            return base;
+        }
+
+        /**
+         * Adds the given path to the list of files or directories to archive.
+         * If the given path is a directory, then all children will be included.
+         * Children to exclude, if any, should be managed by {@link ExcludedFiles}.
+         *
+         * @param item a file or directory to archive
+         * @param attributes the file's basic attributes
+         * @param isDirectory whether the file is a directory
+         */
+        void add(Path item, BasicFileAttributes attributes, boolean isDirectory) {
+            TimestampCheck tc = existingJAR;
+            if (tc != null && tc.isUpdated(item, attributes, isDirectory)) {
+                existingJAR = null; // Signal that the existing file is outdated.
+            }
+            files.add(item);
+        }
+
+        /**
+         * Adds to the given list the arguments to provide to the "jar" tool for this version.
+         * The elements added to the list will be instances of {@link String} or {@link Path}.
+         *
+         * <h4>Note about the {@code -C} option</h4>
+         * This method repeats the {@code -C} option before each file.
+         * Our tests suggest that the first file after the directory specified by the {@code -C} option must
+         * be relative to that directory and all files after the first one must be prefixed by the directory
+         * which was specified in the {@code -C} option. This behavior is not very intuitive and replying on
+         * it can be fragile. Furthermore, it seems that the relativized file needs to be the shortest one,
+         * otherwise the {@code jar} tool rejects files after the first one with "names do not match".
+         * Which file is first depends on the unspecified directory-iteration order.
+         * Repeating the {@code -C} option for each file seems safer.
+         *
+         * @param addTo the list to add the arguments as {@link String} or {@link Path} instances to
+         * @param version the target Java release, or {@code null} for the base version of the <abbr>JAR</abbr> file
+         * @throws IllegalArgumentException if a path cannot be made relative to the base directory
+         */
+        private void arguments(List<Object> addTo, Runtime.Version version) {
+            if (files.isEmpty()) {
+                return;
+            }
+            if (version != null) {
+                addTo.add("--release");
+                addTo.add(version);
+            }
+            Path previous = null;
+            for (Path file : files) {
+                if (previous != null && file.startsWith(previous)) {
+                    // Already added a parent directory.
+                    continue;
+                }
+                previous = file;
+                file = directory.relativize(file);
+                if (file.getNameCount() <= 1 && file.toString().isEmpty()) {
+                    /*
+                     * The `-C` directory itself (e.g. a "META-INF/versions/<n>" directory added as a whole).
+                     * An empty file argument is invalid for the `jar` tool (some implementations reject it,
+                     * others silently misbehave), so archive the whole directory content with ".".
+                     */
+                    file = Path.of(".");
+                }
+                addTo.add("-C");
+                addTo.add(directory);
+                addTo.add(file);
+            }
+        }
+
+        /**
+         * {@return a string representation for debugging purposes}
+         */
+        @Override
+        public String toString() {
+            return getClass().getSimpleName() + '[' + directory.getFileName() + ": " + files.size() + " files]";
+        }
+    }
+
+    /**
+     * Creates an initially empty set of files or directories.
+     *
+     * @param jarFile path to the <abbr>JAR</abbr> file to create
+     * @param moduleName the module name if using module hierarchy, or {@code null} if using package hierarchy
+     * @param version the target Java release, or {@code null} for the base version
+     * @param directory the directory of the classes targeting the base Java release
+     * @param forceCreation whether to force a new <abbr>JAR</abbr> file even if the content seems unchanged
+     * @param logger where to send a warning if an error occurred while checking an existing <abbr>JAR</abbr> file
+     */
+    @SuppressWarnings("checkstyle:NeedBraces")
+    Archive(
+            final Path jarFile,
+            final String moduleName,
+            final Runtime.Version version,
+            final Path directory,
+            final boolean forceCreation,
+            final Log logger) {
+        this.jarFile = jarFile;
+        this.moduleName = moduleName;
+        filesetForRelease = new TreeMap<>((v1, v2) -> {
+            if (v1 == v2) return 0;
+            if (v1 == null) return -1;
+            if (v2 == null) return +1;
+            return v1.compareTo(v2);
+        });
+        filesetForRelease.put(version, new FileSet(directory));
+        if (!forceCreation && Files.isRegularFile(jarFile)) {
+            try {
+                existingJAR = new TimestampCheck(jarFile, directory, logger);
+            } catch (IOException e) {
+                // Ignore, we will regenerate the JAR file.
+                logger.warn(e);
+            }
+        }
+    }
+
+    /**
+     * {@return the files or directories to store in the <abbr>JAR</abbr> file for targeting the base Java release}
+     *
+     * @throws NoSuchElementException should not happen unless {@link #prune(boolean)} has been invoked
+     */
+    FileSet baseRelease() {
+        Map.Entry<Runtime.Version, FileSet> entry = filesetForRelease.firstEntry();
+        String message = null;
+        if (entry != null) {
+            Runtime.Version version = entry.getKey();
+            if (version == null) {
+                return entry.getValue();
+            }
+            message = "Expected base version but found version " + version;
+        }
+        throw new NoSuchElementException(message);
+    }
+
+    /**
+     * Returns the {@code module-info.class} files. Conceptually, there is at most once such file per module.
+     * However, more than one file can exist if additional files are provided for additional Java releases.
+     * This method returns only the files that exist.
+     *
+     * @return all {@code module-info.class} files found for all target Java releases
+     */
+    public List<Path> moduleInfoFiles() {
+        var files = new ArrayList<Path>();
+        filesetForRelease.values().forEach((release) -> {
+            Path file = release.directory.resolve(FileCollector.MODULE_DESCRIPTOR_FILE_NAME);
+            if (Files.isRegularFile(file)) {
+                files.add(file);
+            }
+        });
+        return files;
+    }
+
+    /**
+     * Discards all files in this archive, normally because those files are not in any module.
+     * This method returns a common parent directory for all the files that were discarded.
+     * The caller should use that common directory for logging a warning message.
+     *
+     * @return common directory of discarded files, or {@code null} if none
+     */
+    Path discardAllFiles() {
+        Path base = null;
+        for (FileSet release : filesetForRelease.values()) {
+            base = release.discardAllFiles(base);
+        }
+        filesetForRelease.clear();
+        return base;
+    }
+
+    /**
+     * Removes all empty file sets 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}, then this method ensures that at least one file set
+     * remains even if that file set is empty.
+     *
+     * @param skipIfEmpty value of {@link AbstractJarMojo#skipIfEmpty}
+     */
+    public void prune(final boolean skipIfEmpty) {
+        FileSet keep = (skipIfEmpty || isEmpty())
+                ? null
+                : filesetForRelease.firstEntry().getValue();
+        filesetForRelease.values().removeIf((fs) -> fs.files.isEmpty());
+        Iterator<Map.Entry<Runtime.Version, FileSet>> it =
+                filesetForRelease.entrySet().iterator();
+        if (it.hasNext()) {
+            Map.Entry<Runtime.Version, FileSet> first = it.next();
+            if (first.getKey() == null) {
+                return; // Already contains an entry for the base version, nothing to do.
+            }
+            keep = first.getValue();
+            it.remove();
+        }
+        if (keep != null) {
+            filesetForRelease.put(null, keep);
+        }
+    }
+
+    /**
+     * {@return whether this archive has nothing to archive}
+     * This method can return {@code false} even when there is zero file to archive.
+     * It can happen if {@link AbstractJarMojo#skipIfEmpty} is {@code false}. In such case, the

Review Comment:
   In this case



##########
src/main/java/org/apache/maven/plugins/jar/AbstractJarMojo.java:
##########
@@ -207,167 +205,208 @@ protected final Log getLog() {
     protected abstract String getType();
 
     /**
-     * Returns the JAR file to generate, based on an optional classifier.
+     * {@return the scope of dependencies}
+     * It should be {@link PathScope#MAIN_COMPILE} or {@link PathScope#TEST_COMPILE}.
+     * Note that we use compile scope rather than runtime scope because dependencies
+     * cannot appear in {@code requires} statement if they didn't had compile scope.
+     */
+    protected abstract PathScope getDependencyScope();
+
+    /**
+     * {@return the JAR tool to use for archiving the code}
      *
-     * @param basedir the output directory
-     * @param resultFinalName the name of the JAR file
-     * @param classifier an optional classifier
-     * @return the file to generate
+     * @throws MojoException if no JAR tool was found
+     *
+     * @since 4.0.0-beta-2
      */
-    protected Path getJarFile(Path basedir, String resultFinalName, String classifier) {
-        Objects.requireNonNull(basedir, "basedir is not allowed to be null");
-        Objects.requireNonNull(resultFinalName, "finalName is not allowed to be null");
-        String fileName = resultFinalName + (hasClassifier(classifier) ? '-' + classifier : "") + ".jar";
-        return basedir.resolve(fileName);
+    protected ToolProvider getJarTool() throws MojoException {
+        return ToolProvider.findFirst(toolId).orElseThrow(() -> new MojoException("No such \"" + toolId + "\" tool."));
     }
 
     /**
-     * Generates the JAR.
+     * Returns the output time stamp or, as a fallback, the {@code SOURCE_DATE_EPOCH} environment variable.
+     * If the time stamp is expressed in seconds, it is converted to ISO 8601 format. Otherwise it is returned as-is.
      *
-     * @return the path to the created archive file
-     * @throws MojoException in case of an error
+     * @return the time stamp in presumed ISO 8601 format, or {@code null} if none
+     *
+     * @since 4.0.0-beta-2
      */
-    public Path createArchive() throws MojoException {
-        Path basedir = outputDirectory != null
-                ? outputDirectory
-                : Path.of(project.getBuild().getDirectory());
-        String resultFinalName =
-                finalName != null ? finalName : project.getBuild().getFinalName();
-        Path jarFile = getJarFile(basedir, resultFinalName, getClassifier());
-
-        FileSetManager fileSetManager = new FileSetManager();
-        FileSet jarContentFileSet = new FileSet();
-        jarContentFileSet.setDirectory(getClassesDirectory().toAbsolutePath().toString());
-        jarContentFileSet.setIncludes(Arrays.asList(getIncludes()));
-        jarContentFileSet.setExcludes(Arrays.asList(getExcludes()));
-
-        String[] includedFiles = fileSetManager.getIncludedFiles(jarContentFileSet);
-
-        if (detectMultiReleaseJar
-                && Arrays.stream(includedFiles)
-                        .anyMatch(
-                                p -> p.startsWith("META-INF" + File.separatorChar + "versions" + File.separatorChar))) {
-            getLog().debug("Adding 'Multi-Release: true' manifest entry.");
-            archive.addManifestEntry(Attributes.Name.MULTI_RELEASE.toString(), "true");
+    protected String getOutputTimestamp() {
+        String time = nullIfAbsent(outputTimestamp);
+        if (time == null) {
+            time = nullIfAbsent(System.getenv("SOURCE_DATE_EPOCH"));
+            if (time == null) {
+                return null;
+            }
         }
+        if (Runtime.version().feature() < ToolExecutor.JDK_SUPPORT_DATE) {
+            log.warn("Reproducible build requires Java " + ToolExecutor.JDK_SUPPORT_DATE + " or later.");
+            return null;
+        }
+        for (int i = time.length(); --i >= 0; ) {
+            char c = time.charAt(i);
+            if ((c < '0' || c > '9') && (i != 0 || c != '-')) {
+                return time;
+            }
+        }
+        return Instant.ofEpochSecond(Long.parseLong(time)).toString();
+    }
 
-        // May give false positives if the files is named as module descriptor
-        // but is not in the root of the archive or in the versioned area
-        // (and hence not actually a module descriptor).
-        // That is fine since the modular Jar archiver will gracefully
-        // handle such case.
-        // And also such case is unlikely to happen as file ending
-        // with "module-info.class" is unlikely to be included in Jar file
-        // unless it is a module descriptor.
-        boolean containsModuleDescriptor =
-                Arrays.stream(includedFiles).anyMatch(p -> p.endsWith(MODULE_DESCRIPTOR_FILE_NAME));
-
-        String archiverName = containsModuleDescriptor ? "mjar" : "jar";
+    /**
+     * {@return the patterns of files to include, or an empty list if no include pattern was specified}
+     */
+    protected List<String> getIncludes() {
+        return asList(includes);
+    }
 
-        MavenArchiver archiver = new MavenArchiver();
-        archiver.setCreatedBy("Maven JAR Plugin", "org.apache.maven.plugins", "maven-jar-plugin");
-        archiver.setBuildJdkSpecDefaultEntry(archive.getManifest().isAddBuildEnvironmentEntries());
-        archiver.setArchiver((JarArchiver) archivers.get(archiverName));
-        archiver.setOutputFile(jarFile.toFile());
+    /**
+     * {@return the patterns of files to exclude, or an empty list if no exclude pattern was specified}
+     */
+    protected List<String> getExcludes() {
+        return asList(excludes);
+    }
 
-        // configure for Reproducible Builds based on outputTimestamp value
-        archiver.configureReproducibleBuild(outputTimestamp);
+    /**
+     * Returns the output directory and ensures that the directory exists.
+     * The returned directory will be either {@link #outputDirectory} if non-null,
+     * or {@link org.apache.maven.api.model.Build#getDirectory()} otherwise.
+     *
+     * <p>The directory is usually {@code target} and should always exist since it is usually the output
+     * of the compiler plugin. If nevertheless the directory does not exist, then this method creates it.
+     * However, this method does not try to create the parent directory, which should be the Maven sub-project.</p>
+     *
+     * @return the directory containing the generated <abbr>JAR</abbr> files.
+     * @throws IOException if the output directory did not existed and could not be created
+     */
+    protected Path getOutputDirectory() throws IOException {
+        Path dir = outputDirectory;
+        if (dir == null) {
+            dir = Path.of(project.getBuild().getDirectory());
+        }
+        if (Files.notExists(dir)) {
+            dir = Files.createDirectory(dir);
+        }
+        return dir;
+    }
 
-        archive.setForced(forceCreation);
+    /**
+     * Returns the given elements as a list if non-null.
+     *
+     * @param elements the elements, or {@code null}
+     * @return the elements as a list, or {@code null} if the given array was null
+     */
+    private static List<String> asList(String[] elements) {
+        return (elements == null) ? List.of() : Arrays.asList(elements);
+    }
 
-        try {
-            Path contentDirectory = getClassesDirectory();
-            if (!Files.exists(contentDirectory)) {
-                if (!forceCreation) {
-                    getLog().warn("JAR will be empty - no content was marked for inclusion!");
-                }
-            } else {
-                archiver.getArchiver().addDirectory(contentDirectory.toFile(), getIncludes(), getExcludes());
+    /**
+     * Generates the <abbr>JAR</abbr> files.
+     * Map keys are module names or {@code null} if the project does not use module hierarchy.
+     * Values are (<var>type</var>, <var>path</var>) pairs associated with each module where
+     * <var>type</var> is {@code "pom"}, {@code "jar"} or {@code "test-jar"} and <var>path</var>
+     * is the path to the <abbr>POM</abbr> or <abbr>JAR</abbr> file.
+     *
+     * <p>Note that a null key does not necessarily means that the <abbr>JAR</abbr> is not modular.
+     * It only means that the project was not compiled with module hierarchy,
+     * i.e. {@code target/classes/} subdirectories having module names.
+     * A project can be compiled with package hierarchy and still be modular.</p>
+     *
+     * @return the paths to the created archive files
+     * @throws IOException if an error occurred while walking the file tree
+     * @throws MojoException if an error occurred while writing a <abbr>JAR</abbr> file
+     */
+    public Map<String, Map<String, Path>> createArchives() throws IOException, MojoException {
+        final Path classesDirectory = getClassesDirectory();
+        final boolean notExists = Files.notExists(classesDirectory);
+        if (notExists) {
+            if (forceCreation) {
+                log.warn("No JAR created because no content was marked for inclusion.");
+            }
+            if (skipIfEmpty) {
+                log.info(String.format("Skipping packaging of the %s.", getType()));
+                return Map.of();
             }
-
-            archiver.createArchive(session, project, archive);
-
-            return jarFile;
-        } catch (Exception e) {
-            // TODO: improve error handling
-            throw new MojoException("Error assembling JAR", e);
         }
+        archive.setForced(forceCreation);
+        // TODO: we want a null manifest if there is no <archive> configuration.
+        final var archiver = new MavenArchiver();
+        archiver.setCreatedBy("Maven JAR Plugin", "org.apache.maven.plugins", "maven-jar-plugin");
+        archiver.setBuildJdkSpecDefaultEntry(archive.getManifest().isAddBuildEnvironmentEntries());
+        var executor = new ToolExecutor(this, archiver.getManifest(session, project, archive), archive);
+        var files = new FileCollector(this, executor, classesDirectory, matcherFactory);
+        if (!notExists) {
+            Files.walkFileTree(classesDirectory, files);
+        }
+        files.prune(skipIfEmpty);
+        List<Path> moduleRoots = files.getModuleHierarchyRoots();
+        if (!moduleRoots.isEmpty()) {
+            executor.pomDerivation = new PomDerivation(this, moduleRoots);
+        }
+        return executor.writeAllJARs(files);
     }
 
     /**
-     * Generates the JAR.
+     * Generates the <abbr>JAR</abbr> file, then attaches the artifact.
      *
      * @throws MojoException in case of an error
      */
     @Override
+    @SuppressWarnings("UseSpecificCatch")
     public void execute() throws MojoException {
-        if (skipIfEmpty && isEmpty(getClassesDirectory())) {
-            getLog().info(String.format("Skipping packaging of the %s.", getType()));
-        } else {
-            Path jarFile = createArchive();
-
-            if (attach) {
-                ProducedArtifact artifact;
-                String classifier = getClassifier();
-                if (hasClassifier(classifier)) {
-                    artifact = session.createProducedArtifact(
-                            project.getGroupId(),
-                            project.getArtifactId(),
-                            project.getVersion(),
-                            classifier,
-                            null,
-                            getType());
-                } else {
-                    if (projectHasAlreadySetAnArtifact()) {
-                        throw new MojoException("You have to use a classifier "
-                                + "to attach supplemental artifacts to the project instead of replacing them.");
+        final Map<String, Map<String, Path>> artifactFiles;
+        try {
+            artifactFiles = createArchives();
+        } catch (MojoException e) {
+            throw e;
+        } catch (Exception e) {

Review Comment:
   You don't need to worry about that. Checked exceptions are caught by the compiler. Unchecked exceptions are bugs in the code we want to be alerted toi.



##########
src/main/java/org/apache/maven/plugins/jar/Archive.java:
##########
@@ -0,0 +1,655 @@
+/*
+ * 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.jar;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.TreeMap;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.Type;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.MojoException;
+
+/**
+ * Files or root directories to archive for a single module.
+ * A single instance of {@code Archive} can contain many directories for different target Java releases.
+ * Many instances of {@code Archive} can exist when archiving a multi-modules project.
+ */
+final class Archive {
+    /**
+     * Path to the <abbr>POM</abbr> file generated for this archive, or {@code null} if none.
+     * This is non-null only if module source hierarchy is used, in which case the dependencies
+     * declared in this file are the intersection of the project dependencies and the content of
+     * the {@code module-info.class} file.
+     */
+    @Nullable
+    Path pomFile;
+
+    /**
+     * The <var>JAR</var> file to create. Can be an existing file,
+     * in which case the file creation can be skipped if the file is still up-to-date.
+     */
+    @Nonnull
+    final Path jarFile;
+
+    /**
+     * A helper class for checking whether an existing <abbr>JAR</abbr> file is still up-to-date.
+     * This is null if there is no existing JAR file, or if we determined that the file is outdated.
+     */
+    private TimestampCheck existingJAR;
+
+    /**
+     * Name of the module being archived when the project is using module hierarchy.
+     * This is {@code null} if the project is using package hierarchy, either because it is a classical
+     * class-path project or because it is a single module compiled without using the module hierarchy.
+     * When using module source hierarchy, {@code javac} guarantees that the module name in the output
+     * directory is the name of the parent directory of {@code module-info.class}.
+     */
+    @Nullable
+    final String moduleName;
+
+    /**
+     * Path to {@code META-INF/MANIFEST.MF}, or {@code null} if none.
+     * If non-null, this value will be given to the {@code --manifest} option.
+     * The use of this option is preferable to adding {@code MANIFEST.MF} as an ordinary file.
+     *
+     * @see #setManifest(Path, boolean)
+     * @see #mergeManifest(Path, Manifest)
+     */
+    @Nullable
+    private Path manifest;
+
+    /**
+     * The Maven generated {@code pom.xml} and {@code pom.properties} files, or {@code null} if none.
+     * This first item must be the base directory where the files are located.
+     */
+    @Nullable
+    List<Path> mavenFiles;
+
+    /**
+     * Fully-qualified name of the main class, or {@code null} if none.
+     * This is the value to provide to the {@code --main-class} option.
+     */
+    private String mainClass;
+
+    /**
+     * Files or root directories to store in the <abbr>JAR</abbr> file for each target Java release
+     * other than the base release. Keys are the target Java release with {@code null} for the base
+     * release.
+     */
+    @Nonnull
+    private final NavigableMap<Runtime.Version, FileSet> filesetForRelease;
+
+    /**
+     * Files or root directories to archive for a single target Java release of a single module.
+     * The {@link Archive} enclosing must contain at least one instance of {@code FileSet} for
+     * the base release, and an arbitrary amount of other instances for other target releases.
+     */
+    final class FileSet {
+        /**
+         * The root directory of all files or directories to archive.
+         * This is the value to pass to the {@code -C} tool option.
+         */
+        @Nonnull
+        final Path directory;
+
+        /**
+         * The files or directories to include in the <var>JAR</var> file.
+         * Can be absolute paths or paths relative to {@link #directory}.
+         * It usually contains only the files or directories directly in
+         * the root {@linkplain #directory}, not in sub-directories.
+         */
+        @Nonnull
+        final List<Path> files;
+
+        /**
+         * Creates an initially empty set of files or directories for a specific target Java release.
+         *
+         * @param directory the base directory of the files or directories to archive
+         */
+        private FileSet(Path directory) {
+            this.directory = directory;
+            this.files = new ArrayList<>();
+        }
+
+        /**
+         * 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.
+         * The caller should use that common directory for logging a warning message.
+         *
+         * @param base base directory found by previous invocations of this method, or {@code null} if none
+         * @return common directory of discarded files
+         */
+        private Path discardAllFiles(Path base) {
+            for (Path file : files) {
+                if (base == null) {
+                    base = file.getParent();
+                } else {
+                    while (!file.startsWith(base)) {
+                        base = base.getParent();
+                        if (base == null) {
+                            break;
+                        }
+                    }
+                }
+            }
+            files.clear();
+            return base;
+        }
+
+        /**
+         * Adds the given path to the list of files or directories to archive.
+         * If the given path is a directory, then all children will be included.
+         * Children to exclude, if any, should be managed by {@link ExcludedFiles}.
+         *
+         * @param item a file or directory to archive
+         * @param attributes the file's basic attributes
+         * @param isDirectory whether the file is a directory
+         */
+        void add(Path item, BasicFileAttributes attributes, boolean isDirectory) {
+            TimestampCheck tc = existingJAR;
+            if (tc != null && tc.isUpdated(item, attributes, isDirectory)) {
+                existingJAR = null; // Signal that the existing file is outdated.
+            }
+            files.add(item);
+        }
+
+        /**
+         * Adds to the given list the arguments to provide to the "jar" tool for this version.
+         * The elements added to the list will be instances of {@link String} or {@link Path}.
+         *
+         * <h4>Note about the {@code -C} option</h4>
+         * This method repeats the {@code -C} option before each file.
+         * Our tests suggest that the first file after the directory specified by the {@code -C} option must
+         * be relative to that directory and all files after the first one must be prefixed by the directory
+         * which was specified in the {@code -C} option. This behavior is not very intuitive and replying on
+         * it can be fragile. Furthermore, it seems that the relativized file needs to be the shortest one,
+         * otherwise the {@code jar} tool rejects files after the first one with "names do not match".
+         * Which file is first depends on the unspecified directory-iteration order.
+         * Repeating the {@code -C} option for each file seems safer.
+         *
+         * @param addTo the list to add the arguments as {@link String} or {@link Path} instances to
+         * @param version the target Java release, or {@code null} for the base version of the <abbr>JAR</abbr> file
+         * @throws IllegalArgumentException if a path cannot be made relative to the base directory
+         */
+        private void arguments(List<Object> addTo, Runtime.Version version) {
+            if (files.isEmpty()) {
+                return;
+            }
+            if (version != null) {
+                addTo.add("--release");
+                addTo.add(version);
+            }
+            Path previous = null;
+            for (Path file : files) {
+                if (previous != null && file.startsWith(previous)) {
+                    // Already added a parent directory.
+                    continue;
+                }
+                previous = file;
+                file = directory.relativize(file);
+                if (file.getNameCount() <= 1 && file.toString().isEmpty()) {
+                    /*
+                     * The `-C` directory itself (e.g. a "META-INF/versions/<n>" directory added as a whole).
+                     * An empty file argument is invalid for the `jar` tool (some implementations reject it,
+                     * others silently misbehave), so archive the whole directory content with ".".
+                     */
+                    file = Path.of(".");
+                }
+                addTo.add("-C");
+                addTo.add(directory);
+                addTo.add(file);
+            }
+        }
+
+        /**
+         * {@return a string representation for debugging purposes}
+         */
+        @Override
+        public String toString() {
+            return getClass().getSimpleName() + '[' + directory.getFileName() + ": " + files.size() + " files]";
+        }
+    }
+
+    /**
+     * Creates an initially empty set of files or directories.
+     *
+     * @param jarFile path to the <abbr>JAR</abbr> file to create
+     * @param moduleName the module name if using module hierarchy, or {@code null} if using package hierarchy
+     * @param version the target Java release, or {@code null} for the base version
+     * @param directory the directory of the classes targeting the base Java release
+     * @param forceCreation whether to force a new <abbr>JAR</abbr> file even if the content seems unchanged
+     * @param logger where to send a warning if an error occurred while checking an existing <abbr>JAR</abbr> file
+     */
+    @SuppressWarnings("checkstyle:NeedBraces")
+    Archive(
+            final Path jarFile,
+            final String moduleName,
+            final Runtime.Version version,
+            final Path directory,
+            final boolean forceCreation,
+            final Log logger) {
+        this.jarFile = jarFile;
+        this.moduleName = moduleName;
+        filesetForRelease = new TreeMap<>((v1, v2) -> {
+            if (v1 == v2) return 0;
+            if (v1 == null) return -1;
+            if (v2 == null) return +1;
+            return v1.compareTo(v2);
+        });
+        filesetForRelease.put(version, new FileSet(directory));
+        if (!forceCreation && Files.isRegularFile(jarFile)) {
+            try {
+                existingJAR = new TimestampCheck(jarFile, directory, logger);
+            } catch (IOException e) {
+                // Ignore, we will regenerate the JAR file.
+                logger.warn(e);
+            }
+        }
+    }
+
+    /**
+     * {@return the files or directories to store in the <abbr>JAR</abbr> file for targeting the base Java release}
+     *
+     * @throws NoSuchElementException should not happen unless {@link #prune(boolean)} has been invoked
+     */
+    FileSet baseRelease() {
+        Map.Entry<Runtime.Version, FileSet> entry = filesetForRelease.firstEntry();
+        String message = null;
+        if (entry != null) {
+            Runtime.Version version = entry.getKey();
+            if (version == null) {
+                return entry.getValue();
+            }
+            message = "Expected base version but found version " + version;
+        }
+        throw new NoSuchElementException(message);
+    }
+
+    /**
+     * Returns the {@code module-info.class} files. Conceptually, there is at most once such file per module.
+     * However, more than one file can exist if additional files are provided for additional Java releases.
+     * This method returns only the files that exist.
+     *
+     * @return all {@code module-info.class} files found for all target Java releases
+     */
+    public List<Path> moduleInfoFiles() {
+        var files = new ArrayList<Path>();
+        filesetForRelease.values().forEach((release) -> {
+            Path file = release.directory.resolve(FileCollector.MODULE_DESCRIPTOR_FILE_NAME);
+            if (Files.isRegularFile(file)) {
+                files.add(file);
+            }
+        });
+        return files;
+    }
+
+    /**
+     * Discards all files in this archive, normally because those files are not in any module.
+     * This method returns a common parent directory for all the files that were discarded.
+     * The caller should use that common directory for logging a warning message.
+     *
+     * @return common directory of discarded files, or {@code null} if none
+     */
+    Path discardAllFiles() {
+        Path base = null;
+        for (FileSet release : filesetForRelease.values()) {
+            base = release.discardAllFiles(base);
+        }
+        filesetForRelease.clear();
+        return base;
+    }
+
+    /**
+     * Removes all empty file sets 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}, then this method ensures that at least one file set
+     * remains even if that file set is empty.
+     *
+     * @param skipIfEmpty value of {@link AbstractJarMojo#skipIfEmpty}
+     */
+    public void prune(final boolean skipIfEmpty) {
+        FileSet keep = (skipIfEmpty || isEmpty())
+                ? null
+                : filesetForRelease.firstEntry().getValue();
+        filesetForRelease.values().removeIf((fs) -> fs.files.isEmpty());
+        Iterator<Map.Entry<Runtime.Version, FileSet>> it =
+                filesetForRelease.entrySet().iterator();
+        if (it.hasNext()) {
+            Map.Entry<Runtime.Version, FileSet> first = it.next();
+            if (first.getKey() == null) {
+                return; // Already contains an entry for the base version, nothing to do.
+            }
+            keep = first.getValue();
+            it.remove();
+        }
+        if (keep != null) {
+            filesetForRelease.put(null, keep);
+        }
+    }
+
+    /**
+     * {@return whether this archive has nothing to archive}
+     * This method can return {@code false} even when there is zero file to archive.
+     * It can happen if {@link AbstractJarMojo#skipIfEmpty} is {@code false}. In such case, the
+     * "empty" <abbr>JAR</abbr> file will still contain at {@code META-INF/MANIFEST.MF} file.
+     *
+     * <h4>Prerequisites</h4>
+     * The {@link #prune(boolean)} method should be invoked before this method for accurate result.

Review Comment:
   Why not just call prune from this method instead?



##########
src/main/java/org/apache/maven/plugins/jar/ToolExecutor.java:
##########
@@ -0,0 +1,551 @@
+/*
+ * 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.jar;
+
+import javax.lang.model.SourceVersion;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+import java.util.spi.ToolProvider;
+
+import org.apache.maven.api.Project;
+import org.apache.maven.api.Type;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.MojoException;
+import org.apache.maven.shared.archiver.MavenArchiveConfiguration;
+
+/**
+ * Writer of <abbr>JAR</abbr> files using the information collected by {@link FileCollector}.
+ * This class uses the {@code "jar"} tool provided with the <abbr>JDK</abbr>.
+ */
+final class ToolExecutor {
+    /**
+     * First JDK feature version whose {@code jar} tool can run {@code --validate} on archives
+     * that contain records. Earlier {@code jar} tools failed with "This feature requires ASM8"
+     * (JDK-8282446, fixed by JDK-8282508 in JDK 19 by not backported to a 17u or 18u update).
+     *
+     * @see <a href="https://bugs.openjdk.org/browse/JDK-8282446">JDK-8282446</a>
+     * @see <a href="https://bugs.openjdk.org/browse/JDK-8282508">JDK-8282508</a>
+     */
+    private static final int JDK_FIXING_JAR_VALIDATE = 19;
+
+    /**
+     * First JDK feature version whose {@code jar} tool support the {@code --date} option.
+     */
+    private static final int JDK_SUPPORT_DATE = 19;
+
+    /**
+     * The {@value} attribute. Its value is automatically generated by {@link Manifest},
+     * but may need to be replaced by another value if JDK-independent value is desired
+     * for strictly reproducible builds.
+     */
+    private static final String CREATED_BY = "Created-By";
+
+    /**
+     * The Maven project for which to create an archive.
+     */
+    final Project project;
+
+    /**
+     * {@code "jar"} or {@link "test-jar"}.
+     */
+    private final String artifactType;
+
+    /**
+     * The output directory where to write the <abbr>JAR</abbr> file.
+     * This is usually {@code ${baseDir}/target/}.
+     */
+    private final Path outputDirectory;
+
+    /**
+     * The <abbr>JAR</abbr> file name when package hierarchy is used.
+     * This is usually a file placed in the {@link ToolExecutor#outputDirectory} directory.
+     */
+    private final String finalName;
+
+    /**
+     * The classifier (e.g. "test"), or {@code null} if none.
+     */
+    private final String classifier;
+
+    /**
+     * Whether to validate the <abbr>JAR</abbr> file after its creation.
+     * If {@code null}, a value will be determined automatically based on heuristic rules.
+     */
+    private final Boolean validate;
+
+    /**
+     * The tool to use for creating the <abbr>JAR</abbr> files.
+     */
+    private final ToolProvider tool;
+
+    /**
+     * Where to send messages emitted by the "jar" tool.
+     */
+    private final PrintWriter messageWriter;
+
+    /**
+     * Where to send error messages emitted by the "jar" tool.
+     */
+    private final PrintWriter errorWriter;
+
+    /**
+     * Where the messages sent to {@link #messageWriter} are stored.
+     */
+    private final StringBuffer messages;

Review Comment:
   StringBuffer shoudl probably be a StringBuilder unless you need thread safety here



##########
src/test/java/org/apache/maven/plugins/jar/ArchiveTest.java:
##########
@@ -0,0 +1,264 @@
+/*
+ * 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.jar;
+
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Unit tests for {@link Archive}, focused on the two behaviours that are otherwise only
+ * exercised by integration tests whose outcome depends on the (unspecified) filesystem
+ * directory-iteration order, and therefore pass on some platforms while failing on others.
+ */
+class ArchiveTest {
+
+    /**
+     * Creates an {@code Archive} suitable for a unit test. {@code forceCreation = true} skips the
+     * existing-JAR timestamp check, so the (here {@code null}) logger is never dereferenced.
+     */
+    private static Archive archive(String moduleName, Runtime.Version version, Path directory, boolean isReproducible) {
+        return new Archive(directory.resolve("out.jar"), moduleName, version, directory, true, isReproducible, null);
+    }
+
+    /**
+     * Creates a manifest with the main class attribute set to the given value.
+     *
+     * @param value value of the main class attribute
+     * @return a new manifest with the given attribute value
+     */
+    private static Manifest manifestWithMainClass(String value) {
+        Manifest m = new Manifest();
+        Attributes attributes = m.getMainAttributes();
+        attributes.put(Attributes.Name.MANIFEST_VERSION, "1.0");
+        attributes.put(Attributes.Name.MAIN_CLASS, value);
+        return m;
+    }
+
+    /**
+     * Returns the value of the main class attribute.
+     *
+     * @param m the manifest from which to get the value
+     * @return the main class attribute value, or {@code null} if none
+     */
+    private static Object mainClassOf(Manifest m) {
+        return m.getMainAttributes().get(Attributes.Name.MAIN_CLASS);
+    }
+
+    /**
+     * Verifies that {@link Archive#setMainClass(Manifest)} takes ownership for a module-qualified
+     * {@code "module/Class"} main class.
+     *
+     * Note that the {@code "foo.bar/"} prefix in this test (the module name) is a Maven extension.
+     * The standard <abbr>JAR</abbr> specification accepts only the {@code "foo.MainFile"} class name.
+     */
+    @Test
+    void owningModuleClaimsMainClassAndRemovesItFromManifest() {
+        Archive owner = archive("foo.bar", null, Path.of("."), false);
+        Manifest m = manifestWithMainClass("foo.bar/foo.MainFile");
+        // The owner keeps the main class (emitted via --main-class) ...
+        assertTrue(owner.setMainClass(m));
+        // ... and the raw `module/Class` value is removed from the written manifest.
+        assertNull(mainClassOf(m));
+    }
+
+    /**
+     * Verifies that {@link Archive#setMainClass(Manifest)} does <em>not</em> take ownership fo

Review Comment:
   ping



##########
src/main/java/org/apache/maven/plugins/jar/Archive.java:
##########
@@ -0,0 +1,655 @@
+/*
+ * 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.jar;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.TreeMap;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.Type;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.MojoException;
+
+/**
+ * Files or root directories to archive for a single module.
+ * A single instance of {@code Archive} can contain many directories for different target Java releases.
+ * Many instances of {@code Archive} can exist when archiving a multi-modules project.
+ */
+final class Archive {
+    /**
+     * Path to the <abbr>POM</abbr> file generated for this archive, or {@code null} if none.
+     * This is non-null only if module source hierarchy is used, in which case the dependencies
+     * declared in this file are the intersection of the project dependencies and the content of
+     * the {@code module-info.class} file.
+     */
+    @Nullable
+    Path pomFile;
+
+    /**
+     * The <var>JAR</var> file to create. Can be an existing file,
+     * in which case the file creation can be skipped if the file is still up-to-date.
+     */
+    @Nonnull
+    final Path jarFile;
+
+    /**
+     * A helper class for checking whether an existing <abbr>JAR</abbr> file is still up-to-date.
+     * This is null if there is no existing JAR file, or if we determined that the file is outdated.
+     */
+    private TimestampCheck existingJAR;
+
+    /**
+     * Name of the module being archived when the project is using module hierarchy.
+     * This is {@code null} if the project is using package hierarchy, either because it is a classical
+     * class-path project or because it is a single module compiled without using the module hierarchy.
+     * When using module source hierarchy, {@code javac} guarantees that the module name in the output
+     * directory is the name of the parent directory of {@code module-info.class}.
+     */
+    @Nullable
+    final String moduleName;
+
+    /**
+     * Path to {@code META-INF/MANIFEST.MF}, or {@code null} if none.
+     * If non-null, this value will be given to the {@code --manifest} option.
+     * The use of this option is preferable to adding {@code MANIFEST.MF} as an ordinary file.
+     *
+     * @see #setManifest(Path, boolean)
+     * @see #mergeManifest(Path, Manifest)
+     */
+    @Nullable
+    private Path manifest;
+
+    /**
+     * The Maven generated {@code pom.xml} and {@code pom.properties} files, or {@code null} if none.
+     * This first item must be the base directory where the files are located.
+     */
+    @Nullable
+    List<Path> mavenFiles;
+
+    /**
+     * Fully-qualified name of the main class, or {@code null} if none.
+     * This is the value to provide to the {@code --main-class} option.
+     */
+    private String mainClass;
+
+    /**
+     * Files or root directories to store in the <abbr>JAR</abbr> file for each target Java release
+     * other than the base release. Keys are the target Java release with {@code null} for the base
+     * release.
+     */
+    @Nonnull
+    private final NavigableMap<Runtime.Version, FileSet> filesetForRelease;
+
+    /**
+     * Files or root directories to archive for a single target Java release of a single module.
+     * The {@link Archive} enclosing must contain at least one instance of {@code FileSet} for
+     * the base release, and an arbitrary amount of other instances for other target releases.
+     */
+    final class FileSet {
+        /**
+         * The root directory of all files or directories to archive.
+         * This is the value to pass to the {@code -C} tool option.
+         */
+        @Nonnull
+        final Path directory;
+
+        /**
+         * The files or directories to include in the <var>JAR</var> file.
+         * Can be absolute paths or paths relative to {@link #directory}.
+         * It usually contains only the files or directories directly in
+         * the root {@linkplain #directory}, not in sub-directories.
+         */
+        @Nonnull
+        final List<Path> files;
+
+        /**
+         * Creates an initially empty set of files or directories for a specific target Java release.
+         *
+         * @param directory the base directory of the files or directories to archive
+         */
+        private FileSet(Path directory) {
+            this.directory = directory;
+            this.files = new ArrayList<>();
+        }
+
+        /**
+         * 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.
+         * The caller should use that common directory for logging a warning message.
+         *
+         * @param base base directory found by previous invocations of this method, or {@code null} if none
+         * @return common directory of discarded files
+         */
+        private Path discardAllFiles(Path base) {
+            for (Path file : files) {
+                if (base == null) {
+                    base = file.getParent();
+                } else {
+                    while (!file.startsWith(base)) {
+                        base = base.getParent();
+                        if (base == null) {
+                            break;
+                        }
+                    }
+                }
+            }
+            files.clear();
+            return base;
+        }
+
+        /**
+         * Adds the given path to the list of files or directories to archive.
+         * If the given path is a directory, then all children will be included.
+         * Children to exclude, if any, should be managed by {@link ExcludedFiles}.
+         *
+         * @param item a file or directory to archive
+         * @param attributes the file's basic attributes
+         * @param isDirectory whether the file is a directory
+         */
+        void add(Path item, BasicFileAttributes attributes, boolean isDirectory) {
+            TimestampCheck tc = existingJAR;
+            if (tc != null && tc.isUpdated(item, attributes, isDirectory)) {
+                existingJAR = null; // Signal that the existing file is outdated.
+            }
+            files.add(item);
+        }
+
+        /**
+         * Adds to the given list the arguments to provide to the "jar" tool for this version.
+         * The elements added to the list will be instances of {@link String} or {@link Path}.
+         *
+         * <h4>Note about the {@code -C} option</h4>
+         * This method repeats the {@code -C} option before each file.
+         * Our tests suggest that the first file after the directory specified by the {@code -C} option must
+         * be relative to that directory and all files after the first one must be prefixed by the directory
+         * which was specified in the {@code -C} option. This behavior is not very intuitive and replying on
+         * it can be fragile. Furthermore, it seems that the relativized file needs to be the shortest one,
+         * otherwise the {@code jar} tool rejects files after the first one with "names do not match".
+         * Which file is first depends on the unspecified directory-iteration order.
+         * Repeating the {@code -C} option for each file seems safer.
+         *
+         * @param addTo the list to add the arguments as {@link String} or {@link Path} instances to
+         * @param version the target Java release, or {@code null} for the base version of the <abbr>JAR</abbr> file
+         * @throws IllegalArgumentException if a path cannot be made relative to the base directory
+         */
+        private void arguments(List<Object> addTo, Runtime.Version version) {
+            if (files.isEmpty()) {
+                return;
+            }
+            if (version != null) {
+                addTo.add("--release");
+                addTo.add(version);
+            }
+            Path previous = null;
+            for (Path file : files) {
+                if (previous != null && file.startsWith(previous)) {
+                    // Already added a parent directory.
+                    continue;
+                }
+                previous = file;
+                file = directory.relativize(file);
+                if (file.getNameCount() <= 1 && file.toString().isEmpty()) {
+                    /*
+                     * The `-C` directory itself (e.g. a "META-INF/versions/<n>" directory added as a whole).
+                     * An empty file argument is invalid for the `jar` tool (some implementations reject it,
+                     * others silently misbehave), so archive the whole directory content with ".".
+                     */
+                    file = Path.of(".");
+                }
+                addTo.add("-C");
+                addTo.add(directory);
+                addTo.add(file);
+            }
+        }
+
+        /**
+         * {@return a string representation for debugging purposes}
+         */
+        @Override
+        public String toString() {
+            return getClass().getSimpleName() + '[' + directory.getFileName() + ": " + files.size() + " files]";
+        }
+    }
+
+    /**
+     * Creates an initially empty set of files or directories.
+     *
+     * @param jarFile path to the <abbr>JAR</abbr> file to create
+     * @param moduleName the module name if using module hierarchy, or {@code null} if using package hierarchy
+     * @param version the target Java release, or {@code null} for the base version
+     * @param directory the directory of the classes targeting the base Java release
+     * @param forceCreation whether to force a new <abbr>JAR</abbr> file even if the content seems unchanged
+     * @param logger where to send a warning if an error occurred while checking an existing <abbr>JAR</abbr> file
+     */
+    @SuppressWarnings("checkstyle:NeedBraces")
+    Archive(
+            final Path jarFile,
+            final String moduleName,
+            final Runtime.Version version,
+            final Path directory,
+            final boolean forceCreation,
+            final Log logger) {
+        this.jarFile = jarFile;
+        this.moduleName = moduleName;
+        filesetForRelease = new TreeMap<>((v1, v2) -> {
+            if (v1 == v2) return 0;
+            if (v1 == null) return -1;
+            if (v2 == null) return +1;
+            return v1.compareTo(v2);
+        });
+        filesetForRelease.put(version, new FileSet(directory));
+        if (!forceCreation && Files.isRegularFile(jarFile)) {
+            try {
+                existingJAR = new TimestampCheck(jarFile, directory, logger);
+            } catch (IOException e) {
+                // Ignore, we will regenerate the JAR file.
+                logger.warn(e);
+            }
+        }
+    }
+
+    /**
+     * {@return the files or directories to store in the <abbr>JAR</abbr> file for targeting the base Java release}
+     *
+     * @throws NoSuchElementException should not happen unless {@link #prune(boolean)} has been invoked
+     */
+    FileSet baseRelease() {
+        Map.Entry<Runtime.Version, FileSet> entry = filesetForRelease.firstEntry();
+        String message = null;
+        if (entry != null) {
+            Runtime.Version version = entry.getKey();
+            if (version == null) {
+                return entry.getValue();
+            }
+            message = "Expected base version but found version " + version;
+        }
+        throw new NoSuchElementException(message);
+    }
+
+    /**
+     * Returns the {@code module-info.class} files. Conceptually, there is at most once such file per module.
+     * However, more than one file can exist if additional files are provided for additional Java releases.
+     * This method returns only the files that exist.
+     *
+     * @return all {@code module-info.class} files found for all target Java releases
+     */
+    public List<Path> moduleInfoFiles() {
+        var files = new ArrayList<Path>();
+        filesetForRelease.values().forEach((release) -> {
+            Path file = release.directory.resolve(FileCollector.MODULE_DESCRIPTOR_FILE_NAME);
+            if (Files.isRegularFile(file)) {
+                files.add(file);
+            }
+        });
+        return files;
+    }
+
+    /**
+     * Discards all files in this archive, normally because those files are not in any module.
+     * This method returns a common parent directory for all the files that were discarded.
+     * The caller should use that common directory for logging a warning message.
+     *
+     * @return common directory of discarded files, or {@code null} if none
+     */
+    Path discardAllFiles() {
+        Path base = null;
+        for (FileSet release : filesetForRelease.values()) {
+            base = release.discardAllFiles(base);
+        }
+        filesetForRelease.clear();
+        return base;
+    }
+
+    /**
+     * Removes all empty file sets 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}, then this method ensures that at least one file set
+     * remains even if that file set is empty.
+     *
+     * @param skipIfEmpty value of {@link AbstractJarMojo#skipIfEmpty}
+     */
+    public void prune(final boolean skipIfEmpty) {
+        FileSet keep = (skipIfEmpty || isEmpty())
+                ? null
+                : filesetForRelease.firstEntry().getValue();
+        filesetForRelease.values().removeIf((fs) -> fs.files.isEmpty());
+        Iterator<Map.Entry<Runtime.Version, FileSet>> it =
+                filesetForRelease.entrySet().iterator();
+        if (it.hasNext()) {
+            Map.Entry<Runtime.Version, FileSet> first = it.next();
+            if (first.getKey() == null) {
+                return; // Already contains an entry for the base version, nothing to do.
+            }
+            keep = first.getValue();
+            it.remove();
+        }
+        if (keep != null) {
+            filesetForRelease.put(null, keep);
+        }
+    }
+
+    /**
+     * {@return whether this archive has nothing to archive}
+     * This method can return {@code false} even when there is zero file to archive.
+     * It can happen if {@link AbstractJarMojo#skipIfEmpty} is {@code false}. In such case, the
+     * "empty" <abbr>JAR</abbr> file will still contain at {@code META-INF/MANIFEST.MF} file.
+     *
+     * <h4>Prerequisites</h4>
+     * The {@link #prune(boolean)} method should be invoked before this method for accurate result.
+     */
+    public boolean isEmpty() {
+        return filesetForRelease.isEmpty();
+    }
+
+    /**
+     * Checks whether the <abbr>JAR</abbr> file already exists and can be reused.
+     * This method verifies that the <abbr>JAR</abbr> file contains all the files to archive,
+     * contains no extra file, and no file to archive is newer than the <abbr>JAR</abbr> file.
+     *
+     * <p>This method can be invoked only once.
+     * If invoked more often, it returns {@code false} on all subsequent invocations.</p>
+     *
+     * @return whether the <abbr>JAR</abbr> file already exists and can be reused
+     */
+    public boolean isUpToDateJAR() {
+        final TimestampCheck tc = existingJAR;

Review Comment:
   tc --> timestampCheck
   
   and in any case these names are very wonky here. something feels off. Timestamps, checks, and JARs are not the same thing. It seems likele one of them is misnamed.



##########
src/main/java/org/apache/maven/plugins/jar/Archive.java:
##########
@@ -0,0 +1,655 @@
+/*
+ * 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.jar;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.TreeMap;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.Type;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.MojoException;
+
+/**
+ * Files or root directories to archive for a single module.
+ * A single instance of {@code Archive} can contain many directories for different target Java releases.
+ * Many instances of {@code Archive} can exist when archiving a multi-modules project.
+ */
+final class Archive {
+    /**
+     * Path to the <abbr>POM</abbr> file generated for this archive, or {@code null} if none.
+     * This is non-null only if module source hierarchy is used, in which case the dependencies
+     * declared in this file are the intersection of the project dependencies and the content of
+     * the {@code module-info.class} file.
+     */
+    @Nullable
+    Path pomFile;
+
+    /**
+     * The <var>JAR</var> file to create. Can be an existing file,
+     * in which case the file creation can be skipped if the file is still up-to-date.
+     */
+    @Nonnull
+    final Path jarFile;
+
+    /**
+     * A helper class for checking whether an existing <abbr>JAR</abbr> file is still up-to-date.
+     * This is null if there is no existing JAR file, or if we determined that the file is outdated.
+     */
+    private TimestampCheck existingJAR;
+
+    /**
+     * Name of the module being archived when the project is using module hierarchy.
+     * This is {@code null} if the project is using package hierarchy, either because it is a classical
+     * class-path project or because it is a single module compiled without using the module hierarchy.
+     * When using module source hierarchy, {@code javac} guarantees that the module name in the output
+     * directory is the name of the parent directory of {@code module-info.class}.
+     */
+    @Nullable
+    final String moduleName;
+
+    /**
+     * Path to {@code META-INF/MANIFEST.MF}, or {@code null} if none.
+     * If non-null, this value will be given to the {@code --manifest} option.
+     * The use of this option is preferable to adding {@code MANIFEST.MF} as an ordinary file.
+     *
+     * @see #setManifest(Path, boolean)
+     * @see #mergeManifest(Path, Manifest)
+     */
+    @Nullable
+    private Path manifest;
+
+    /**
+     * The Maven generated {@code pom.xml} and {@code pom.properties} files, or {@code null} if none.
+     * This first item must be the base directory where the files are located.
+     */
+    @Nullable
+    List<Path> mavenFiles;
+
+    /**
+     * Fully-qualified name of the main class, or {@code null} if none.
+     * This is the value to provide to the {@code --main-class} option.
+     */
+    private String mainClass;
+
+    /**
+     * Files or root directories to store in the <abbr>JAR</abbr> file for each target Java release
+     * other than the base release. Keys are the target Java release with {@code null} for the base
+     * release.
+     */
+    @Nonnull
+    private final NavigableMap<Runtime.Version, FileSet> filesetForRelease;
+
+    /**
+     * Files or root directories to archive for a single target Java release of a single module.
+     * The {@link Archive} enclosing must contain at least one instance of {@code FileSet} for
+     * the base release, and an arbitrary amount of other instances for other target releases.
+     */
+    final class FileSet {
+        /**
+         * The root directory of all files or directories to archive.
+         * This is the value to pass to the {@code -C} tool option.
+         */
+        @Nonnull
+        final Path directory;
+
+        /**
+         * The files or directories to include in the <var>JAR</var> file.
+         * Can be absolute paths or paths relative to {@link #directory}.
+         * It usually contains only the files or directories directly in
+         * the root {@linkplain #directory}, not in sub-directories.
+         */
+        @Nonnull
+        final List<Path> files;
+
+        /**
+         * Creates an initially empty set of files or directories for a specific target Java release.
+         *
+         * @param directory the base directory of the files or directories to archive
+         */
+        private FileSet(Path directory) {
+            this.directory = directory;
+            this.files = new ArrayList<>();
+        }
+
+        /**
+         * 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.
+         * The caller should use that common directory for logging a warning message.
+         *
+         * @param base base directory found by previous invocations of this method, or {@code null} if none
+         * @return common directory of discarded files
+         */
+        private Path discardAllFiles(Path base) {
+            for (Path file : files) {
+                if (base == null) {
+                    base = file.getParent();
+                } else {
+                    while (!file.startsWith(base)) {
+                        base = base.getParent();
+                        if (base == null) {
+                            break;
+                        }
+                    }
+                }
+            }
+            files.clear();
+            return base;
+        }
+
+        /**
+         * Adds the given path to the list of files or directories to archive.
+         * If the given path is a directory, then all children will be included.
+         * Children to exclude, if any, should be managed by {@link ExcludedFiles}.
+         *
+         * @param item a file or directory to archive
+         * @param attributes the file's basic attributes
+         * @param isDirectory whether the file is a directory
+         */
+        void add(Path item, BasicFileAttributes attributes, boolean isDirectory) {
+            TimestampCheck tc = existingJAR;
+            if (tc != null && tc.isUpdated(item, attributes, isDirectory)) {
+                existingJAR = null; // Signal that the existing file is outdated.
+            }
+            files.add(item);
+        }
+
+        /**
+         * Adds to the given list the arguments to provide to the "jar" tool for this version.
+         * The elements added to the list will be instances of {@link String} or {@link Path}.
+         *
+         * <h4>Note about the {@code -C} option</h4>
+         * This method repeats the {@code -C} option before each file.
+         * Our tests suggest that the first file after the directory specified by the {@code -C} option must
+         * be relative to that directory and all files after the first one must be prefixed by the directory
+         * which was specified in the {@code -C} option. This behavior is not very intuitive and replying on
+         * it can be fragile. Furthermore, it seems that the relativized file needs to be the shortest one,
+         * otherwise the {@code jar} tool rejects files after the first one with "names do not match".
+         * Which file is first depends on the unspecified directory-iteration order.
+         * Repeating the {@code -C} option for each file seems safer.
+         *
+         * @param addTo the list to add the arguments as {@link String} or {@link Path} instances to
+         * @param version the target Java release, or {@code null} for the base version of the <abbr>JAR</abbr> file
+         * @throws IllegalArgumentException if a path cannot be made relative to the base directory
+         */
+        private void arguments(List<Object> addTo, Runtime.Version version) {
+            if (files.isEmpty()) {
+                return;
+            }
+            if (version != null) {
+                addTo.add("--release");
+                addTo.add(version);
+            }
+            Path previous = null;
+            for (Path file : files) {
+                if (previous != null && file.startsWith(previous)) {
+                    // Already added a parent directory.
+                    continue;
+                }
+                previous = file;
+                file = directory.relativize(file);
+                if (file.getNameCount() <= 1 && file.toString().isEmpty()) {
+                    /*
+                     * The `-C` directory itself (e.g. a "META-INF/versions/<n>" directory added as a whole).
+                     * An empty file argument is invalid for the `jar` tool (some implementations reject it,
+                     * others silently misbehave), so archive the whole directory content with ".".
+                     */
+                    file = Path.of(".");
+                }
+                addTo.add("-C");
+                addTo.add(directory);
+                addTo.add(file);
+            }
+        }
+
+        /**
+         * {@return a string representation for debugging purposes}
+         */
+        @Override
+        public String toString() {
+            return getClass().getSimpleName() + '[' + directory.getFileName() + ": " + files.size() + " files]";
+        }
+    }
+
+    /**
+     * Creates an initially empty set of files or directories.
+     *
+     * @param jarFile path to the <abbr>JAR</abbr> file to create
+     * @param moduleName the module name if using module hierarchy, or {@code null} if using package hierarchy
+     * @param version the target Java release, or {@code null} for the base version
+     * @param directory the directory of the classes targeting the base Java release
+     * @param forceCreation whether to force a new <abbr>JAR</abbr> file even if the content seems unchanged
+     * @param logger where to send a warning if an error occurred while checking an existing <abbr>JAR</abbr> file
+     */
+    @SuppressWarnings("checkstyle:NeedBraces")
+    Archive(
+            final Path jarFile,
+            final String moduleName,
+            final Runtime.Version version,
+            final Path directory,
+            final boolean forceCreation,
+            final Log logger) {
+        this.jarFile = jarFile;
+        this.moduleName = moduleName;
+        filesetForRelease = new TreeMap<>((v1, v2) -> {
+            if (v1 == v2) return 0;
+            if (v1 == null) return -1;
+            if (v2 == null) return +1;
+            return v1.compareTo(v2);
+        });
+        filesetForRelease.put(version, new FileSet(directory));
+        if (!forceCreation && Files.isRegularFile(jarFile)) {
+            try {
+                existingJAR = new TimestampCheck(jarFile, directory, logger);
+            } catch (IOException e) {
+                // Ignore, we will regenerate the JAR file.
+                logger.warn(e);
+            }
+        }
+    }
+
+    /**
+     * {@return the files or directories to store in the <abbr>JAR</abbr> file for targeting the base Java release}
+     *
+     * @throws NoSuchElementException should not happen unless {@link #prune(boolean)} has been invoked
+     */
+    FileSet baseRelease() {
+        Map.Entry<Runtime.Version, FileSet> entry = filesetForRelease.firstEntry();
+        String message = null;
+        if (entry != null) {
+            Runtime.Version version = entry.getKey();
+            if (version == null) {
+                return entry.getValue();
+            }
+            message = "Expected base version but found version " + version;
+        }
+        throw new NoSuchElementException(message);
+    }
+
+    /**
+     * Returns the {@code module-info.class} files. Conceptually, there is at most once such file per module.
+     * However, more than one file can exist if additional files are provided for additional Java releases.
+     * This method returns only the files that exist.
+     *
+     * @return all {@code module-info.class} files found for all target Java releases
+     */
+    public List<Path> moduleInfoFiles() {
+        var files = new ArrayList<Path>();
+        filesetForRelease.values().forEach((release) -> {
+            Path file = release.directory.resolve(FileCollector.MODULE_DESCRIPTOR_FILE_NAME);
+            if (Files.isRegularFile(file)) {
+                files.add(file);
+            }
+        });
+        return files;
+    }
+
+    /**
+     * Discards all files in this archive, normally because those files are not in any module.
+     * This method returns a common parent directory for all the files that were discarded.
+     * The caller should use that common directory for logging a warning message.
+     *
+     * @return common directory of discarded files, or {@code null} if none
+     */
+    Path discardAllFiles() {
+        Path base = null;
+        for (FileSet release : filesetForRelease.values()) {
+            base = release.discardAllFiles(base);
+        }
+        filesetForRelease.clear();
+        return base;
+    }
+
+    /**
+     * Removes all empty file sets 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}, then this method ensures that at least one file set
+     * remains even if that file set is empty.
+     *
+     * @param skipIfEmpty value of {@link AbstractJarMojo#skipIfEmpty}
+     */
+    public void prune(final boolean skipIfEmpty) {
+        FileSet keep = (skipIfEmpty || isEmpty())
+                ? null
+                : filesetForRelease.firstEntry().getValue();
+        filesetForRelease.values().removeIf((fs) -> fs.files.isEmpty());
+        Iterator<Map.Entry<Runtime.Version, FileSet>> it =
+                filesetForRelease.entrySet().iterator();
+        if (it.hasNext()) {
+            Map.Entry<Runtime.Version, FileSet> first = it.next();
+            if (first.getKey() == null) {
+                return; // Already contains an entry for the base version, nothing to do.
+            }
+            keep = first.getValue();
+            it.remove();
+        }
+        if (keep != null) {
+            filesetForRelease.put(null, keep);
+        }
+    }
+
+    /**
+     * {@return whether this archive has nothing to archive}
+     * This method can return {@code false} even when there is zero file to archive.
+     * It can happen if {@link AbstractJarMojo#skipIfEmpty} is {@code false}. In such case, the
+     * "empty" <abbr>JAR</abbr> file will still contain at {@code META-INF/MANIFEST.MF} file.
+     *
+     * <h4>Prerequisites</h4>
+     * The {@link #prune(boolean)} method should be invoked before this method for accurate result.
+     */
+    public boolean isEmpty() {
+        return filesetForRelease.isEmpty();
+    }
+
+    /**
+     * Checks whether the <abbr>JAR</abbr> file already exists and can be reused.
+     * This method verifies that the <abbr>JAR</abbr> file contains all the files to archive,
+     * contains no extra file, and no file to archive is newer than the <abbr>JAR</abbr> file.
+     *
+     * <p>This method can be invoked only once.
+     * If invoked more often, it returns {@code false} on all subsequent invocations.</p>

Review Comment:
   more often --> more than once



##########
src/main/java/org/apache/maven/plugins/jar/Archive.java:
##########
@@ -0,0 +1,655 @@
+/*
+ * 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.jar;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.TreeMap;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.Type;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.MojoException;
+
+/**
+ * Files or root directories to archive for a single module.
+ * A single instance of {@code Archive} can contain many directories for different target Java releases.
+ * Many instances of {@code Archive} can exist when archiving a multi-modules project.
+ */
+final class Archive {
+    /**
+     * Path to the <abbr>POM</abbr> file generated for this archive, or {@code null} if none.
+     * This is non-null only if module source hierarchy is used, in which case the dependencies
+     * declared in this file are the intersection of the project dependencies and the content of
+     * the {@code module-info.class} file.
+     */
+    @Nullable
+    Path pomFile;
+
+    /**
+     * The <var>JAR</var> file to create. Can be an existing file,
+     * in which case the file creation can be skipped if the file is still up-to-date.
+     */
+    @Nonnull
+    final Path jarFile;
+
+    /**
+     * A helper class for checking whether an existing <abbr>JAR</abbr> file is still up-to-date.
+     * This is null if there is no existing JAR file, or if we determined that the file is outdated.
+     */
+    private TimestampCheck existingJAR;
+
+    /**
+     * Name of the module being archived when the project is using module hierarchy.
+     * This is {@code null} if the project is using package hierarchy, either because it is a classical
+     * class-path project or because it is a single module compiled without using the module hierarchy.
+     * When using module source hierarchy, {@code javac} guarantees that the module name in the output
+     * directory is the name of the parent directory of {@code module-info.class}.
+     */
+    @Nullable
+    final String moduleName;
+
+    /**
+     * Path to {@code META-INF/MANIFEST.MF}, or {@code null} if none.
+     * If non-null, this value will be given to the {@code --manifest} option.
+     * The use of this option is preferable to adding {@code MANIFEST.MF} as an ordinary file.
+     *
+     * @see #setManifest(Path, boolean)
+     * @see #mergeManifest(Path, Manifest)
+     */
+    @Nullable
+    private Path manifest;
+
+    /**
+     * The Maven generated {@code pom.xml} and {@code pom.properties} files, or {@code null} if none.
+     * This first item must be the base directory where the files are located.
+     */
+    @Nullable
+    List<Path> mavenFiles;
+
+    /**
+     * Fully-qualified name of the main class, or {@code null} if none.
+     * This is the value to provide to the {@code --main-class} option.
+     */
+    private String mainClass;
+
+    /**
+     * Files or root directories to store in the <abbr>JAR</abbr> file for each target Java release
+     * other than the base release. Keys are the target Java release with {@code null} for the base
+     * release.
+     */
+    @Nonnull
+    private final NavigableMap<Runtime.Version, FileSet> filesetForRelease;
+
+    /**
+     * Files or root directories to archive for a single target Java release of a single module.
+     * The {@link Archive} enclosing must contain at least one instance of {@code FileSet} for
+     * the base release, and an arbitrary amount of other instances for other target releases.
+     */
+    final class FileSet {
+        /**
+         * The root directory of all files or directories to archive.
+         * This is the value to pass to the {@code -C} tool option.
+         */
+        @Nonnull
+        final Path directory;
+
+        /**
+         * The files or directories to include in the <var>JAR</var> file.
+         * Can be absolute paths or paths relative to {@link #directory}.
+         * It usually contains only the files or directories directly in
+         * the root {@linkplain #directory}, not in sub-directories.
+         */
+        @Nonnull
+        final List<Path> files;
+
+        /**
+         * Creates an initially empty set of files or directories for a specific target Java release.
+         *
+         * @param directory the base directory of the files or directories to archive
+         */
+        private FileSet(Path directory) {
+            this.directory = directory;
+            this.files = new ArrayList<>();
+        }
+
+        /**
+         * 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.
+         * The caller should use that common directory for logging a warning message.
+         *
+         * @param base base directory found by previous invocations of this method, or {@code null} if none
+         * @return common directory of discarded files
+         */
+        private Path discardAllFiles(Path base) {
+            for (Path file : files) {
+                if (base == null) {
+                    base = file.getParent();
+                } else {
+                    while (!file.startsWith(base)) {
+                        base = base.getParent();
+                        if (base == null) {
+                            break;
+                        }
+                    }
+                }
+            }
+            files.clear();
+            return base;
+        }
+
+        /**
+         * Adds the given path to the list of files or directories to archive.
+         * If the given path is a directory, then all children will be included.
+         * Children to exclude, if any, should be managed by {@link ExcludedFiles}.
+         *
+         * @param item a file or directory to archive
+         * @param attributes the file's basic attributes
+         * @param isDirectory whether the file is a directory
+         */
+        void add(Path item, BasicFileAttributes attributes, boolean isDirectory) {
+            TimestampCheck tc = existingJAR;
+            if (tc != null && tc.isUpdated(item, attributes, isDirectory)) {
+                existingJAR = null; // Signal that the existing file is outdated.
+            }
+            files.add(item);
+        }
+
+        /**
+         * Adds to the given list the arguments to provide to the "jar" tool for this version.
+         * The elements added to the list will be instances of {@link String} or {@link Path}.
+         *
+         * <h4>Note about the {@code -C} option</h4>
+         * This method repeats the {@code -C} option before each file.
+         * Our tests suggest that the first file after the directory specified by the {@code -C} option must
+         * be relative to that directory and all files after the first one must be prefixed by the directory
+         * which was specified in the {@code -C} option. This behavior is not very intuitive and replying on
+         * it can be fragile. Furthermore, it seems that the relativized file needs to be the shortest one,
+         * otherwise the {@code jar} tool rejects files after the first one with "names do not match".
+         * Which file is first depends on the unspecified directory-iteration order.
+         * Repeating the {@code -C} option for each file seems safer.
+         *
+         * @param addTo the list to add the arguments as {@link String} or {@link Path} instances to
+         * @param version the target Java release, or {@code null} for the base version of the <abbr>JAR</abbr> file
+         * @throws IllegalArgumentException if a path cannot be made relative to the base directory
+         */
+        private void arguments(List<Object> addTo, Runtime.Version version) {
+            if (files.isEmpty()) {
+                return;
+            }
+            if (version != null) {
+                addTo.add("--release");
+                addTo.add(version);
+            }
+            Path previous = null;
+            for (Path file : files) {
+                if (previous != null && file.startsWith(previous)) {
+                    // Already added a parent directory.
+                    continue;
+                }
+                previous = file;
+                file = directory.relativize(file);
+                if (file.getNameCount() <= 1 && file.toString().isEmpty()) {
+                    /*
+                     * The `-C` directory itself (e.g. a "META-INF/versions/<n>" directory added as a whole).
+                     * An empty file argument is invalid for the `jar` tool (some implementations reject it,
+                     * others silently misbehave), so archive the whole directory content with ".".
+                     */
+                    file = Path.of(".");
+                }
+                addTo.add("-C");
+                addTo.add(directory);
+                addTo.add(file);
+            }
+        }
+
+        /**
+         * {@return a string representation for debugging purposes}
+         */
+        @Override
+        public String toString() {
+            return getClass().getSimpleName() + '[' + directory.getFileName() + ": " + files.size() + " files]";
+        }
+    }
+
+    /**
+     * Creates an initially empty set of files or directories.
+     *
+     * @param jarFile path to the <abbr>JAR</abbr> file to create
+     * @param moduleName the module name if using module hierarchy, or {@code null} if using package hierarchy
+     * @param version the target Java release, or {@code null} for the base version
+     * @param directory the directory of the classes targeting the base Java release
+     * @param forceCreation whether to force a new <abbr>JAR</abbr> file even if the content seems unchanged
+     * @param logger where to send a warning if an error occurred while checking an existing <abbr>JAR</abbr> file
+     */
+    @SuppressWarnings("checkstyle:NeedBraces")
+    Archive(
+            final Path jarFile,
+            final String moduleName,
+            final Runtime.Version version,
+            final Path directory,
+            final boolean forceCreation,
+            final Log logger) {
+        this.jarFile = jarFile;
+        this.moduleName = moduleName;
+        filesetForRelease = new TreeMap<>((v1, v2) -> {
+            if (v1 == v2) return 0;
+            if (v1 == null) return -1;
+            if (v2 == null) return +1;
+            return v1.compareTo(v2);
+        });
+        filesetForRelease.put(version, new FileSet(directory));
+        if (!forceCreation && Files.isRegularFile(jarFile)) {
+            try {
+                existingJAR = new TimestampCheck(jarFile, directory, logger);
+            } catch (IOException e) {
+                // Ignore, we will regenerate the JAR file.
+                logger.warn(e);
+            }
+        }
+    }
+
+    /**
+     * {@return the files or directories to store in the <abbr>JAR</abbr> file for targeting the base Java release}
+     *
+     * @throws NoSuchElementException should not happen unless {@link #prune(boolean)} has been invoked
+     */
+    FileSet baseRelease() {
+        Map.Entry<Runtime.Version, FileSet> entry = filesetForRelease.firstEntry();
+        String message = null;
+        if (entry != null) {
+            Runtime.Version version = entry.getKey();
+            if (version == null) {
+                return entry.getValue();
+            }
+            message = "Expected base version but found version " + version;
+        }
+        throw new NoSuchElementException(message);
+    }
+
+    /**
+     * Returns the {@code module-info.class} files. Conceptually, there is at most once such file per module.
+     * However, more than one file can exist if additional files are provided for additional Java releases.
+     * This method returns only the files that exist.
+     *
+     * @return all {@code module-info.class} files found for all target Java releases
+     */
+    public List<Path> moduleInfoFiles() {
+        var files = new ArrayList<Path>();
+        filesetForRelease.values().forEach((release) -> {
+            Path file = release.directory.resolve(FileCollector.MODULE_DESCRIPTOR_FILE_NAME);
+            if (Files.isRegularFile(file)) {
+                files.add(file);
+            }
+        });
+        return files;
+    }
+
+    /**
+     * Discards all files in this archive, normally because those files are not in any module.
+     * This method returns a common parent directory for all the files that were discarded.
+     * The caller should use that common directory for logging a warning message.
+     *
+     * @return common directory of discarded files, or {@code null} if none
+     */
+    Path discardAllFiles() {
+        Path base = null;
+        for (FileSet release : filesetForRelease.values()) {
+            base = release.discardAllFiles(base);
+        }
+        filesetForRelease.clear();
+        return base;
+    }
+
+    /**
+     * Removes all empty file sets 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}, then this method ensures that at least one file set
+     * remains even if that file set is empty.
+     *
+     * @param skipIfEmpty value of {@link AbstractJarMojo#skipIfEmpty}
+     */
+    public void prune(final boolean skipIfEmpty) {
+        FileSet keep = (skipIfEmpty || isEmpty())
+                ? null
+                : filesetForRelease.firstEntry().getValue();
+        filesetForRelease.values().removeIf((fs) -> fs.files.isEmpty());
+        Iterator<Map.Entry<Runtime.Version, FileSet>> it =
+                filesetForRelease.entrySet().iterator();
+        if (it.hasNext()) {
+            Map.Entry<Runtime.Version, FileSet> first = it.next();
+            if (first.getKey() == null) {
+                return; // Already contains an entry for the base version, nothing to do.
+            }
+            keep = first.getValue();
+            it.remove();
+        }
+        if (keep != null) {
+            filesetForRelease.put(null, keep);
+        }
+    }
+
+    /**
+     * {@return whether this archive has nothing to archive}
+     * This method can return {@code false} even when there is zero file to archive.
+     * It can happen if {@link AbstractJarMojo#skipIfEmpty} is {@code false}. In such case, the
+     * "empty" <abbr>JAR</abbr> file will still contain at {@code META-INF/MANIFEST.MF} file.
+     *
+     * <h4>Prerequisites</h4>
+     * The {@link #prune(boolean)} method should be invoked before this method for accurate result.
+     */
+    public boolean isEmpty() {
+        return filesetForRelease.isEmpty();
+    }
+
+    /**
+     * Checks whether the <abbr>JAR</abbr> file already exists and can be reused.
+     * This method verifies that the <abbr>JAR</abbr> file contains all the files to archive,
+     * contains no extra file, and no file to archive is newer than the <abbr>JAR</abbr> file.
+     *
+     * <p>This method can be invoked only once.
+     * If invoked more often, it returns {@code false} on all subsequent invocations.</p>
+     *
+     * @return whether the <abbr>JAR</abbr> file already exists and can be reused
+     */
+    public boolean isUpToDateJAR() {
+        final TimestampCheck tc = existingJAR;
+        if (tc == null) {
+            return false;
+        }
+        existingJAR = null; // Let GC do its job.
+        return tc.isUpToDateJAR(filesetForRelease.values());
+    }
+
+    /**
+     * Returns an initially empty set of files or directories for the specified target Java release.
+     *
+     * @param directory the base directory of the files to archive
+     * @param version the target Java release, or {@code null} for the base version
+     * @return container where to declare files and directories to archive
+     */
+    FileSet newTargetRelease(Path directory, Runtime.Version version) {
+        return filesetForRelease.computeIfAbsent(version, (key) -> new FileSet(directory));
+    }
+
+    /**
+     * Sets the {@code --main-class} option to the value of the {@code Main-Class} entry of the given manifest.
+     * As an extension, this method accepts the {@code module/classname} syntax (a syntax already used in some
+     * Java tools). If a module is specified, the main class is kept only if the module match. The intent is to
+     * allow users to specify on which module the main class applies when they use plugin configuration.
+     *
+     * <p>This method may modify the {@code content} manifest. Caller must ensure that the given manifest

Review Comment:
   may --> can



##########
src/main/java/org/apache/maven/plugins/jar/ExcludedFiles.java:
##########
@@ -0,0 +1,145 @@
+/*
+ * 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.jar;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardCopyOption;
+import java.util.List;
+
+/**
+ * A list of files to temporarily move outside the directory to package in a <abbr>JAR</abbr> archive.
+ * This is used for excluding files from the <abbr>JAR</abbr> archive according to include/exclude filters.
+ * We move these files for making possible to specify the whole directory to the {@code jar} tool.
+ * This approach is used instead of enumerating files in arguments given to the {@code jar} tool because
+ * such enumeration can not contain directory entries (otherwise the whole directory would be included).
+ * Some software such as Spring applications component scan relies on the presence of directory entries.
+ */
+final class ExcludedFiles implements Closeable {
+    /**
+     * The paths of files or directories to temporarily move in another directory.
+     */
+    private final Path[] original;
+
+    /**
+     * The paths where files or directories were moved.
+     * For each index <var>i</var>, the original path of {@code moved[i]} was {@code original[i]}.
+     */
+    private final Path[] moved;
+
+    /**
+     * Temporary directory which will contain the {@code moved} files.
+     * It should be a parent directory of {@link #original} files for
+     * increasing the chances that it is on the same file system.
+     */
+    private final Path temporaryDirectory;
+
+    /**
+     * Index of the first path which is a directory instead of a file.
+     * All paths before this index in the {@link #original} and {@link #moved} arrays are files.
+     * All paths at this index and after this index are directories.
+     */
+    private final int indexOfFirstDirectory;
+
+    /**
+     * Creates a new list of files to move in a temporary directory.
+     *
+     * @param directory the directory which was scanned for files to include in the <abbr>JAR</abbr>
+     * @param excludedFiles paths of files to temporarily move in another directory
+     * @param excludedDirectories paths of directories to temporarily move in another directory
+     * @throws IOException if an error occurred while creating the temporary directory.
+     */
+    ExcludedFiles(Path directory, List<Path> excludedFiles, List<Path> excludedDirectories) throws IOException {
+        indexOfFirstDirectory = excludedFiles.size();
+        final int nd = excludedDirectories.size();

Review Comment:
   what is nd? numDirectories?



##########
src/main/java/org/apache/maven/plugins/jar/Archive.java:
##########
@@ -0,0 +1,655 @@
+/*
+ * 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.jar;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.TreeMap;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.Type;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.MojoException;
+
+/**
+ * Files or root directories to archive for a single module.
+ * A single instance of {@code Archive} can contain many directories for different target Java releases.
+ * Many instances of {@code Archive} can exist when archiving a multi-modules project.
+ */
+final class Archive {
+    /**
+     * Path to the <abbr>POM</abbr> file generated for this archive, or {@code null} if none.
+     * This is non-null only if module source hierarchy is used, in which case the dependencies
+     * declared in this file are the intersection of the project dependencies and the content of
+     * the {@code module-info.class} file.
+     */
+    @Nullable
+    Path pomFile;
+
+    /**
+     * The <var>JAR</var> file to create. Can be an existing file,
+     * in which case the file creation can be skipped if the file is still up-to-date.
+     */
+    @Nonnull
+    final Path jarFile;
+
+    /**
+     * A helper class for checking whether an existing <abbr>JAR</abbr> file is still up-to-date.
+     * This is null if there is no existing JAR file, or if we determined that the file is outdated.
+     */
+    private TimestampCheck existingJAR;
+
+    /**
+     * Name of the module being archived when the project is using module hierarchy.
+     * This is {@code null} if the project is using package hierarchy, either because it is a classical
+     * class-path project or because it is a single module compiled without using the module hierarchy.
+     * When using module source hierarchy, {@code javac} guarantees that the module name in the output
+     * directory is the name of the parent directory of {@code module-info.class}.
+     */
+    @Nullable
+    final String moduleName;
+
+    /**
+     * Path to {@code META-INF/MANIFEST.MF}, or {@code null} if none.
+     * If non-null, this value will be given to the {@code --manifest} option.
+     * The use of this option is preferable to adding {@code MANIFEST.MF} as an ordinary file.
+     *
+     * @see #setManifest(Path, boolean)
+     * @see #mergeManifest(Path, Manifest)
+     */
+    @Nullable
+    private Path manifest;
+
+    /**
+     * The Maven generated {@code pom.xml} and {@code pom.properties} files, or {@code null} if none.
+     * This first item must be the base directory where the files are located.
+     */
+    @Nullable
+    List<Path> mavenFiles;
+
+    /**
+     * Fully-qualified name of the main class, or {@code null} if none.
+     * This is the value to provide to the {@code --main-class} option.
+     */
+    private String mainClass;
+
+    /**
+     * Files or root directories to store in the <abbr>JAR</abbr> file for each target Java release
+     * other than the base release. Keys are the target Java release with {@code null} for the base
+     * release.
+     */
+    @Nonnull
+    private final NavigableMap<Runtime.Version, FileSet> filesetForRelease;
+
+    /**
+     * Files or root directories to archive for a single target Java release of a single module.
+     * The {@link Archive} enclosing must contain at least one instance of {@code FileSet} for
+     * the base release, and an arbitrary amount of other instances for other target releases.
+     */
+    final class FileSet {
+        /**
+         * The root directory of all files or directories to archive.
+         * This is the value to pass to the {@code -C} tool option.
+         */
+        @Nonnull
+        final Path directory;
+
+        /**
+         * The files or directories to include in the <var>JAR</var> file.
+         * Can be absolute paths or paths relative to {@link #directory}.
+         * It usually contains only the files or directories directly in
+         * the root {@linkplain #directory}, not in sub-directories.
+         */
+        @Nonnull
+        final List<Path> files;
+
+        /**
+         * Creates an initially empty set of files or directories for a specific target Java release.
+         *
+         * @param directory the base directory of the files or directories to archive
+         */
+        private FileSet(Path directory) {
+            this.directory = directory;
+            this.files = new ArrayList<>();
+        }
+
+        /**
+         * 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.
+         * The caller should use that common directory for logging a warning message.
+         *
+         * @param base base directory found by previous invocations of this method, or {@code null} if none
+         * @return common directory of discarded files
+         */
+        private Path discardAllFiles(Path base) {
+            for (Path file : files) {
+                if (base == null) {
+                    base = file.getParent();
+                } else {
+                    while (!file.startsWith(base)) {
+                        base = base.getParent();
+                        if (base == null) {
+                            break;
+                        }
+                    }
+                }
+            }
+            files.clear();
+            return base;
+        }
+
+        /**
+         * Adds the given path to the list of files or directories to archive.
+         * If the given path is a directory, then all children will be included.
+         * Children to exclude, if any, should be managed by {@link ExcludedFiles}.
+         *
+         * @param item a file or directory to archive
+         * @param attributes the file's basic attributes
+         * @param isDirectory whether the file is a directory
+         */
+        void add(Path item, BasicFileAttributes attributes, boolean isDirectory) {
+            TimestampCheck tc = existingJAR;
+            if (tc != null && tc.isUpdated(item, attributes, isDirectory)) {
+                existingJAR = null; // Signal that the existing file is outdated.
+            }
+            files.add(item);
+        }
+
+        /**
+         * Adds to the given list the arguments to provide to the "jar" tool for this version.
+         * The elements added to the list will be instances of {@link String} or {@link Path}.
+         *
+         * <h4>Note about the {@code -C} option</h4>
+         * This method repeats the {@code -C} option before each file.
+         * Our tests suggest that the first file after the directory specified by the {@code -C} option must
+         * be relative to that directory and all files after the first one must be prefixed by the directory
+         * which was specified in the {@code -C} option. This behavior is not very intuitive and replying on
+         * it can be fragile. Furthermore, it seems that the relativized file needs to be the shortest one,
+         * otherwise the {@code jar} tool rejects files after the first one with "names do not match".
+         * Which file is first depends on the unspecified directory-iteration order.
+         * Repeating the {@code -C} option for each file seems safer.
+         *
+         * @param addTo the list to add the arguments as {@link String} or {@link Path} instances to
+         * @param version the target Java release, or {@code null} for the base version of the <abbr>JAR</abbr> file
+         * @throws IllegalArgumentException if a path cannot be made relative to the base directory
+         */
+        private void arguments(List<Object> addTo, Runtime.Version version) {
+            if (files.isEmpty()) {
+                return;
+            }
+            if (version != null) {
+                addTo.add("--release");
+                addTo.add(version);
+            }
+            Path previous = null;
+            for (Path file : files) {
+                if (previous != null && file.startsWith(previous)) {
+                    // Already added a parent directory.
+                    continue;
+                }
+                previous = file;
+                file = directory.relativize(file);
+                if (file.getNameCount() <= 1 && file.toString().isEmpty()) {
+                    /*
+                     * The `-C` directory itself (e.g. a "META-INF/versions/<n>" directory added as a whole).
+                     * An empty file argument is invalid for the `jar` tool (some implementations reject it,
+                     * others silently misbehave), so archive the whole directory content with ".".
+                     */
+                    file = Path.of(".");
+                }
+                addTo.add("-C");
+                addTo.add(directory);
+                addTo.add(file);
+            }
+        }
+
+        /**
+         * {@return a string representation for debugging purposes}
+         */
+        @Override
+        public String toString() {
+            return getClass().getSimpleName() + '[' + directory.getFileName() + ": " + files.size() + " files]";
+        }
+    }
+
+    /**
+     * Creates an initially empty set of files or directories.
+     *
+     * @param jarFile path to the <abbr>JAR</abbr> file to create
+     * @param moduleName the module name if using module hierarchy, or {@code null} if using package hierarchy
+     * @param version the target Java release, or {@code null} for the base version
+     * @param directory the directory of the classes targeting the base Java release
+     * @param forceCreation whether to force a new <abbr>JAR</abbr> file even if the content seems unchanged
+     * @param logger where to send a warning if an error occurred while checking an existing <abbr>JAR</abbr> file
+     */
+    @SuppressWarnings("checkstyle:NeedBraces")
+    Archive(
+            final Path jarFile,
+            final String moduleName,
+            final Runtime.Version version,
+            final Path directory,
+            final boolean forceCreation,
+            final Log logger) {
+        this.jarFile = jarFile;
+        this.moduleName = moduleName;
+        filesetForRelease = new TreeMap<>((v1, v2) -> {
+            if (v1 == v2) return 0;
+            if (v1 == null) return -1;
+            if (v2 == null) return +1;
+            return v1.compareTo(v2);
+        });
+        filesetForRelease.put(version, new FileSet(directory));
+        if (!forceCreation && Files.isRegularFile(jarFile)) {
+            try {
+                existingJAR = new TimestampCheck(jarFile, directory, logger);
+            } catch (IOException e) {
+                // Ignore, we will regenerate the JAR file.
+                logger.warn(e);
+            }
+        }
+    }
+
+    /**
+     * {@return the files or directories to store in the <abbr>JAR</abbr> file for targeting the base Java release}
+     *
+     * @throws NoSuchElementException should not happen unless {@link #prune(boolean)} has been invoked
+     */
+    FileSet baseRelease() {
+        Map.Entry<Runtime.Version, FileSet> entry = filesetForRelease.firstEntry();
+        String message = null;
+        if (entry != null) {
+            Runtime.Version version = entry.getKey();
+            if (version == null) {
+                return entry.getValue();
+            }
+            message = "Expected base version but found version " + version;
+        }
+        throw new NoSuchElementException(message);
+    }
+
+    /**
+     * Returns the {@code module-info.class} files. Conceptually, there is at most once such file per module.
+     * However, more than one file can exist if additional files are provided for additional Java releases.
+     * This method returns only the files that exist.
+     *
+     * @return all {@code module-info.class} files found for all target Java releases
+     */
+    public List<Path> moduleInfoFiles() {
+        var files = new ArrayList<Path>();
+        filesetForRelease.values().forEach((release) -> {
+            Path file = release.directory.resolve(FileCollector.MODULE_DESCRIPTOR_FILE_NAME);
+            if (Files.isRegularFile(file)) {
+                files.add(file);
+            }
+        });
+        return files;
+    }
+
+    /**
+     * Discards all files in this archive, normally because those files are not in any module.
+     * This method returns a common parent directory for all the files that were discarded.
+     * The caller should use that common directory for logging a warning message.
+     *
+     * @return common directory of discarded files, or {@code null} if none
+     */
+    Path discardAllFiles() {
+        Path base = null;
+        for (FileSet release : filesetForRelease.values()) {
+            base = release.discardAllFiles(base);
+        }
+        filesetForRelease.clear();
+        return base;
+    }
+
+    /**
+     * Removes all empty file sets 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}, then this method ensures that at least one file set
+     * remains even if that file set is empty.
+     *
+     * @param skipIfEmpty value of {@link AbstractJarMojo#skipIfEmpty}
+     */
+    public void prune(final boolean skipIfEmpty) {
+        FileSet keep = (skipIfEmpty || isEmpty())
+                ? null
+                : filesetForRelease.firstEntry().getValue();
+        filesetForRelease.values().removeIf((fs) -> fs.files.isEmpty());
+        Iterator<Map.Entry<Runtime.Version, FileSet>> it =
+                filesetForRelease.entrySet().iterator();
+        if (it.hasNext()) {
+            Map.Entry<Runtime.Version, FileSet> first = it.next();
+            if (first.getKey() == null) {
+                return; // Already contains an entry for the base version, nothing to do.
+            }
+            keep = first.getValue();
+            it.remove();
+        }
+        if (keep != null) {
+            filesetForRelease.put(null, keep);
+        }
+    }
+
+    /**
+     * {@return whether this archive has nothing to archive}
+     * This method can return {@code false} even when there is zero file to archive.
+     * It can happen if {@link AbstractJarMojo#skipIfEmpty} is {@code false}. In such case, the
+     * "empty" <abbr>JAR</abbr> file will still contain at {@code META-INF/MANIFEST.MF} file.
+     *
+     * <h4>Prerequisites</h4>
+     * The {@link #prune(boolean)} method should be invoked before this method for accurate result.
+     */
+    public boolean isEmpty() {
+        return filesetForRelease.isEmpty();
+    }
+
+    /**
+     * Checks whether the <abbr>JAR</abbr> file already exists and can be reused.
+     * This method verifies that the <abbr>JAR</abbr> file contains all the files to archive,
+     * contains no extra file, and no file to archive is newer than the <abbr>JAR</abbr> file.
+     *
+     * <p>This method can be invoked only once.
+     * If invoked more often, it returns {@code false} on all subsequent invocations.</p>
+     *
+     * @return whether the <abbr>JAR</abbr> file already exists and can be reused
+     */
+    public boolean isUpToDateJAR() {
+        final TimestampCheck tc = existingJAR;
+        if (tc == null) {
+            return false;
+        }
+        existingJAR = null; // Let GC do its job.
+        return tc.isUpToDateJAR(filesetForRelease.values());
+    }
+
+    /**
+     * Returns an initially empty set of files or directories for the specified target Java release.
+     *
+     * @param directory the base directory of the files to archive
+     * @param version the target Java release, or {@code null} for the base version
+     * @return container where to declare files and directories to archive
+     */
+    FileSet newTargetRelease(Path directory, Runtime.Version version) {
+        return filesetForRelease.computeIfAbsent(version, (key) -> new FileSet(directory));
+    }
+
+    /**
+     * Sets the {@code --main-class} option to the value of the {@code Main-Class} entry of the given manifest.
+     * As an extension, this method accepts the {@code module/classname} syntax (a syntax already used in some
+     * Java tools). If a module is specified, the main class is kept only if the module match. The intent is to
+     * allow users to specify on which module the main class applies when they use plugin configuration.
+     *
+     * <p>This method may modify the {@code content} manifest. Caller must ensure that the given manifest
+     * is not a shared instance. This method returns whether a change has actually been done.</p>
+     *
+     * @param content combination of existing {@code MANIFEST.MF} and manifest inferred from configuration, or null
+     * @return whether the given manifest has been modified by this method
+     */
+    boolean setMainClass(Manifest content) {
+        if (content == null || mainClass != null) {
+            return false;
+        }
+        // We need to remove the attribute, otherwise it will conflict with `--main-class`.
+        mainClass = (String) content.getMainAttributes().remove(Attributes.Name.MAIN_CLASS);
+        if (mainClass != null) {
+            int s = mainClass.indexOf('/');
+            if (s >= 0) {
+                if (mainClass.substring(0, s).strip().equals(moduleName)) {
+                    mainClass = mainClass.substring(s + 1).strip();
+                } else {
+                    mainClass = null; // Main class is defined for another module.
+                }
+            }
+        }
+        return mainClass != null;
+    }
+
+    /**
+     * Sets the {@code --manifest} option to the given value if that option was not already set.
+     *
+     * @param file path to the manifest file
+     * @param force whether to set the manifest even if already set
+     * @return whether the manifest has been set
+     */
+    boolean setManifest(Path file, boolean force) {
+        if (manifest == null || force) {
+            manifest = file;
+            return true;
+        }
+        return false;
+    }
+
+    /**
+     * Merges the manifest of this module with the manifest specified in plugin configuration.
+     * If both {@code file} and {@code content} are non-null, then {@code content} must be the
+     * result of reading {@code file}.
+     *
+     * <p>This method never modifies the given {@code content} object. If manifest are merged,
+     * a new {@link Manifest} instance is created. Therefore, caller can check whether this
+     * method returned a new instance as a way to recognize that a merge occurred.</p>
+     *
+     * <p>If a merge occurs, the content specified to {@link #setManifest(Path)} has precedence.
+     * It should be the {@code target/classes/META-INF/MANIFEST.MF} file (or modular equivalent).</p>
+     *
+     * @param  file     an additional manifest file, or {@code null}
+     * @param  content  the content of {@code file}, or a standalone manifest produced at runtime
+     * @return the merged manifest as a new instance if some changes were necessary
+     * @throws IOException if an error occurred while reading a manifest file
+     */
+    Manifest mergeManifest(Path file, Manifest content) throws IOException {
+        if (manifest == null) {
+            manifest = file;
+        } else if (file != null && Files.isSameFile(file, manifest)) {
+            // Nothing to merge because of the constraint that `content` must be the content of `file`.
+        } else {
+            try (InputStream in = Files.newInputStream(manifest)) {
+                // No need to wrap in `BufferedInputStream`.
+                if (content != null) {
+                    content = new Manifest(content);
+                    content.read(in);
+                } else {
+                    content = new Manifest(in);
+                }
+            }
+        }
+        return content;
+    }
+
+    /**
+     * Adds to the given list the arguments to provide to the "jar" tool for each version.
+     * Elements added to the list must be instances of {@link String} or {@link Path}.
+     * Callers should have added the following options (if applicable) before to invoke this method:
+     *
+     * <ul>
+     *   <li>{@code --create}</li>
+     *   <li>{@code --no-compress}</li>
+     *   <li>{@code --date} followed by the output time stamp</li>
+     *   <li>{@code --module-version} followed by module version</li>
+     *   <li>{@code --hash-modules} followed by patters of module names</li>
+     *   <li>{@code --module-path} followed by module path</li>
+     * </ul>
+     *
+     * This method adds the following options:
+     *
+     * <ul>
+     *   <li>{@code --file} followed by the path to the <abbr>JAR</abbr> file</li>
+     *   <li>{@code --manifest} followed by path to the manifest file</li>
+     *   <li>{@code --main-class} followed by fully qualified name class</li>
+     *   <li>{@code --release} followed by Java target release</li>
+     *   <li>{@code -C} followed by directory</li>
+     *   <li>files or directories to archive</li>
+     * </ul>
+     *
+     * @param addTo the list where to add the arguments as {@link String} or {@link Path} instances
+     */
+    void arguments(final List<Object> addTo) {
+        addTo.add("--file");
+        addTo.add(jarFile);
+        if (manifest != null) {
+            addTo.add("--manifest");
+            addTo.add(manifest);
+        }
+        if (mainClass != null) {
+            addTo.add("--main-class");
+            addTo.add(mainClass);
+        }
+        if (mavenFiles != null) {
+            addTo.add("-C");
+            addTo.addAll(mavenFiles);
+        }
+        for (Map.Entry<Runtime.Version, FileSet> entry : filesetForRelease.entrySet()) {
+            entry.getValue().arguments(addTo, entry.getKey());
+        }
+    }
+
+    /**
+     * Adds to the given list the arguments to provide to the "jar" tool for validating the <abbr>JAR</abbr> file.
+     * The file is validated only if requested or, in automatic mode, if the validation was not done implicitly at
+     * <abbr>JAR</abbr> creation time. Implicit validation happens if some {@code --release} options were used.
+     * If {@code true}, this method adds the following options:
+     *
+     * <ul>
+     *   <li>{@code --validate} operation mode</li>
+     *   <li>{@code --file} followed by the path to the <abbr>JAR</abbr> file</li>
+     * </ul>
+     *
+     * @param  validate whether to validate, or {@code null} for automatic based on heuristic rules
+     * @param  addTo the list to add the arguments as {@link String} or {@link Path} instances to
+     * @return whether a validation should be run

Review Comment:
   Why would a method named validate not validate? Something's off here. Either the method should always validate, or it's misnamed.



##########
src/main/java/org/apache/maven/plugins/jar/Archive.java:
##########
@@ -0,0 +1,655 @@
+/*
+ * 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.jar;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.TreeMap;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.Type;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.MojoException;
+
+/**
+ * Files or root directories to archive for a single module.
+ * A single instance of {@code Archive} can contain many directories for different target Java releases.
+ * Many instances of {@code Archive} can exist when archiving a multi-modules project.
+ */
+final class Archive {
+    /**
+     * Path to the <abbr>POM</abbr> file generated for this archive, or {@code null} if none.
+     * This is non-null only if module source hierarchy is used, in which case the dependencies
+     * declared in this file are the intersection of the project dependencies and the content of
+     * the {@code module-info.class} file.
+     */
+    @Nullable
+    Path pomFile;
+
+    /**
+     * The <var>JAR</var> file to create. Can be an existing file,
+     * in which case the file creation can be skipped if the file is still up-to-date.
+     */
+    @Nonnull
+    final Path jarFile;
+
+    /**
+     * A helper class for checking whether an existing <abbr>JAR</abbr> file is still up-to-date.
+     * This is null if there is no existing JAR file, or if we determined that the file is outdated.
+     */
+    private TimestampCheck existingJAR;
+
+    /**
+     * Name of the module being archived when the project is using module hierarchy.
+     * This is {@code null} if the project is using package hierarchy, either because it is a classical
+     * class-path project or because it is a single module compiled without using the module hierarchy.
+     * When using module source hierarchy, {@code javac} guarantees that the module name in the output
+     * directory is the name of the parent directory of {@code module-info.class}.
+     */
+    @Nullable
+    final String moduleName;
+
+    /**
+     * Path to {@code META-INF/MANIFEST.MF}, or {@code null} if none.
+     * If non-null, this value will be given to the {@code --manifest} option.
+     * The use of this option is preferable to adding {@code MANIFEST.MF} as an ordinary file.
+     *
+     * @see #setManifest(Path, boolean)
+     * @see #mergeManifest(Path, Manifest)
+     */
+    @Nullable
+    private Path manifest;
+
+    /**
+     * The Maven generated {@code pom.xml} and {@code pom.properties} files, or {@code null} if none.
+     * This first item must be the base directory where the files are located.
+     */
+    @Nullable
+    List<Path> mavenFiles;
+
+    /**
+     * Fully-qualified name of the main class, or {@code null} if none.
+     * This is the value to provide to the {@code --main-class} option.
+     */
+    private String mainClass;
+
+    /**
+     * Files or root directories to store in the <abbr>JAR</abbr> file for each target Java release
+     * other than the base release. Keys are the target Java release with {@code null} for the base
+     * release.
+     */
+    @Nonnull
+    private final NavigableMap<Runtime.Version, FileSet> filesetForRelease;
+
+    /**
+     * Files or root directories to archive for a single target Java release of a single module.
+     * The {@link Archive} enclosing must contain at least one instance of {@code FileSet} for
+     * the base release, and an arbitrary amount of other instances for other target releases.
+     */
+    final class FileSet {
+        /**
+         * The root directory of all files or directories to archive.
+         * This is the value to pass to the {@code -C} tool option.
+         */
+        @Nonnull
+        final Path directory;
+
+        /**
+         * The files or directories to include in the <var>JAR</var> file.
+         * Can be absolute paths or paths relative to {@link #directory}.
+         * It usually contains only the files or directories directly in
+         * the root {@linkplain #directory}, not in sub-directories.
+         */
+        @Nonnull
+        final List<Path> files;
+
+        /**
+         * Creates an initially empty set of files or directories for a specific target Java release.
+         *
+         * @param directory the base directory of the files or directories to archive
+         */
+        private FileSet(Path directory) {
+            this.directory = directory;
+            this.files = new ArrayList<>();
+        }
+
+        /**
+         * 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.
+         * The caller should use that common directory for logging a warning message.
+         *
+         * @param base base directory found by previous invocations of this method, or {@code null} if none
+         * @return common directory of discarded files
+         */
+        private Path discardAllFiles(Path base) {
+            for (Path file : files) {
+                if (base == null) {
+                    base = file.getParent();
+                } else {
+                    while (!file.startsWith(base)) {
+                        base = base.getParent();
+                        if (base == null) {
+                            break;
+                        }
+                    }
+                }
+            }
+            files.clear();
+            return base;
+        }
+
+        /**
+         * Adds the given path to the list of files or directories to archive.
+         * If the given path is a directory, then all children will be included.
+         * Children to exclude, if any, should be managed by {@link ExcludedFiles}.
+         *
+         * @param item a file or directory to archive
+         * @param attributes the file's basic attributes
+         * @param isDirectory whether the file is a directory
+         */
+        void add(Path item, BasicFileAttributes attributes, boolean isDirectory) {
+            TimestampCheck tc = existingJAR;
+            if (tc != null && tc.isUpdated(item, attributes, isDirectory)) {
+                existingJAR = null; // Signal that the existing file is outdated.
+            }
+            files.add(item);
+        }
+
+        /**
+         * Adds to the given list the arguments to provide to the "jar" tool for this version.
+         * The elements added to the list will be instances of {@link String} or {@link Path}.
+         *
+         * <h4>Note about the {@code -C} option</h4>
+         * This method repeats the {@code -C} option before each file.
+         * Our tests suggest that the first file after the directory specified by the {@code -C} option must
+         * be relative to that directory and all files after the first one must be prefixed by the directory
+         * which was specified in the {@code -C} option. This behavior is not very intuitive and replying on
+         * it can be fragile. Furthermore, it seems that the relativized file needs to be the shortest one,
+         * otherwise the {@code jar} tool rejects files after the first one with "names do not match".
+         * Which file is first depends on the unspecified directory-iteration order.
+         * Repeating the {@code -C} option for each file seems safer.
+         *
+         * @param addTo the list to add the arguments as {@link String} or {@link Path} instances to
+         * @param version the target Java release, or {@code null} for the base version of the <abbr>JAR</abbr> file
+         * @throws IllegalArgumentException if a path cannot be made relative to the base directory
+         */
+        private void arguments(List<Object> addTo, Runtime.Version version) {
+            if (files.isEmpty()) {
+                return;
+            }
+            if (version != null) {
+                addTo.add("--release");
+                addTo.add(version);
+            }
+            Path previous = null;
+            for (Path file : files) {
+                if (previous != null && file.startsWith(previous)) {
+                    // Already added a parent directory.
+                    continue;
+                }
+                previous = file;
+                file = directory.relativize(file);
+                if (file.getNameCount() <= 1 && file.toString().isEmpty()) {
+                    /*
+                     * The `-C` directory itself (e.g. a "META-INF/versions/<n>" directory added as a whole).
+                     * An empty file argument is invalid for the `jar` tool (some implementations reject it,
+                     * others silently misbehave), so archive the whole directory content with ".".
+                     */
+                    file = Path.of(".");
+                }
+                addTo.add("-C");
+                addTo.add(directory);
+                addTo.add(file);
+            }
+        }
+
+        /**
+         * {@return a string representation for debugging purposes}
+         */
+        @Override
+        public String toString() {
+            return getClass().getSimpleName() + '[' + directory.getFileName() + ": " + files.size() + " files]";
+        }
+    }
+
+    /**
+     * Creates an initially empty set of files or directories.
+     *
+     * @param jarFile path to the <abbr>JAR</abbr> file to create
+     * @param moduleName the module name if using module hierarchy, or {@code null} if using package hierarchy
+     * @param version the target Java release, or {@code null} for the base version
+     * @param directory the directory of the classes targeting the base Java release
+     * @param forceCreation whether to force a new <abbr>JAR</abbr> file even if the content seems unchanged
+     * @param logger where to send a warning if an error occurred while checking an existing <abbr>JAR</abbr> file
+     */
+    @SuppressWarnings("checkstyle:NeedBraces")
+    Archive(
+            final Path jarFile,
+            final String moduleName,
+            final Runtime.Version version,
+            final Path directory,
+            final boolean forceCreation,
+            final Log logger) {
+        this.jarFile = jarFile;
+        this.moduleName = moduleName;
+        filesetForRelease = new TreeMap<>((v1, v2) -> {
+            if (v1 == v2) return 0;
+            if (v1 == null) return -1;
+            if (v2 == null) return +1;
+            return v1.compareTo(v2);
+        });
+        filesetForRelease.put(version, new FileSet(directory));
+        if (!forceCreation && Files.isRegularFile(jarFile)) {
+            try {
+                existingJAR = new TimestampCheck(jarFile, directory, logger);
+            } catch (IOException e) {
+                // Ignore, we will regenerate the JAR file.
+                logger.warn(e);
+            }
+        }
+    }
+
+    /**
+     * {@return the files or directories to store in the <abbr>JAR</abbr> file for targeting the base Java release}
+     *
+     * @throws NoSuchElementException should not happen unless {@link #prune(boolean)} has been invoked
+     */
+    FileSet baseRelease() {
+        Map.Entry<Runtime.Version, FileSet> entry = filesetForRelease.firstEntry();
+        String message = null;
+        if (entry != null) {
+            Runtime.Version version = entry.getKey();
+            if (version == null) {
+                return entry.getValue();
+            }
+            message = "Expected base version but found version " + version;
+        }
+        throw new NoSuchElementException(message);
+    }
+
+    /**
+     * Returns the {@code module-info.class} files. Conceptually, there is at most once such file per module.
+     * However, more than one file can exist if additional files are provided for additional Java releases.
+     * This method returns only the files that exist.
+     *
+     * @return all {@code module-info.class} files found for all target Java releases
+     */
+    public List<Path> moduleInfoFiles() {
+        var files = new ArrayList<Path>();
+        filesetForRelease.values().forEach((release) -> {
+            Path file = release.directory.resolve(FileCollector.MODULE_DESCRIPTOR_FILE_NAME);
+            if (Files.isRegularFile(file)) {
+                files.add(file);
+            }
+        });
+        return files;
+    }
+
+    /**
+     * Discards all files in this archive, normally because those files are not in any module.
+     * This method returns a common parent directory for all the files that were discarded.
+     * The caller should use that common directory for logging a warning message.
+     *
+     * @return common directory of discarded files, or {@code null} if none
+     */
+    Path discardAllFiles() {
+        Path base = null;
+        for (FileSet release : filesetForRelease.values()) {
+            base = release.discardAllFiles(base);
+        }
+        filesetForRelease.clear();
+        return base;
+    }
+
+    /**
+     * Removes all empty file sets 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}, then this method ensures that at least one file set
+     * remains even if that file set is empty.
+     *
+     * @param skipIfEmpty value of {@link AbstractJarMojo#skipIfEmpty}
+     */
+    public void prune(final boolean skipIfEmpty) {
+        FileSet keep = (skipIfEmpty || isEmpty())
+                ? null
+                : filesetForRelease.firstEntry().getValue();
+        filesetForRelease.values().removeIf((fs) -> fs.files.isEmpty());
+        Iterator<Map.Entry<Runtime.Version, FileSet>> it =
+                filesetForRelease.entrySet().iterator();
+        if (it.hasNext()) {
+            Map.Entry<Runtime.Version, FileSet> first = it.next();
+            if (first.getKey() == null) {
+                return; // Already contains an entry for the base version, nothing to do.
+            }
+            keep = first.getValue();
+            it.remove();
+        }
+        if (keep != null) {
+            filesetForRelease.put(null, keep);
+        }
+    }
+
+    /**
+     * {@return whether this archive has nothing to archive}
+     * This method can return {@code false} even when there is zero file to archive.
+     * It can happen if {@link AbstractJarMojo#skipIfEmpty} is {@code false}. In such case, the
+     * "empty" <abbr>JAR</abbr> file will still contain at {@code META-INF/MANIFEST.MF} file.
+     *
+     * <h4>Prerequisites</h4>
+     * The {@link #prune(boolean)} method should be invoked before this method for accurate result.
+     */
+    public boolean isEmpty() {
+        return filesetForRelease.isEmpty();
+    }
+
+    /**
+     * Checks whether the <abbr>JAR</abbr> file already exists and can be reused.
+     * This method verifies that the <abbr>JAR</abbr> file contains all the files to archive,
+     * contains no extra file, and no file to archive is newer than the <abbr>JAR</abbr> file.
+     *
+     * <p>This method can be invoked only once.
+     * If invoked more often, it returns {@code false} on all subsequent invocations.</p>
+     *
+     * @return whether the <abbr>JAR</abbr> file already exists and can be reused
+     */
+    public boolean isUpToDateJAR() {
+        final TimestampCheck tc = existingJAR;
+        if (tc == null) {
+            return false;
+        }
+        existingJAR = null; // Let GC do its job.
+        return tc.isUpToDateJAR(filesetForRelease.values());
+    }
+
+    /**
+     * Returns an initially empty set of files or directories for the specified target Java release.
+     *
+     * @param directory the base directory of the files to archive
+     * @param version the target Java release, or {@code null} for the base version
+     * @return container where to declare files and directories to archive
+     */
+    FileSet newTargetRelease(Path directory, Runtime.Version version) {
+        return filesetForRelease.computeIfAbsent(version, (key) -> new FileSet(directory));
+    }
+
+    /**
+     * Sets the {@code --main-class} option to the value of the {@code Main-Class} entry of the given manifest.
+     * As an extension, this method accepts the {@code module/classname} syntax (a syntax already used in some
+     * Java tools). If a module is specified, the main class is kept only if the module match. The intent is to
+     * allow users to specify on which module the main class applies when they use plugin configuration.
+     *
+     * <p>This method may modify the {@code content} manifest. Caller must ensure that the given manifest
+     * is not a shared instance. This method returns whether a change has actually been done.</p>

Review Comment:
   delete actually



##########
src/main/java/org/apache/maven/plugins/jar/ExcludedFiles.java:
##########
@@ -0,0 +1,145 @@
+/*
+ * 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.jar;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardCopyOption;
+import java.util.List;
+
+/**
+ * A list of files to temporarily move outside the directory to package in a <abbr>JAR</abbr> archive.
+ * This is used for excluding files from the <abbr>JAR</abbr> archive according to include/exclude filters.
+ * We move these files for making possible to specify the whole directory to the {@code jar} tool.
+ * This approach is used instead of enumerating files in arguments given to the {@code jar} tool because
+ * such enumeration can not contain directory entries (otherwise the whole directory would be included).

Review Comment:
   cannot



##########
src/main/java/org/apache/maven/plugins/jar/PomDerivation.java:
##########
@@ -0,0 +1,529 @@
+/*
+ * 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.jar;
+
+import javax.xml.stream.XMLStreamException;
+
+import java.io.BufferedInputStream;
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.UncheckedIOException;
+import java.lang.module.ModuleDescriptor;
+import java.lang.module.ModuleFinder;
+import java.lang.module.ModuleReference;
+import java.net.URI;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.DependencyCoordinates;
+import org.apache.maven.api.JavaPathType;
+import org.apache.maven.api.Session;
+import org.apache.maven.api.Type;
+import org.apache.maven.api.model.Dependency;
+import org.apache.maven.api.model.Model;
+import org.apache.maven.api.model.Parent;
+import org.apache.maven.api.plugin.MojoException;
+import org.apache.maven.api.services.DependencyCoordinatesFactory;
+import org.apache.maven.api.services.DependencyCoordinatesFactoryRequest;
+import org.apache.maven.api.services.DependencyResolver;
+import org.apache.maven.api.services.DependencyResolverRequest;
+import org.apache.maven.api.services.DependencyResolverResult;
+import org.apache.maven.api.services.ModelBuilderException;
+import org.apache.maven.model.v4.MavenStaxWriter;
+
+/**
+ * A mapper from Maven model dependencies to Java module names.
+ * A single instance of this class is created for a Maven project,
+ * then shared by all {@link ForModule} instances (one per module to archive).
+ */
+final class PomDerivation {
+    /**
+     * Whether to expand the list of transitive dependencies in the generated <abbr>POM</abbr>.
+     */
+    private static final boolean EXPAND_TRANSITIVE = false;
+
+    /**
+     * Copy of {@link AbstractJarMojo#session}.
+     */
+    private final Session session;
+
+    /**
+     * The project model, which includes dependencies of all modules.
+     */
+    private final Model projectModel;
+
+    /**
+     * The factory to use for creating temporary {@link DependencyCoordinates} instances.
+     */
+    private final DependencyCoordinatesFactory coordinateFactory;
+
+    /**
+     * Provide module descriptors from module names.
+     * May be {@code null} if no {@code module-info} was found.
+     */
+    private final ModuleFinder moduleFinder;
+
+    /**
+     * Module references from paths to the <abbr>JAR</abbr> file or root directory.
+     */
+    private final Map<URI, ModuleReference> fromURI;
+
+    /**
+     * Module names associated with Maven dependencies.
+     * This map contains {@link DependencyCoordinates#getId()} as keys and module references as values.
+     * This is used to detect which dependencies are really used according to {@code module-info.class}.
+     *
+     * @todo The keys should be instances of {@link DependencyCoordinates}. Unfortunately, as of Maven 4.0.0-rc-5
+     *       that interface does not define the {@code equals} and {@code hashCode} contracts.
+     */
+    private final Map<String, ModuleReference> fromDependency;
+
+    /**
+     * Modules that are built by the project. Keys are module names.
+     */
+    private final Map<String, Dependency> builtModules;
+
+    /**
+     * Creates a new mapper from Maven dependency to module name.
+     *
+     * @param mojo the enclosing <abbr>MOJO</abbr>
+     * @param moduleRoots paths to root directories of each module to archive in a module hierarchy
+     * @throws IOException if an I/O error occurred while fetching dependencies
+     * @throws MavenException if an error occurred while fetching dependencies for a reason other than I/O.
+     */
+    PomDerivation(final AbstractJarMojo mojo, final List<Path> moduleRoots) throws IOException {
+        this.session = mojo.session;
+        projectModel = mojo.project.getModel();
+        coordinateFactory = session.getService(DependencyCoordinatesFactory.class);
+        DependencyResolver resolver = session.getService(DependencyResolver.class);
+        DependencyResolverResult result = resolver.resolve(DependencyResolverRequest.builder()
+                .session(session)
+                .project(mojo.project)
+                .requestType(DependencyResolverRequest.RequestType.RESOLVE)
+                .pathScope(mojo.getDependencyScope())
+                .pathTypeFilter(Set.of(JavaPathType.MODULES, JavaPathType.CLASSES))
+                .build());
+
+        rethrow(result);
+        final Map<org.apache.maven.api.Dependency, Path> dependencies = result.getDependencies();
+        final Path[] allModulePaths = toRealPaths(moduleRoots, dependencies.values());
+        fromURI = new HashMap<>(allModulePaths.length); // TODO: use newHashMap with JDK19.
+        moduleFinder = ModuleFinder.of(allModulePaths);
+        if (moduleFinder != null) {
+            for (ModuleReference reference : moduleFinder.findAll()) {
+                reference.location().ifPresent((location) -> fromURI.put(location, reference));
+            }
+        }
+        fromDependency = new HashMap<>(dependencies.size()); // TODO: use newHashMap with JDK19.
+        for (Map.Entry<org.apache.maven.api.Dependency, Path> entry : dependencies.entrySet()) {
+            Path modulePath = entry.getValue().toRealPath();
+            ModuleReference reference = fromURI.get(modulePath.toUri());
+            if (reference != null) {
+                DependencyCoordinates coordinates = entry.getKey().toCoordinates();
+                String id = coordinates.getId();
+                ModuleReference old = fromDependency.putIfAbsent(id, reference);
+                if (old == null) {
+                    coordinates = withoutVersion(coordinates);
+                    id = coordinates.getId();
+                    old = fromDependency.putIfAbsent(id, reference);
+                }
+                if (old != null && !old.equals(reference)) {
+                    mojo.log.warn("The \"" + id + "\" dependency is declared twice with different module names: \""
+                            + old.descriptor().name() + "\" and \""
+                            + reference.descriptor().name() + "\".");
+                }
+            }
+        }
+        builtModules = new HashMap<>(moduleRoots.size()); // TODO: use newHashMap with JDK19.

Review Comment:
   drop the TODO; these cleanups are usually found via static analysis years in the future



##########
src/main/java/org/apache/maven/plugins/jar/FileCollector.java:
##########
@@ -0,0 +1,541 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.PathMatcher;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Deque;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.services.PathMatcherFactory;
+
+/**
+ * Dispatch the files from the output directory into the <abbr>JAR</abbr> files to create.
+ * Instead of just archiving as-is the content of the output directory, this class separates
+ * the following subdirectories to the options listed below:
+ *
+ * <ul>
+ *   <li>The {@code META-INF/MANIFEST.MF} file will be given to the {@code --manifest} option.</li>
+ *   <li>Files in the following directories will be given to the {@code --release} option:
+ *     <ul>
+ *       <li>{@code META-INF/versions/}</li>
+ *       <li>{@code META-INF/versions-modular/<module>/}</li>
+ *       <li>{@code <module>/META-INF/versions/}</li>
+ *     </ul>
+ *   </li>
+ * </ul>
+ *
+ * The reason for using the options is that they allow the {@code jar} tool to perform additional verifications.
+ * For example, when using the {@code --release} option, {@code jar} verifies the <abbr>API</abbr> compatibility.
+ */
+final class FileCollector extends SimpleFileVisitor<Path> {
+    /**
+     * The file to check for deciding whether the <abbr>JAR</abbr> is modular.
+     */
+    static final String MODULE_DESCRIPTOR_FILE_NAME = "module-info.class";
+
+    /**
+     * The {@value} directory.
+     * This is part of <abbr>JAR</abbr> file specification.
+     */
+    private static final String VERSIONS = "versions";
+
+    /**
+     * The {@value} directory.
+     * This is Maven-specific.
+     */
+    private static final String VERSIONS_MODULAR = "versions-modular";
+
+    /**
+     * Context (logger, configuration) in which the <abbr>JAR</abbr> file are created.
+     */
+    private final ToolExecutor context;
+
+    /**
+     * Whether to detect multi-release <abbr>JAR</abbr> files.
+     * The default value is {@code true}.
+     *
+     * @see AbstractJarMojo#detectMultiReleaseJar
+     */
+    private final boolean detectMultiReleaseJar;
+
+    /**
+     * The root directory to traverse. It will be used for temporarily moving excluded files.
+     */
+    private final Path rootDirectory;
+
+    /**
+     * Combination of includes and excludes path matcher applied on files.
+     */
+    @Nonnull
+    private final PathMatcher fileMatcher;
+
+    /**
+     * Combination of includes and excludes path matcher applied on directories.
+     */
+    @Nonnull
+    private final PathMatcher directoryMatcher;
+
+    /**
+     * Files to exclude. These files will be moved to a temporary location
+     * for allowing {@link ToolExecutor} to specify whole directories to the {@code jar} tool.
+     * Specifying whole directories is preferable to enumerating the files because otherwise,
+     * the generated <abbr>JAR</abbr> file contains only entries for the files and is missing
+     * entries for the directories.
+     *
+     * <p>This field is {@code null} if it is not possible to have any excluded file
+     * (because there is no include/exclude filters).</p>
+     */
+    @Nullable
+    private final List<Path> excludedFiles;
+
+    /**
+     * Directories to exclude. This field serves the same purpose as {@link #excludedFiles},
+     * but where the sources a directories instead of files.
+     */
+    @Nullable
+    private final List<Path> excludedDirectories;
+
+    /**
+     * Files found in the output directory when package hierarchy is used.
+     * At most one of {@code packageHierarchy} and {@link #moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Archive packageHierarchy;
+
+    /**
+     * Files found in the output directory when module hierarchy is used. Keys are module names.
+     * At most one of {@link #packageHierarchy} and {@code moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Map<String, Archive> moduleHierarchy;
+
+    /**
+     * The current module being archived. This field is updated every times that {@code FileCollector}
+     * visits a new module directory.
+     */
+    @Nonnull
+    private Archive currentModule;
+
+    /**
+     * The module and target Java release currently being scanned. This field is updated every times that
+     * {@code FileCollector} visits a new module directory or in a new target Java release for a given module.
+     */
+    @Nonnull
+    private Archive.FileSet currentFilesToArchive;
+
+    /**
+     * The current target Java release, or {@code null} if none.
+     */
+    @Nullable
+    private Runtime.Version currentTargetVersion;
+
+    /**
+     * Identification of the kinds of directories being traversed.
+     * The length of this list is the depth in the directory hierarchy.
+     * The last element identifies the type of the current directory.
+     */
+    private final Deque<DirectoryRole> directoryRoles;
+
+    /**
+     * Whether to check when a file is the {@code MANIFEST.MF} file.
+     * This is allowed only when scanning the content of a {@code META-INF} directory.
+     */
+    private boolean checkForManifest;
+
+    /**
+     * Creates a new file collector.
+     *
+     * @param mojo the <abbr>MOJO</abbr> from which to get the configuration
+     * @param context context (logger, configuration) in which the <abbr>JAR</abbr> file are created
+     * @param directory the base directory of the files to archive
+     */
+    FileCollector(AbstractJarMojo mojo, ToolExecutor context, Path directory, PathMatcherFactory matcherFactory) {
+        this.context = context;
+        rootDirectory = directory;
+        detectMultiReleaseJar = mojo.detectMultiReleaseJar;
+        directoryRoles = new ArrayDeque<>();
+        fileMatcher = matcherFactory.createPathMatcher(directory, mojo.getIncludes(), mojo.getExcludes(), false);
+        directoryMatcher = matcherFactory.deriveDirectoryMatcher(fileMatcher);
+        if (matcherFactory.isIncludesAll(fileMatcher) && matcherFactory.isIncludesAll(directoryMatcher)) {
+            excludedFiles = null;
+            excludedDirectories = null;
+        } else {
+            excludedFiles = new ArrayList<>();
+            excludedDirectories = new ArrayList<>();
+        }
+        packageHierarchy = context.newArchive(null, null, directory);
+        moduleHierarchy = new LinkedHashMap<>();
+        resetToPackageHierarchy();
+    }
+
+    /**
+     * Resets this {@code FileCollector} to the state where a package hierarchy is presumed.
+     */
+    private void resetToPackageHierarchy() {
+        currentModule = packageHierarchy;
+        currentFilesToArchive = currentModule.baseRelease();
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a module.
+     * For an output generated by {@code javac} from a module source hierarchy,
+     * the directory name is guaranteed to be the module name.
+     *
+     * @param directory a {@code "<module>"} or {@code "META-INF/versions-modular/<module>"} directory
+     */
+    private void preVisitVersionDirectory(final Path directory) {
+        String moduleName = directory.getFileName().toString();
+        currentModule = moduleHierarchy.computeIfAbsent(
+                moduleName, (name) -> context.newArchive(name, currentTargetVersion, directory));
+        currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a target Java version.
+     * The {@code useDirectly} argument tells whether the content of this directory will be specified directly
+     * as the content to add in the <abbr>JAR</abbr> file. This argument should be {@code false} when there is
+     * another directory level (the module names) to process before to add content.
+     *
+     * @param directory a {@code "META-INF/versions/<n>"} or {@code "META-INF/versions-modular/<n>"} directory
+     * @param useDirectly whether the directory is {@code "META-INF/versions/<n>"}
+     * @return whether to skip the directory because of invalid version number
+     */
+    private boolean preVisitVersionDirectory(final Path directory, final boolean useDirectly) {
+        try {
+            currentTargetVersion = Runtime.Version.parse(directory.getFileName().toString());
+        } catch (IllegalArgumentException e) {
+            context.warnInvalidVersion(directory, e);
+            return true;
+        }
+        if (useDirectly) {
+            currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+        }
+        return false;
+    }
+
+    /**
+     * Determines if the given directory should be scanned for files to archive.
+     * This method may also update {@link #currentFilesToArchive} if it detects
+     * that we are visiting the content of a new module or a new target Java release.
+     *
+     * @param directory the directory which will be traversed
+     * @param attributes the directory's basic attributes
+     */
+    @Override
+    @SuppressWarnings("checkstyle:MissingSwitchDefault")
+    public FileVisitResult preVisitDirectory(final Path directory, final BasicFileAttributes attributes)
+            throws IOException {
+        DirectoryRole role;
+        if (directoryRoles.isEmpty()) {
+            role = DirectoryRole.ROOT;
+        } else {
+            if (!directoryMatcher.matches(directory)) {
+                excludedDirectories.add(directory); // Cannot be null if excluded directories may exist.
+                return FileVisitResult.SKIP_SUBTREE;
+            }
+            checkForManifest = false;
+            role = directoryRoles.getLast();
+            switch (role) {
+                case ROOT:
+                    /*
+                     * Visiting any subdirectory of `target/classes` (or other directory to archive).
+                     * We need to handle `META-INF` and modules in a special way, and archive the rest.
+                     */
+                    if (directory.endsWith(MetadataFiles.META_INF)) {
+                        role = DirectoryRole.META_INF;
+                        checkForManifest = true;
+                    } else if (Files.isRegularFile(directory.resolve(MODULE_DESCRIPTOR_FILE_NAME))) {
+                        role = DirectoryRole.NAMED_MODULE;
+                        preVisitVersionDirectory(directory);
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case META_INF:
+                    /*
+                     * Visiting a subdirectory of `META-INF` or `<module>/META-INF`. We will need to handle
+                     * `MANIFEST.MF`, `versions` and `versions-modular` in a special way, and archive the rest.
+                     */
+                    if (detectMultiReleaseJar && directory.endsWith(VERSIONS)) {
+                        role = DirectoryRole.VERSIONS;
+                    } else if (directory.endsWith(VERSIONS_MODULAR)) {
+                        if (!detectMultiReleaseJar) {
+                            // Used asked for no multi-release JAR.
+                            return FileVisitResult.SKIP_SUBTREE;
+                        }
+                        role = DirectoryRole.VERSIONS_MODULAR;
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case VERSIONS:
+                    /*
+                     * Visiting a `META-INF/versions/<n>/` directory for a specific target Java release.
+                     * Can also be a `<module>/META-INF/versions/<n>/` directory, even if the latter is not
+                     * the layout generated by Maven Compiler Plugin.
+                     */
+                    if (preVisitVersionDirectory(directory, true)) {
+                        // An error occurred while parsing the version number.
+                        return FileVisitResult.SKIP_SUBTREE;
+                    }
+                    role = DirectoryRole.RESOURCES;
+                    break;
+
+                case VERSIONS_MODULAR:
+                    /*
+                     * Visiting a `META-INF/versions-modular/<n>/` directory for a specific target Java release.
+                     * That directory contains all modules for the version.
+                     */
+                    resetToPackageHierarchy(); // No module in particular yet.
+                    if (preVisitVersionDirectory(directory, false)) {
+                        // An error occurred while parsing the version number.
+                        return FileVisitResult.SKIP_SUBTREE;
+                    }
+                    role = DirectoryRole.MODULES;
+                    break;
+
+                case MODULES:
+                    /*
+                     * Visiting a `META-INF/versions-modular/<n>/<module>` directory.
+                     */
+                    preVisitVersionDirectory(directory);
+                    role = DirectoryRole.NAMED_MODULE;
+                    break;
+
+                case NAMED_MODULE:
+                    /*
+                     * Visiting a `<module>` or `META-INF/versions-modular/<n>/<module>` subdirectory.
+                     * A module could have its own `META-INF` subdirectory, so we need to check again.
+                     */
+                    if (directory.endsWith(MetadataFiles.META_INF)) {
+                        role = DirectoryRole.META_INF;
+                        checkForManifest = true;
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+            }
+        }
+        /*
+         * Do not move this condition inside the `switch` block because `role` may have been modified.
+         * The `role` value is now the role of `directory`, not the role of parent directory.
+         */
+        if (role == DirectoryRole.RESOURCES) {
+            currentFilesToArchive.add(directory, attributes, true);
+            if (excludedFiles == null) {
+                /*
+                 * Since we are skipping the whole directory, `postVisitDirectory(…)` will not be invoked.
+                 * We must reset `currentFilesToArchive` and `currentTargetVersion` by an explicit call.
+                 * This is important mostly after we added a whole `META-INF/versions/<n>` directory.
+                 * Otherwise, since directory iteration order is unspecified, base files visited afterwards
+                 * would be added to this version's file set instead of the base release.
+                 */
+                resetToParentDirectoryState();
+                return FileVisitResult.SKIP_SUBTREE;
+            }
+        }
+        directoryRoles.addLast(role);
+        return FileVisitResult.CONTINUE;
+    }
+
+    /**
+     * Updates the {@code FileCollector} state after we finished scanning the contents of a directory.
+     * The fields to update depend on which directory has been visited (module, version, etc.).
+     *
+     * @param directory the directory which has been traversed
+     * @param error the error that occurred while traversing the directory, or {@code null} if none
+     */
+    @Override
+    public FileVisitResult postVisitDirectory(final Path directory, final IOException error) throws IOException {
+        if (error != null) {
+            throw error;
+        }
+        switch (directoryRoles.removeLast()) {
+            case ROOT:
+                break;
+
+            case NAMED_MODULE:
+                // Exited the directory of a single module.
+                resetToPackageHierarchy();
+                break;
+
+            default:
+                resetToParentDirectoryState();
+                break;
+        }
+        return FileVisitResult.CONTINUE;
+    }
+
+    /**
+     * Updates {@code FileCollector} to a state suitable for the parent of the directory that we finished to scan.
+     * Contrary to {@link #postVisitDirectory(Path, IOException)}, this method expects the last element of
+     * {@link #directoryRoles} to describe the parent directory, not the directory that we finished to visit.
+     */
+    @SuppressWarnings("checkstyle:MissingSwitchDefault")
+    private void resetToParentDirectoryState() {
+        switch (directoryRoles.getLast()) {
+            case VERSIONS:
+            case VERSIONS_MODULAR:
+                // Exited the directory for one target Java release.
+                currentFilesToArchive = currentModule.baseRelease();
+                currentTargetVersion = null;
+                break;
+
+            case META_INF:
+                checkForManifest = true;
+                break;
+        }
+    }
+
+    /**
+     * Archives a single file if accepted by the matcher.
+     *
+     * @param file the file
+     * @param attributes the file's basic attributes
+     */
+    @Override
+    public FileVisitResult visitFile(final Path file, final BasicFileAttributes attributes) {
+        if (fileMatcher.matches(file)) {
+            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.add(file, attributes, false);
+            }
+        } else {
+            excludedFiles.add(file); // Cannot be null if excluded files may exist.
+        }
+        return FileVisitResult.CONTINUE;
+    }
+
+    /**
+     * 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}
+     */
+    public void prune(boolean skipIfEmpty) {
+        boolean isModuleHierarchy = !moduleHierarchy.isEmpty();
+        moduleHierarchy.values().forEach((archive) -> archive.prune(skipIfEmpty));
+        moduleHierarchy.values().removeIf(Archive::isEmpty);
+        packageHierarchy.prune(isModuleHierarchy || skipIfEmpty);
+    }
+
+    /**
+     * Moves, copies, or ignores orphan files.
+     * An orphan file is a file which is not in any module when module hierarchy is used.
+     * For example, some Maven plugins may create files such as {@code META-INF/LICENSE},
+     * {@code META-INF/NOTICE} or {@code META-INF/DEPENDENCIES}. These files are not in
+     * the correct directory (they should be in a {@code "<module>/META-INF"} directory)
+     * because the plugin may not be aware of module hierarchy.
+     *
+     * <p>A possible strategy could be to copy the {@code LICENSE} and {@code NOTICE} files
+     * in each module, and ignore the {@code DEPENDENCIES} file because its content is not
+     * correct for a module. For now, we just log a warning and ignore.</p>
+     *
+     * <h4>Prerequisites</h4>

Review Comment:
   why not just call prune here then?



##########
src/main/java/org/apache/maven/plugins/jar/PomDerivation.java:
##########
@@ -0,0 +1,529 @@
+/*
+ * 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.jar;
+
+import javax.xml.stream.XMLStreamException;
+
+import java.io.BufferedInputStream;
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.UncheckedIOException;
+import java.lang.module.ModuleDescriptor;
+import java.lang.module.ModuleFinder;
+import java.lang.module.ModuleReference;
+import java.net.URI;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.DependencyCoordinates;
+import org.apache.maven.api.JavaPathType;
+import org.apache.maven.api.Session;
+import org.apache.maven.api.Type;
+import org.apache.maven.api.model.Dependency;
+import org.apache.maven.api.model.Model;
+import org.apache.maven.api.model.Parent;
+import org.apache.maven.api.plugin.MojoException;
+import org.apache.maven.api.services.DependencyCoordinatesFactory;
+import org.apache.maven.api.services.DependencyCoordinatesFactoryRequest;
+import org.apache.maven.api.services.DependencyResolver;
+import org.apache.maven.api.services.DependencyResolverRequest;
+import org.apache.maven.api.services.DependencyResolverResult;
+import org.apache.maven.api.services.ModelBuilderException;
+import org.apache.maven.model.v4.MavenStaxWriter;
+
+/**
+ * A mapper from Maven model dependencies to Java module names.
+ * A single instance of this class is created for a Maven project,
+ * then shared by all {@link ForModule} instances (one per module to archive).
+ */
+final class PomDerivation {
+    /**
+     * Whether to expand the list of transitive dependencies in the generated <abbr>POM</abbr>.
+     */
+    private static final boolean EXPAND_TRANSITIVE = false;
+
+    /**
+     * Copy of {@link AbstractJarMojo#session}.
+     */
+    private final Session session;
+
+    /**
+     * The project model, which includes dependencies of all modules.
+     */
+    private final Model projectModel;
+
+    /**
+     * The factory to use for creating temporary {@link DependencyCoordinates} instances.
+     */
+    private final DependencyCoordinatesFactory coordinateFactory;
+
+    /**
+     * Provide module descriptors from module names.
+     * May be {@code null} if no {@code module-info} was found.
+     */
+    private final ModuleFinder moduleFinder;
+
+    /**
+     * Module references from paths to the <abbr>JAR</abbr> file or root directory.
+     */
+    private final Map<URI, ModuleReference> fromURI;
+
+    /**
+     * Module names associated with Maven dependencies.
+     * This map contains {@link DependencyCoordinates#getId()} as keys and module references as values.
+     * This is used to detect which dependencies are really used according to {@code module-info.class}.
+     *
+     * @todo The keys should be instances of {@link DependencyCoordinates}. Unfortunately, as of Maven 4.0.0-rc-5
+     *       that interface does not define the {@code equals} and {@code hashCode} contracts.
+     */
+    private final Map<String, ModuleReference> fromDependency;
+
+    /**
+     * Modules that are built by the project. Keys are module names.
+     */
+    private final Map<String, Dependency> builtModules;
+
+    /**
+     * Creates a new mapper from Maven dependency to module name.
+     *
+     * @param mojo the enclosing <abbr>MOJO</abbr>
+     * @param moduleRoots paths to root directories of each module to archive in a module hierarchy
+     * @throws IOException if an I/O error occurred while fetching dependencies
+     * @throws MavenException if an error occurred while fetching dependencies for a reason other than I/O.
+     */
+    PomDerivation(final AbstractJarMojo mojo, final List<Path> moduleRoots) throws IOException {
+        this.session = mojo.session;
+        projectModel = mojo.project.getModel();
+        coordinateFactory = session.getService(DependencyCoordinatesFactory.class);
+        DependencyResolver resolver = session.getService(DependencyResolver.class);
+        DependencyResolverResult result = resolver.resolve(DependencyResolverRequest.builder()
+                .session(session)
+                .project(mojo.project)
+                .requestType(DependencyResolverRequest.RequestType.RESOLVE)
+                .pathScope(mojo.getDependencyScope())
+                .pathTypeFilter(Set.of(JavaPathType.MODULES, JavaPathType.CLASSES))
+                .build());
+
+        rethrow(result);
+        final Map<org.apache.maven.api.Dependency, Path> dependencies = result.getDependencies();
+        final Path[] allModulePaths = toRealPaths(moduleRoots, dependencies.values());
+        fromURI = new HashMap<>(allModulePaths.length); // TODO: use newHashMap with JDK19.
+        moduleFinder = ModuleFinder.of(allModulePaths);
+        if (moduleFinder != null) {
+            for (ModuleReference reference : moduleFinder.findAll()) {
+                reference.location().ifPresent((location) -> fromURI.put(location, reference));
+            }
+        }
+        fromDependency = new HashMap<>(dependencies.size()); // TODO: use newHashMap with JDK19.
+        for (Map.Entry<org.apache.maven.api.Dependency, Path> entry : dependencies.entrySet()) {
+            Path modulePath = entry.getValue().toRealPath();
+            ModuleReference reference = fromURI.get(modulePath.toUri());
+            if (reference != null) {
+                DependencyCoordinates coordinates = entry.getKey().toCoordinates();
+                String id = coordinates.getId();
+                ModuleReference old = fromDependency.putIfAbsent(id, reference);
+                if (old == null) {
+                    coordinates = withoutVersion(coordinates);
+                    id = coordinates.getId();
+                    old = fromDependency.putIfAbsent(id, reference);
+                }
+                if (old != null && !old.equals(reference)) {
+                    mojo.log.warn("The \"" + id + "\" dependency is declared twice with different module names: \""
+                            + old.descriptor().name() + "\" and \""
+                            + reference.descriptor().name() + "\".");
+                }
+            }
+        }
+        builtModules = new HashMap<>(moduleRoots.size()); // TODO: use newHashMap with JDK19.
+        for (Path root : moduleRoots) {
+            root = root.toRealPath();

Review Comment:
   try to avoid reusing the loop variable



##########
src/main/java/org/apache/maven/plugins/jar/TimestampCheck.java:
##########
@@ -0,0 +1,261 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.nio.file.attribute.FileTime;
+import java.util.Collection;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+
+import org.apache.maven.api.plugin.Log;
+
+/**
+ * Checks file timestamps in order to determine if anything changed compared to an existing <abbr>JAR</abbr> file.
+ * This class may scan directories, but only if they have not already been visited by {@link FileCollector}.
+ * The latter can only occur if {@link FileCollector} has no {@code PathMatcher}.
+ * Therefore, this class uses no {@code PathMatcher}.
+ *
+ * <h2>Ignore files</h2>
+ * The {@code META-INF/MANIFEST.MF} file and the {@code META-INF/maven/} directory are ignored.
+ * See {@link #isIgnored(Path)} for the rational.
+ */
+final class TimestampCheck extends SimpleFileVisitor<Path> {
+    /**
+     * The base directory of archived files.
+     */
+    private final Path classesDir;
+
+    /**
+     * Path to the existing <abbr>JAR</abbr> file.
+     */
+    private final Path jarFile;
+
+    /**
+     * The last modified time of the <abbr>JAR</abbr> file.
+     */
+    private final FileTime jarFileTime;
+
+    /**
+     * Where to send non-fatal error messages.
+     */
+    private final Log logger;
+
+    /**
+     * Entries of the <abbr>JAR</abbr> file. Note that getting elements from this enumeration can be costly.
+     * Therefore, we only fetch elements when needed.
+     */
+    private Enumeration<? extends ZipEntry> entries;
+
+    /**
+     * Files found in the <abbr>JAR</abbr> file but not yet traversed by the file visitor.
+     * Files are added lazily when needed, and removed as soon as they have been traversed.
+     * Path are absolute (resolved with {@link #classesDir}).
+     * For each entry, the associated value is whether the path is a directory.
+     */
+    private final Map<Path, Boolean> filesInJAR;
+
+    /**
+     * Some of the files in the build directory. This list contains only the files for which we have already
+     * verified the timestamp. We store them in a separate list for avoiding to check the timestamp twice.
+     * We need this list because we still need to verify if the files are in the {@link #jarFile}.
+     * For each entry, the associated value is whether the path is a directory.
+     */
+    private final Map<Path, Boolean> filesInBuild;
+
+    /**
+     * Whether at least one file is more recent than the <abbr>JAR</abbr> file.
+     * The scan of files will stop quickly after this flag become {@code true}.
+     */
+    private boolean hasUpdates;
+
+    /**
+     * Creates a new visitor for checking the validity of a <abbr>JAR</abbr> file.
+     *
+     * @param jarFile the existing <abbr>JAR</abbr> file
+     * @param jarFileTime the last modified time of the <abbr>JAR</abbr> file
+     * @param classesDir base directory of archived files
+     * @param logger where to send a warning if an error occurred while checking an existing <abbr>JAR</abbr> file
+     * @throws IOException if an error occurred while fetching the <abbr>JAR</abbr> file modification time
+     */
+    TimestampCheck(final Path jarFile, final Path classesDir, final Log logger) throws IOException {
+        this.classesDir = classesDir;
+        this.jarFile = jarFile;
+        this.logger = logger;
+        jarFileTime = Files.getLastModifiedTime(jarFile);
+        filesInJAR = new HashMap<>();
+        filesInBuild = new HashMap<>();
+    }
+
+    /**
+     * Returns {@code true} if the given file is more recent that the <abbr>JAR</abbr> file.
+     *
+     * @param file the file to check
+     * @param attributes the file's basic attributes
+     * @param isDirectory whether the file is a directory
+     * @return whether the modification time is more recent than the <abbr>JAR</abbr> file
+     */
+    boolean isUpdated(final Path file, final BasicFileAttributes attributes, final boolean isDirectory) {
+        if (jarFileTime.compareTo(attributes.lastModifiedTime()) < 0) {
+            return true;
+        }
+        filesInBuild.put(file, isDirectory);
+        return false;
+    }
+
+    /**
+     * Checks if the <abbr>JAR</abbr> file contains all the given files, no extra entry, and no outdated entry.

Review Comment:
   no extra entries



##########
src/main/java/org/apache/maven/plugins/jar/AbstractJarMojo.java:
##########
@@ -72,23 +72,20 @@ public abstract class AbstractJarMojo implements org.apache.maven.api.plugin.Moj
     protected String[] excludes;
 
     /**
-     * Directory containing the generated JAR.
+     * Directory containing the generated <abbr>JAR</abbr> files.
      */
     @Parameter(defaultValue = "${project.build.directory}", required = true)
     protected Path outputDirectory;
 
     /**
-     * Name of the generated JAR.
+     * Name of the generated <abbr>JAR</abbr> file.

Review Comment:
   I'm skeptical abbr is appropriate here.



##########
src/main/java/org/apache/maven/plugins/jar/PomDerivation.java:
##########
@@ -0,0 +1,529 @@
+/*
+ * 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.jar;
+
+import javax.xml.stream.XMLStreamException;
+
+import java.io.BufferedInputStream;
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.UncheckedIOException;
+import java.lang.module.ModuleDescriptor;
+import java.lang.module.ModuleFinder;
+import java.lang.module.ModuleReference;
+import java.net.URI;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.DependencyCoordinates;
+import org.apache.maven.api.JavaPathType;
+import org.apache.maven.api.Session;
+import org.apache.maven.api.Type;
+import org.apache.maven.api.model.Dependency;
+import org.apache.maven.api.model.Model;
+import org.apache.maven.api.model.Parent;
+import org.apache.maven.api.plugin.MojoException;
+import org.apache.maven.api.services.DependencyCoordinatesFactory;
+import org.apache.maven.api.services.DependencyCoordinatesFactoryRequest;
+import org.apache.maven.api.services.DependencyResolver;
+import org.apache.maven.api.services.DependencyResolverRequest;
+import org.apache.maven.api.services.DependencyResolverResult;
+import org.apache.maven.api.services.ModelBuilderException;
+import org.apache.maven.model.v4.MavenStaxWriter;
+
+/**
+ * A mapper from Maven model dependencies to Java module names.
+ * A single instance of this class is created for a Maven project,
+ * then shared by all {@link ForModule} instances (one per module to archive).
+ */
+final class PomDerivation {
+    /**
+     * Whether to expand the list of transitive dependencies in the generated <abbr>POM</abbr>.
+     */
+    private static final boolean EXPAND_TRANSITIVE = false;
+
+    /**
+     * Copy of {@link AbstractJarMojo#session}.
+     */
+    private final Session session;
+
+    /**
+     * The project model, which includes dependencies of all modules.
+     */
+    private final Model projectModel;
+
+    /**
+     * The factory to use for creating temporary {@link DependencyCoordinates} instances.
+     */
+    private final DependencyCoordinatesFactory coordinateFactory;
+
+    /**
+     * Provide module descriptors from module names.
+     * May be {@code null} if no {@code module-info} was found.
+     */
+    private final ModuleFinder moduleFinder;
+
+    /**
+     * Module references from paths to the <abbr>JAR</abbr> file or root directory.
+     */
+    private final Map<URI, ModuleReference> fromURI;
+
+    /**
+     * Module names associated with Maven dependencies.
+     * This map contains {@link DependencyCoordinates#getId()} as keys and module references as values.
+     * This is used to detect which dependencies are really used according to {@code module-info.class}.
+     *
+     * @todo The keys should be instances of {@link DependencyCoordinates}. Unfortunately, as of Maven 4.0.0-rc-5
+     *       that interface does not define the {@code equals} and {@code hashCode} contracts.
+     */
+    private final Map<String, ModuleReference> fromDependency;
+
+    /**
+     * Modules that are built by the project. Keys are module names.
+     */
+    private final Map<String, Dependency> builtModules;
+
+    /**
+     * Creates a new mapper from Maven dependency to module name.
+     *
+     * @param mojo the enclosing <abbr>MOJO</abbr>
+     * @param moduleRoots paths to root directories of each module to archive in a module hierarchy
+     * @throws IOException if an I/O error occurred while fetching dependencies
+     * @throws MavenException if an error occurred while fetching dependencies for a reason other than I/O.
+     */
+    PomDerivation(final AbstractJarMojo mojo, final List<Path> moduleRoots) throws IOException {
+        this.session = mojo.session;
+        projectModel = mojo.project.getModel();
+        coordinateFactory = session.getService(DependencyCoordinatesFactory.class);
+        DependencyResolver resolver = session.getService(DependencyResolver.class);
+        DependencyResolverResult result = resolver.resolve(DependencyResolverRequest.builder()
+                .session(session)
+                .project(mojo.project)
+                .requestType(DependencyResolverRequest.RequestType.RESOLVE)
+                .pathScope(mojo.getDependencyScope())
+                .pathTypeFilter(Set.of(JavaPathType.MODULES, JavaPathType.CLASSES))
+                .build());
+
+        rethrow(result);
+        final Map<org.apache.maven.api.Dependency, Path> dependencies = result.getDependencies();
+        final Path[] allModulePaths = toRealPaths(moduleRoots, dependencies.values());
+        fromURI = new HashMap<>(allModulePaths.length); // TODO: use newHashMap with JDK19.
+        moduleFinder = ModuleFinder.of(allModulePaths);
+        if (moduleFinder != null) {
+            for (ModuleReference reference : moduleFinder.findAll()) {
+                reference.location().ifPresent((location) -> fromURI.put(location, reference));
+            }
+        }
+        fromDependency = new HashMap<>(dependencies.size()); // TODO: use newHashMap with JDK19.
+        for (Map.Entry<org.apache.maven.api.Dependency, Path> entry : dependencies.entrySet()) {
+            Path modulePath = entry.getValue().toRealPath();
+            ModuleReference reference = fromURI.get(modulePath.toUri());
+            if (reference != null) {
+                DependencyCoordinates coordinates = entry.getKey().toCoordinates();
+                String id = coordinates.getId();
+                ModuleReference old = fromDependency.putIfAbsent(id, reference);
+                if (old == null) {
+                    coordinates = withoutVersion(coordinates);
+                    id = coordinates.getId();
+                    old = fromDependency.putIfAbsent(id, reference);
+                }
+                if (old != null && !old.equals(reference)) {
+                    mojo.log.warn("The \"" + id + "\" dependency is declared twice with different module names: \""
+                            + old.descriptor().name() + "\" and \""
+                            + reference.descriptor().name() + "\".");
+                }
+            }
+        }
+        builtModules = new HashMap<>(moduleRoots.size()); // TODO: use newHashMap with JDK19.
+        for (Path root : moduleRoots) {
+            root = root.toRealPath();
+            ModuleReference reference = fromURI.get(root.toUri());
+            if (reference != null) { // Actually a null value would be a bug, but be tolerant.
+                String moduleName = reference.descriptor().name();
+                builtModules.put(
+                        moduleName,
+                        Dependency.newBuilder()
+                                .groupId(projectModel.getGroupId())
+                                .artifactId(moduleName)
+                                .version(projectModel.getVersion())
+                                .type(Type.MODULAR_JAR)
+                                .build());
+            }
+        }
+    }
+
+    /**
+     * Rebuilds the given dependency coordinates without version.
+     *
+     * Note: I'm not sure if it is necessary. This is done in case version numbers are not resolved

Review Comment:
   can we resolve this one way or the other now?



##########
src/main/java/org/apache/maven/plugins/jar/TimestampCheck.java:
##########
@@ -0,0 +1,237 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.nio.file.attribute.FileTime;
+import java.util.Collection;
+import java.util.Enumeration;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+
+import org.apache.maven.api.plugin.Log;
+
+/**
+ * Checks file timestamps in order to determine if anything changed compared to an existing <abbr>JAR</abbr> file.
+ * This class may scan directories, but only if they have not already been visited by {@link FileCollector}.
+ * Note that the latter can occur only if {@link FileCollector} has no {@code PathMatcher}.
+ * Therefore, this class uses no {@code PathMatcher} neither.
+ *
+ * <h2>Ignore files</h2>
+ * The {@code META-INF/MANIFEST.MF} file and the {@code META-INF/maven/} directory are ignored.
+ * See {@link #isIgnored(Path)} for the rational.
+ */
+final class TimestampCheck extends SimpleFileVisitor<Path> {
+    /**
+     * The base directory of archived files.
+     */
+    private final Path classesDir;
+
+    /**
+     * Path to the existing <abbr>JAR</abbr> file.
+     */
+    private final Path jarFile;
+
+    /**
+     * The last modified time of the <abbr>JAR</abbr> file.
+     */
+    private final FileTime jarFileTime;
+
+    /**
+     * Where to send non-fatal error messages.
+     */
+    private final Log logger;
+
+    /**
+     * Entries of the <abbr>JAR</abbr> file. Note that getting elements from this enumeration can be costly.
+     * Therefore, we do not fetch all elements in advance but only when needed.
+     */
+    private Enumeration<? extends ZipEntry> entries;
+
+    /**
+     * Files found in the <abbr>JAR</abbr> file but not yet traversed by the file visitor.
+     * Files are added lazily only when needed, and removed as soon as they have been traversed.
+     * Path are absolute (resolved with {@link #classesDir}).
+     */
+    private final Set<Path> filesInJAR;
+
+    /**
+     * Some of the files in the build directory. This list contains only the files for which we have already
+     * verified the timestamp. We store them in a separated list for avoiding to check the timestamp twice.
+     * We need this list because we still need to verify if the files are in the {@link #jarFile}.
+     */
+    private final Set<Path> filesInBuild;
+
+    /**
+     * Whether at least one file is more recent than the <abbr>JAR</abbr> file.
+     * The scan of files will stop quickly after this flag become {@code true}.

Review Comment:
   quickly --> soon



##########
src/main/java/org/apache/maven/plugins/jar/Providers.java:
##########
@@ -22,25 +22,13 @@
 import org.apache.maven.api.di.Named;
 import org.apache.maven.api.di.Provides;
 import org.apache.maven.api.services.ProjectManager;
-import org.codehaus.plexus.archiver.Archiver;
-import org.codehaus.plexus.archiver.jar.JarArchiver;
-import org.codehaus.plexus.archiver.jar.JarToolModularJarArchiver;
 
+/**
+ * For providing instances to fields annotated with {@code @Inject} if the MOJO.

Review Comment:
   @gnodet 



##########
src/main/java/org/apache/maven/plugins/jar/ToolExecutor.java:
##########
@@ -0,0 +1,551 @@
+/*
+ * 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.jar;
+
+import javax.lang.model.SourceVersion;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+import java.util.spi.ToolProvider;
+
+import org.apache.maven.api.Project;
+import org.apache.maven.api.Type;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.MojoException;
+import org.apache.maven.shared.archiver.MavenArchiveConfiguration;
+
+/**
+ * Writer of <abbr>JAR</abbr> files using the information collected by {@link FileCollector}.
+ * This class uses the {@code "jar"} tool provided with the <abbr>JDK</abbr>.
+ */
+final class ToolExecutor {
+    /**
+     * First JDK feature version whose {@code jar} tool can run {@code --validate} on archives
+     * that contain records. Earlier {@code jar} tools failed with "This feature requires ASM8"
+     * (JDK-8282446, fixed by JDK-8282508 in JDK 19 by not backported to a 17u or 18u update).
+     *
+     * @see <a href="https://bugs.openjdk.org/browse/JDK-8282446">JDK-8282446</a>
+     * @see <a href="https://bugs.openjdk.org/browse/JDK-8282508">JDK-8282508</a>
+     */
+    private static final int JDK_FIXING_JAR_VALIDATE = 19;
+
+    /**
+     * First JDK feature version whose {@code jar} tool support the {@code --date} option.
+     */
+    private static final int JDK_SUPPORT_DATE = 19;
+
+    /**
+     * The {@value} attribute. Its value is automatically generated by {@link Manifest},
+     * but may need to be replaced by another value if JDK-independent value is desired
+     * for strictly reproducible builds.
+     */
+    private static final String CREATED_BY = "Created-By";
+
+    /**
+     * The Maven project for which to create an archive.
+     */
+    final Project project;
+
+    /**
+     * {@code "jar"} or {@link "test-jar"}.
+     */
+    private final String artifactType;
+
+    /**
+     * The output directory where to write the <abbr>JAR</abbr> file.
+     * This is usually {@code ${baseDir}/target/}.
+     */
+    private final Path outputDirectory;
+
+    /**
+     * The <abbr>JAR</abbr> file name when package hierarchy is used.
+     * This is usually a file placed in the {@link ToolExecutor#outputDirectory} directory.
+     */
+    private final String finalName;
+
+    /**
+     * The classifier (e.g. "test"), or {@code null} if none.
+     */
+    private final String classifier;
+
+    /**
+     * Whether to validate the <abbr>JAR</abbr> file after its creation.
+     * If {@code null}, a value will be determined automatically based on heuristic rules.
+     */
+    private final Boolean validate;
+
+    /**
+     * The tool to use for creating the <abbr>JAR</abbr> files.
+     */
+    private final ToolProvider tool;
+
+    /**
+     * Where to send messages emitted by the "jar" tool.
+     */
+    private final PrintWriter messageWriter;
+
+    /**
+     * Where to send error messages emitted by the "jar" tool.
+     */
+    private final PrintWriter errorWriter;
+
+    /**
+     * Where the messages sent to {@link #messageWriter} are stored.
+     */
+    private final StringBuffer messages;
+
+    /**
+     * Where the messages sent to {@link #errorWriter} are stored.
+     */
+    private final StringBuffer errors;
+
+    /**
+     * A buffer for the arguments given to the "jar" tool, reused for each module.
+     * Each element of the list must be instances of either {@link String} or {@link Path}.
+     */
+    private final List<Object> arguments;
+
+    /**
+     * The paths to the created archive files.
+     * Map keys are module names or {@code null} if the project does not use module hierarchy.
+     * Values are (<var>type</var>, <var>path</var>) pairs associated with each module where
+     * <var>type</var> is {@code "pom"}, {@code "jar"} or {@code "test-jar"} and <var>path</var>
+     * is the path to the <abbr>POM</abbr> or <abbr>JAR</abbr> file.
+     */
+    private final Map<String, Map<String, Path>> result;
+
+    /**
+     * Mapper from Maven dependencies to Java modules, or {@code null} if the project does not use module hierarchy.
+     * This mapper is created only once for a Maven project and reused for each Java module to archive.
+     *
+     * <p>This field is not used directly by {@code ToolExecutor}. It is defined in this class for transferring
+     * this information from {@link AbstractJarMojo} to {@link PomDerivation.ForModule}.
+     * This is an internal mechanism that should not be public or protected.</p>
+     */
+    PomDerivation pomDerivation;
+
+    /**
+     * Manifest to merge with the manifest found in the files to archive.
+     * This is a manifest built from the {@code <archive>} plugin configuration.
+     * Can be {@code null} if there is noting to add to the existing manifests.
+     */
+    private final Manifest manifestFromPlugin;
+
+    /**
+     * The file from which {@link #manifestFromPlugin} has been read, or {@code null} if none.
+     * If non-null, reading that file must produce the same manifest as {@link #manifestFromPlugin}.
+     * It implies that this field must be {@code null} if {@link #manifestFromPlugin} is the result
+     * of merging elements specified in {@code <archive>} with a file specified in the plugin configuration.
+     */
+    private final Path manifestFile;
+
+    /**
+     * The archive configuration to use.
+     */
+    private final MavenArchiveConfiguration archiveConfiguration;
+
+    /**
+     * The timestamp in ISO-8601 extended offset date-time, or {@code null} if none.
+     * If user provided a value in seconds, it must have been converted to ISO-8601.
+     * This is used for reproducible builds.
+     */
+    private final String outputTimestamp;
+
+    /**
+     * Whether to force to build new <abbr>JAR</abbr> files even if none of the contents appear to have changed.
+     */
+    private final boolean forceCreation;
+
+    /**
+     * Where to send informative or error messages.
+     */
+    private final Log logger;
+
+    /**
+     * Creates a new writer.
+     *
+     * @param mojo the <abbr>MOJO</abbr> from which to get the configuration
+     * @param manifest manifest built from plugin configuration, or {@code null} if none
+     * @param archive the archive configuration
+     * @throws IOException if an error occurred while reading the manifest file
+     */
+    ToolExecutor(AbstractJarMojo mojo, Manifest manifest, MavenArchiveConfiguration archive) throws IOException {
+        project = mojo.project;
+        artifactType = mojo.getType();
+        outputDirectory = mojo.getOutputDirectory();
+        classifier = AbstractJarMojo.nullIfAbsent(mojo.getClassifier());
+        finalName =
+                (mojo.finalName != null) ? mojo.finalName : project.getBuild().getFinalName();
+        forceCreation = mojo.forceCreation;
+        outputTimestamp = mojo.getOutputTimestamp();
+        validate = mojo.getValidate();
+        logger = mojo.log;
+        tool = mojo.getJarTool();
+
+        var buffer = new StringWriter();
+        messages = buffer.getBuffer();
+        messageWriter = new PrintWriter(buffer);
+
+        buffer = new StringWriter();
+        errors = buffer.getBuffer();
+        errorWriter = new PrintWriter(buffer);
+
+        arguments = new ArrayList<>();
+        result = new LinkedHashMap<>();
+        archiveConfiguration = archive;
+
+        Path file = archive.getManifestFile();
+        if (file != null) {
+            try (InputStream in = Files.newInputStream(file)) {
+                // No need to wrap in `BufferedInputStream`.
+                if (manifest != null) {
+                    manifest.read(in);
+                    file = null; // Because the manifest is the result of a merge.
+                } else {
+                    manifest = new Manifest(in);
+                }
+            }
+        }
+        if (manifest != null) {
+            final Attributes mainAttributes = manifest.getMainAttributes();
+            if (mojo.detectMultiReleaseJar) {
+                mainAttributes.remove(Attributes.Name.MULTI_RELEASE);
+            }
+            if (isReproducible()) {
+                // If a "Created-By" attribute was generated by Maven Archiver, it is assumed JDK-independent.
+                // Otherwise, substitute by another value which does not depend on the JDK.
+                if (mainAttributes.getValue(CREATED_BY) == null) {
+                    mainAttributes.putValue(CREATED_BY, createdBy());
+                }
+            } else {
+                // If reproducible build was not requested, let the tool declares itself.
+                // This is a workaround until we port Maven archiver to this JAR plugin.
+                mainAttributes.remove(CREATED_BY);
+            }
+        }
+        manifestFromPlugin = manifest;
+        manifestFile = file;
+    }
+
+    /**
+     * Whether reproducible build was requested.
+     * In current version, the output time stamp is used as a sentinel value.
+     */
+    public boolean isReproducible() {
+        return outputTimestamp != null;
+    }
+
+    /**
+     * Returns the default {@value #CREATED_BY} value to use when strictly reproducible builds is requested.
+     * This value is ignored if the Maven Archiver or if user's configuration provided themselves a value.
+     *
+     * @return a JDK-independent {@value #CREATED_BY} value
+     */
+    private static String createdBy() {
+        String value = "Maven JAR Plugin";
+        String version = ToolExecutor.class.getPackage().getImplementationVersion();
+        if (version != null) {
+            value = value + ' ' + version;
+        }
+        return value;
+    }
+
+    /**
+     * Creates an initially empty archive for <abbr>JAR</abbr> file to generate.
+     * This method does not create the <abbr>JAR</abbr> file immediately,
+     * but collect information for creating the file later.
+     *
+     * @param  moduleName the module name if using module hierarchy, or {@code null} if using package hierarchy
+     * @param  version the target Java release, or {@code null} for the base version
+     * @param  directory the directory of the classes targeting the base Java release
+     */
+    Archive newArchive(final String moduleName, final Runtime.Version version, final Path directory) {
+        var sb = new StringBuilder(60);
+        if (moduleName != null) {
+            sb.append(moduleName).append('-').append(project.getVersion());
+        } else {
+            sb.append(finalName);
+        }
+        if (classifier != null) {
+            sb.append('-').append(classifier);
+        }
+        String filename = sb.append(".jar").toString();
+        return new Archive(outputDirectory.resolve(filename), moduleName, version, directory, forceCreation, logger);
+    }
+
+    /**
+     * Writes all <abbr>JAR</abbr> files, together with their derived <abbr>POM</abbr> files if applicable.
+     * The derived <abbr>POM</abbr> files are the intersections of the project <abbr>POM</abbr> with the
+     * content of {@code module-info.class} files.
+     *
+     * <h4>Prerequisites</h4>
+     * The {@link FileCollector#prune(boolean)} method should have been invoked once before to invoke this method.
+     *
+     * @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
+     * @throws MojoException if an error occurred during the execution of the "jar" tool
+     * @throws IOException if an error occurred while reading or writing a manifest file
+     */
+    @SuppressWarnings("ReturnOfCollectionOrArrayField")
+    public Map<String, Map<String, Path>> writeAllJARs(final FileCollector files) throws IOException {
+        Path ignored = files.handleOrphanFiles();
+        Path parentPOM = files.writeAllJARs(this);
+        if (ignored != null) {
+            logger.warn("Some files in \"" + relativize(outputDirectory, ignored)
+                    + "\" were ignored because they belong to no module.");
+        }
+        if (parentPOM != null) {
+            if (result.put(null, Map.of(Type.POM, parentPOM)) != null) {
+                throw new MojoException("Internal error."); // Should never happen.
+            }
+        }
+        return result;
+    }
+
+    /**
+     * Creates the <abbr>JAR</abbr> files for the specified set of files.
+     * If the operation fails, an error message may be available in the {@link #errors} buffer.
+     *
+     * @param files the result of scanning the build directory for listing the files or directories to archive
+     * @throws MojoException if an error occurred during the execution of the "jar" tool
+     * @throws IOException if an error occurred while reading or writing a manifest file
+     */
+    void writeSingleJAR(final FileCollector files, final Archive archive) throws IOException {
+        final Path relativePath = relativize(project.getRootDirectory(), archive.jarFile);
+        if (archive.isUpToDateJAR()) {
+            logger.info("Keep up-to-date JAR: \"" + relativePath + "\".");
+            archive.saveArtifactPaths(artifactType, result);
+            return;
+        }
+        logger.info("Building JAR: \"" + relativePath + "\".");
+        /*
+         * If `MANIFEST.MF` entries were specified by JAR plugin configuration,
+         * merge those entries with the content of `MANIFEST.MF` file found in
+         * the files to archive.
+         */
+        boolean writeTemporaryManifest = (manifestFromPlugin != null && manifestFile == null); // Check <archive>.
+        Manifest manifest = archive.mergeManifest(manifestFile, manifestFromPlugin);
+        if (manifest != manifestFromPlugin) {
+            writeTemporaryManifest |= (manifestFromPlugin != null); // Check if a merge of two manifests.
+        } else if (manifest != null) {
+            /*
+             * `setMainClass` below removes the Main-Class attribute, and `manifestFromPlugin` is
+             * shared across every module of a module hierarchy. Work on a per-module copy so that
+             * the (unspecified) directory iteration order does not decide which module keeps the
+             * main class: otherwise a non-owning module processed first consumes the attribute and
+             * the owning module never receives it.
+             */
+            manifest = new Manifest(manifest);
+        }
+        writeTemporaryManifest |= archive.setMainClass(manifest);
+        if (manifest != null) {
+            String name = manifest.getMainAttributes().getValue("Automatic-Module-Name");
+            if (name != null && !SourceVersion.isName(name)) {
+                throw new MojoException("Invalid automatic module name: \"" + name + "\".");
+            }
+        }
+        /*
+         * Creates temporary files for META-INF (if the existing file cannot be used directly)
+         * and for the Maven metadata (if requested). The temporary files are in the `target`
+         * directory and will be deleted, unless the build fails or is run in verbose mode.
+         */
+        try (MetadataFiles metadata = new MetadataFiles(project, outputDirectory)) {
+            if (writeTemporaryManifest) {
+                archive.setManifest(metadata.addManifest(manifest), true);
+            }
+            if (archive.moduleName != null) {
+                metadata.deriveModulePOM(this, archive, manifest);
+            }
+            if (archiveConfiguration.isAddMavenDescriptor()) {
+                archive.mavenFiles = metadata.addPOM(archiveConfiguration, isReproducible());
+            }
+            /*
+             * Prepare the arguments to send to the `jar` tool and log a message.
+             */
+            arguments.add("--create");
+            if (!archiveConfiguration.isCompress()) {
+                arguments.add("--no-compress");
+            }
+            if (outputTimestamp != null) {
+                if (Runtime.version().feature() >= JDK_SUPPORT_DATE) {

Review Comment:
   JDK_SUPPORT_DATE --> JDK_SUPPORT_VERSION
   
   support dates are something else entirely



##########
src/test/java/org/apache/maven/plugins/jar/ArchiveTest.java:
##########
@@ -0,0 +1,257 @@
+/*
+ * 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.jar;
+
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Unit tests for {@link Archive}, focused on the two behaviours that are otherwise only
+ * exercised by integration tests whose outcome depends on the (unspecified) filesystem
+ * directory-iteration order, and therefore pass on some platforms while failing on others.
+ */
+class ArchiveTest {
+
+    /**
+     * Creates an {@code Archive} suitable for a unit test. {@code forceCreation = true} skips the
+     * existing-JAR timestamp check, so the (here {@code null}) logger is never dereferenced.
+     */
+    private static Archive archive(String moduleName, Runtime.Version version, Path directory) {
+        return new Archive(directory.resolve("out.jar"), moduleName, version, directory, true, null);
+    }
+
+    /**
+     * Creates a manifest with the main class attribute set to the given value.
+     *
+     * @param value value of the main class attribute
+     * @return a new manifest with the given attribute value
+     */
+    private static Manifest manifestWithMainClass(String value) {
+        Manifest m = new Manifest();
+        Attributes attributes = m.getMainAttributes();
+        attributes.put(Attributes.Name.MANIFEST_VERSION, "1.0");
+        attributes.put(Attributes.Name.MAIN_CLASS, value);
+        return m;
+    }
+
+    /**
+     * Returns the value of the main class attribute.
+     *
+     * @param m the manifest from which to get the value
+     * @return the main class attribute value, or {@code null} if none
+     */
+    private static Object mainClassOf(Manifest m) {
+        return m.getMainAttributes().get(Attributes.Name.MAIN_CLASS);
+    }
+
+    /**
+     * Verifies that {@link Archive#setMainClass(Manifest)} takes ownership for a module-qualified
+     * {@code "module/Class"} main class.
+     *
+     * The {@code "foo.bar/"} prefix in this test (the module name) is a Maven extension.
+     * The standard <abbr>JAR</abbr> specification accepts only the {@code "foo.MainFile"} class name.
+     */
+    @Test
+    void owningModuleClaimsMainClassAndRemovesItFromManifest() {
+        Archive owner = archive("foo.bar", null, Path.of("."));
+        Manifest m = manifestWithMainClass("foo.bar/foo.MainFile");
+        // The owner keeps the main class (emitted via --main-class) ...
+        assertTrue(owner.setMainClass(m));
+        // ... and the raw `module/Class` value is removed from the written manifest.
+        assertNull(mainClassOf(m));
+    }
+
+    /**
+     * Verifies that {@link Archive#setMainClass(Manifest)} does <em>not</em> take ownership fo
+     * a module-qualified {@code "module/Class"} main class when the module name does not match.
+     * The {@code "foo.bar/"} prefix in this test (the module name) is a Maven extension.
+     * The standard <abbr>JAR</abbr> specification accepts only the {@code "foo.MainFile"} class name.
+     */
+    @Test
+    void nonOwningModuleRejectsMainClass() {
+        Archive nonOwner = archive("foo.bar.more", null, Path.of("."));
+        Manifest m = manifestWithMainClass("foo.bar/foo.MainFile");
+        assertFalse(nonOwner.setMainClass(m));
+        assertNull(mainClassOf(m));
+    }
+
+    /**
+     * Tests that which module keeps the main class does not depend on processing order.
+     * {@link ToolExecutor} gives each module a <em>copy</em> of the shared plugin manifest;
+     * this pins that the owning module (and only it) keeps the main class in either order,
+     * and that the shared manifest is never consumed.
+     */
+    @Test
+    void mainClassAssignmentIsIndependentOfModuleOrder() {
+        assertOwnership("foo.bar", "foo.bar.more", true); // owner processed first
+        assertOwnership("foo.bar.more", "foo.bar", false); // non-owner processed first
+    }
+
+    /**
+     * Helper method for {@link #mainClassAssignmentIsIndependentOfModuleOrder()}.
+     * Asserts that {@link Archive#setMainClass(Manifest)} returns {@code true}
+     * for the owner and {@code false} for the other module.
+     *
+     * <p>The {@code "foo.bar/"} prefix in this test (the module name) is a Maven extension.
+     * The standard <abbr>JAR</abbr> specification accepts only the {@code "foo.MainFile"} class name.
+     * This extension is used by the plugin for identifying in which <abbr>JAR</abbr> file to add this
+     * {@code Main-Class} manifest entry.</p>
+     */
+    private static void assertOwnership(String first, String second, boolean ownerIsFirst) {
+        final Path path = Path.of(".");
+        final Manifest shared = manifestWithMainClass("foo.bar/foo.MainFile");
+        final Manifest m1 = new Manifest(shared);
+        final Manifest m2 = new Manifest(shared);
+        assertEquals(ownerIsFirst, archive(first, null, path).setMainClass(m1));
+        assertEquals(!ownerIsFirst, archive(second, null, path).setMainClass(m2));
+        // Per-module copies must leave the shared plugin manifest untouched.
+        assertEquals("foo.bar/foo.MainFile", mainClassOf(shared));
+        assertNull(mainClassOf(m1));
+        assertNull(mainClassOf(m2));
+    }
+
+    /**
+     * Tests that {@code FileSet} association to target release is consistent regardless creation order.

Review Comment:
   regardless of



##########
src/main/java/org/apache/maven/plugins/jar/Archive.java:
##########
@@ -0,0 +1,692 @@
+/*
+ * 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.jar;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.TreeMap;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.Type;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.MojoException;
+
+/**
+ * Files or root directories to archive for a single module.
+ * A single instance of {@code Archive} may contain many directories for different target Java releases.
+ * Many instances of {@code Archive} may exist when archiving a multi-modules project.
+ */
+final class Archive {
+    /**
+     * Whether to repeat the {@code -C} option before each file.
+     * Doing so makes the command-line very verbose while the documentation of
+     * <a href="https://docs.oracle.com/en/java/javase/25/docs/specs/man/jar.html">The jar Command</a>
+     * gives the impression that this option can be provided only once.
+     * However, our tests suggest that the first file after the directory specified by the {@code -C} option
+     * must be relative to that directory and all files after the first one must be prefixed by the directory
+     * which was specified in the {@code -C} option. This behavior is not documented, but we couldn't get the
+     * {@code jar} tool to work otherwise (except by repeating {@code -C} before each file).
+     * Furthermore, it seems that the relativized file needs to be the shortest one,
+     * otherwise the {@code jar} tool rejects files after the first one with "names do not match".
+     * Which file is first depends on the unspecified directory-iteration order.
+     *
+     * <p>If this flag is {@code true}, the plugin repeats {@code -C} before each file.
+     * This flag should be set to {@code false} if a future version of the {@code jar}
+     * tool allows to specify {@code -C} only once.</p>
+     *
+     * <p><b>Historical note:</b> we also tried to relativize only the first file after {@code -C}
+     * and keep all subsequent files as absolute. It works, but because we have to repeat the directory
+     * in the file name, it saves only 3 or 4 characters per file compared to repeating {@code -C}.</p>
+     */
+    private static final boolean REPEAT_C = true;
+
+    /**
+     * Path to the <abbr>POM</abbr> file generated for this archive, or {@code null} if none.
+     * This is non-null only if module source hierarchy is used, in which case the dependencies
+     * declared in this file are the intersection of the project dependencies and the content of
+     * the {@code module-info.class} file.
+     */
+    @Nullable
+    Path pomFile;
+
+    /**
+     * The <var>JAR</var> file to create. May be an existing file,
+     * in which case the file creation may be skipped if the file is still up-to-date.
+     */
+    @Nonnull
+    final Path jarFile;
+
+    /**
+     * A helper class for checking whether an existing <abbr>JAR</abbr> file is still up-to-date.
+     * This is null if there is no existing JAR file, or if we determined that the file is outdated.
+     */
+    private TimestampCheck existingJAR;
+
+    /**
+     * Name of the module being archived when the project is using module hierarchy.
+     * This is {@code null} if the project is using package hierarchy, either because it is a classical
+     * class-path project or because it is a single module compiled without using the module hierarchy.
+     * When using module source hierarchy, {@code javac} guarantees that the module name in the output
+     * directory is the name of the parent directory of {@code module-info.class}.
+     */
+    @Nullable
+    final String moduleName;
+
+    /**
+     * Path to {@code META-INF/MANIFEST.MF}, or {@code null} if none.
+     * If non-null, this value will be given to the {@code --manifest} option.
+     * The use of this option is preferable to adding {@code MANIFEST.MF} as an ordinary file.
+     *
+     * @see #setManifest(Path, boolean)
+     * @see #mergeManifest(Path, Manifest)
+     */
+    @Nullable
+    private Path manifest;
+
+    /**
+     * The Maven generated {@code pom.xml} and {@code pom.properties} files, or {@code null} if none.
+     * This first item shall be the base directory where the files are located.
+     */
+    @Nullable
+    List<Path> mavenFiles;
+
+    /**
+     * Fully-qualified name of the main class, or {@code null} if none.
+     * This is the value to provide to the {@code --main-class} option.
+     */
+    private String mainClass;
+
+    /**
+     * Files or root directories to store in the <abbr>JAR</abbr> file for each target Java release
+     * other than the base release. Keys are the target Java release with {@code null} for the base
+     * release.
+     */
+    @Nonnull
+    private final NavigableMap<Runtime.Version, FileSet> filesetForRelease;
+
+    /**
+     * Files or root directories to archive for a single target Java release of a single module.
+     * The {@link Archive} enclosing shall contain at least one instance of {@code FileSet} for
+     * the base release, and an arbitrary amount of other instances for other target releases.
+     */
+    final class FileSet {
+        /**
+         * A comparator for sorting paths in a reproducible order.
+         * This comparator assumes that all paths are relative to the same base directory (this is not verified).
+         * Note: we do not use {@link Path#compareTo(Path)} because the Javadoc said that it is platform dependent.
+         */
+        private static final Comparator<Path> REPRODUCIBLE_ORDER = (p1, p2) -> {
+            final int c1 = p1.getNameCount();
+            final int c2 = p2.getNameCount();
+            final int c = Math.min(c1, c2);
+            for (int i = 0; i < c; i++) {
+                String n1 = p1.getName(i).toString();
+                String n2 = p2.getName(i).toString();
+                int r = n1.compareTo(n2); // Case-sensitive comparison on all platforms.
+                if (r != 0) {
+                    return r;
+                }
+            }
+            return c1 - c2;
+        };
+
+        /**
+         * The root directory of all files or directories to archive.
+         * This is the value to pass to the {@code -C} tool option.
+         */
+        @Nonnull
+        final Path directory;
+
+        /**
+         * The files or directories to include in the <var>JAR</var> file.
+         * May be absolute paths or paths relative to {@link #directory}.
+         */
+        @Nonnull
+        final List<Path> files;
+
+        /**
+         * Creates an initially empty set of files or directories for a specific target Java release.
+         *
+         * @param directory the base directory of the files or directories to archive
+         */
+        private FileSet(Path directory) {
+            this.directory = directory;
+            this.files = new ArrayList<>();
+        }
+
+        /**
+         * 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.
+         * The caller should use that common directory for logging a warning message.
+         *
+         * @param base base directory found by previous invocations of this method, or {@code null} if none
+         * @return common directory of discarded files
+         */
+        private Path discardAllFiles(Path base) {
+            for (Path file : files) {
+                file = directory.resolve(file);
+                if (base == null) {
+                    base = file.getParent();
+                } else {
+                    while (!file.startsWith(base)) {
+                        base = base.getParent();
+                        if (base == null) {
+                            break;
+                        }
+                    }
+                }
+            }
+            files.clear();
+            return base;
+        }
+
+        /**
+         * Adds the given path to the list of files or directories to archive.
+         * This method may store a relative path instead of the absolute path.
+         *
+         * @param item a file or directory to archive
+         * @param attributes the file's basic attributes
+         * @param isDirectory whether the file is a directory
+         * @throws IllegalArgumentException if the given path cannot be made relative to the base directory
+         */
+        void add(Path item, BasicFileAttributes attributes, boolean isDirectory) {
+            TimestampCheck tc = existingJAR;
+            if (tc != null && tc.isUpdated(item, attributes, isDirectory)) {
+                existingJAR = null; // Signal that the existing file is outdated.
+            }
+            item = directory.relativize(item);
+            if (item.getNameCount() <= 1 && item.toString().isEmpty()) {
+                /*
+                 * The item is the `-C` directory itself (e.g. a `META-INF/versions/<n>` directory
+                 * added as a whole). An empty file argument is invalid for the `jar` tool
+                 * (some implementations reject it, others silently misbehave),
+                 * so archive the whole directory content with ".".
+                 */
+                item = Path.of(".");
+            }
+            files.add(item);
+        }
+
+        /**
+         * Adds to the given list the arguments to provide to the "jar" tool for this version.
+         * Elements added to the list shall be instances of {@link String} or {@link Path}.
+         *
+         * @param addTo the list where to add the arguments as {@link String} or {@link Path} instances
+         * @param version the target Java release, or {@code null} for the base version of the <abbr>JAR</abbr> file
+         */
+        private void arguments(List<Object> addTo, Runtime.Version version) {
+            if (!files.isEmpty()) {
+                if (version != null) {
+                    addTo.add("--release");
+                    addTo.add(version);
+                }
+                if (isReproducible) {
+                    files.sort(REPRODUCIBLE_ORDER);
+                }
+                if (REPEAT_C) {
+                    for (Path file : files) {
+                        addTo.add("-C");
+                        addTo.add(directory);
+                        addTo.add(file);
+                    }
+                } else {
+                    addTo.add("-C");
+                    addTo.add(directory);
+                    addTo.addAll(files);
+                }
+            }
+        }
+
+        /**
+         * {@return a string representation for debugging purposes}
+         */
+        @Override
+        public String toString() {
+            return getClass().getSimpleName() + '[' + directory.getFileName() + ": " + files.size() + " files]";
+        }
+    }
+
+    /**
+     * Whether reproducible build was requested.
+     */
+    private final boolean isReproducible;
+
+    /**
+     * Creates an initially empty set of files or directories.
+     *
+     * @param jarFile path to the <abbr>JAR</abbr> file to create
+     * @param moduleName the module name if using module hierarchy, or {@code null} if using package hierarchy
+     * @param version the target Java release, or {@code null} for the base version
+     * @param directory the directory of the classes targeting the base Java release
+     * @param forceCreation whether to force a new <abbr>JAR</abbr> file even if the content seems unchanged
+     * @param isReproducible whether reproducible build was requested
+     * @param logger where to send a warning if an error occurred while checking an existing <abbr>JAR</abbr> file
+     */
+    @SuppressWarnings("checkstyle:NeedBraces")

Review Comment:
   It's arguable that this is easier to read. 



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3892102757


##########
src/main/java/org/apache/maven/plugins/jar/TimestampCheck.java:
##########
@@ -0,0 +1,237 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.nio.file.attribute.FileTime;
+import java.util.Collection;
+import java.util.Enumeration;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+
+import org.apache.maven.api.plugin.Log;
+
+/**
+ * Checks file timestamps in order to determine if anything changed compared to an existing <abbr>JAR</abbr> file.
+ * This class may scan directories, but only if they have not already been visited by {@link FileCollector}.
+ * Note that the latter can occur only if {@link FileCollector} has no {@code PathMatcher}.
+ * Therefore, this class uses no {@code PathMatcher} neither.
+ *
+ * <h2>Ignore files</h2>
+ * The {@code META-INF/MANIFEST.MF} file and the {@code META-INF/maven/} directory are ignored.
+ * See {@link #isIgnored(Path)} for the rational.
+ */
+final class TimestampCheck extends SimpleFileVisitor<Path> {
+    /**
+     * The base directory of archived files.
+     */
+    private final Path classesDir;
+
+    /**
+     * Path to the existing <abbr>JAR</abbr> file.
+     */
+    private final Path jarFile;
+
+    /**
+     * The last modified time of the <abbr>JAR</abbr> file.
+     */
+    private final FileTime jarFileTime;
+
+    /**
+     * Where to send non-fatal error messages.
+     */
+    private final Log logger;
+
+    /**
+     * Entries of the <abbr>JAR</abbr> file. Note that getting elements from this enumeration can be costly.
+     * Therefore, we do not fetch all elements in advance but only when needed.
+     */
+    private Enumeration<? extends ZipEntry> entries;
+
+    /**
+     * Files found in the <abbr>JAR</abbr> file but not yet traversed by the file visitor.
+     * Files are added lazily only when needed, and removed as soon as they have been traversed.
+     * Path are absolute (resolved with {@link #classesDir}).
+     */
+    private final Set<Path> filesInJAR;
+
+    /**
+     * Some of the files in the build directory. This list contains only the files for which we have already
+     * verified the timestamp. We store them in a separated list for avoiding to check the timestamp twice.
+     * We need this list because we still need to verify if the files are in the {@link #jarFile}.
+     */
+    private final Set<Path> filesInBuild;
+
+    /**
+     * Whether at least one file is more recent than the <abbr>JAR</abbr> file.
+     * The scan of files will stop quickly after this flag become {@code true}.

Review Comment:
   Not immediately because there is a few method calls between the moment when this flag is set and the moment when it is read and the visit interrupted.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3891945076


##########
src/main/java/org/apache/maven/plugins/jar/Archive.java:
##########
@@ -0,0 +1,692 @@
+/*
+ * 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.jar;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.TreeMap;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.Type;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.MojoException;
+
+/**
+ * Files or root directories to archive for a single module.
+ * A single instance of {@code Archive} may contain many directories for different target Java releases.
+ * Many instances of {@code Archive} may exist when archiving a multi-modules project.
+ */
+final class Archive {
+    /**
+     * Whether to repeat the {@code -C} option before each file.
+     * Doing so makes the command-line very verbose while the documentation of
+     * <a href="https://docs.oracle.com/en/java/javase/25/docs/specs/man/jar.html">The jar Command</a>
+     * gives the impression that this option can be provided only once.
+     * However, our tests suggest that the first file after the directory specified by the {@code -C} option
+     * must be relative to that directory and all files after the first one must be prefixed by the directory
+     * which was specified in the {@code -C} option. This behavior is not documented, but we couldn't get the
+     * {@code jar} tool to work otherwise (except by repeating {@code -C} before each file).
+     * Furthermore, it seems that the relativized file needs to be the shortest one,
+     * otherwise the {@code jar} tool rejects files after the first one with "names do not match".
+     * Which file is first depends on the unspecified directory-iteration order.
+     *
+     * <p>If this flag is {@code true}, the plugin repeats {@code -C} before each file.
+     * This flag should be set to {@code false} if a future version of the {@code jar}
+     * tool allows to specify {@code -C} only once.</p>
+     *
+     * <p><b>Historical note:</b> we also tried to relativize only the first file after {@code -C}
+     * and keep all subsequent files as absolute. It works, but because we have to repeat the directory
+     * in the file name, it saves only 3 or 4 characters per file compared to repeating {@code -C}.</p>
+     */
+    private static final boolean REPEAT_C = true;
+
+    /**
+     * Path to the <abbr>POM</abbr> file generated for this archive, or {@code null} if none.
+     * This is non-null only if module source hierarchy is used, in which case the dependencies
+     * declared in this file are the intersection of the project dependencies and the content of
+     * the {@code module-info.class} file.
+     */
+    @Nullable
+    Path pomFile;
+
+    /**
+     * The <var>JAR</var> file to create. May be an existing file,
+     * in which case the file creation may be skipped if the file is still up-to-date.
+     */
+    @Nonnull
+    final Path jarFile;
+
+    /**
+     * A helper class for checking whether an existing <abbr>JAR</abbr> file is still up-to-date.
+     * This is null if there is no existing JAR file, or if we determined that the file is outdated.
+     */
+    private TimestampCheck existingJAR;
+
+    /**
+     * Name of the module being archived when the project is using module hierarchy.
+     * This is {@code null} if the project is using package hierarchy, either because it is a classical
+     * class-path project or because it is a single module compiled without using the module hierarchy.
+     * When using module source hierarchy, {@code javac} guarantees that the module name in the output
+     * directory is the name of the parent directory of {@code module-info.class}.
+     */
+    @Nullable
+    final String moduleName;
+
+    /**
+     * Path to {@code META-INF/MANIFEST.MF}, or {@code null} if none.
+     * If non-null, this value will be given to the {@code --manifest} option.
+     * The use of this option is preferable to adding {@code MANIFEST.MF} as an ordinary file.
+     *
+     * @see #setManifest(Path, boolean)
+     * @see #mergeManifest(Path, Manifest)
+     */
+    @Nullable
+    private Path manifest;
+
+    /**
+     * The Maven generated {@code pom.xml} and {@code pom.properties} files, or {@code null} if none.
+     * This first item shall be the base directory where the files are located.
+     */
+    @Nullable
+    List<Path> mavenFiles;
+
+    /**
+     * Fully-qualified name of the main class, or {@code null} if none.
+     * This is the value to provide to the {@code --main-class} option.
+     */
+    private String mainClass;
+
+    /**
+     * Files or root directories to store in the <abbr>JAR</abbr> file for each target Java release
+     * other than the base release. Keys are the target Java release with {@code null} for the base
+     * release.
+     */
+    @Nonnull
+    private final NavigableMap<Runtime.Version, FileSet> filesetForRelease;
+
+    /**
+     * Files or root directories to archive for a single target Java release of a single module.
+     * The {@link Archive} enclosing shall contain at least one instance of {@code FileSet} for
+     * the base release, and an arbitrary amount of other instances for other target releases.
+     */
+    final class FileSet {
+        /**
+         * A comparator for sorting paths in a reproducible order.
+         * This comparator assumes that all paths are relative to the same base directory (this is not verified).
+         * Note: we do not use {@link Path#compareTo(Path)} because the Javadoc said that it is platform dependent.
+         */
+        private static final Comparator<Path> REPRODUCIBLE_ORDER = (p1, p2) -> {
+            final int c1 = p1.getNameCount();
+            final int c2 = p2.getNameCount();
+            final int c = Math.min(c1, c2);
+            for (int i = 0; i < c; i++) {
+                String n1 = p1.getName(i).toString();
+                String n2 = p2.getName(i).toString();
+                int r = n1.compareTo(n2); // Case-sensitive comparison on all platforms.
+                if (r != 0) {
+                    return r;
+                }
+            }
+            return c1 - c2;
+        };
+
+        /**
+         * The root directory of all files or directories to archive.
+         * This is the value to pass to the {@code -C} tool option.
+         */
+        @Nonnull
+        final Path directory;
+
+        /**
+         * The files or directories to include in the <var>JAR</var> file.
+         * May be absolute paths or paths relative to {@link #directory}.
+         */
+        @Nonnull
+        final List<Path> files;
+
+        /**
+         * Creates an initially empty set of files or directories for a specific target Java release.
+         *
+         * @param directory the base directory of the files or directories to archive
+         */
+        private FileSet(Path directory) {
+            this.directory = directory;
+            this.files = new ArrayList<>();
+        }
+
+        /**
+         * 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.
+         * The caller should use that common directory for logging a warning message.
+         *
+         * @param base base directory found by previous invocations of this method, or {@code null} if none
+         * @return common directory of discarded files
+         */
+        private Path discardAllFiles(Path base) {
+            for (Path file : files) {
+                file = directory.resolve(file);
+                if (base == null) {
+                    base = file.getParent();
+                } else {
+                    while (!file.startsWith(base)) {
+                        base = base.getParent();
+                        if (base == null) {
+                            break;
+                        }
+                    }
+                }
+            }
+            files.clear();
+            return base;
+        }
+
+        /**
+         * Adds the given path to the list of files or directories to archive.
+         * This method may store a relative path instead of the absolute path.
+         *
+         * @param item a file or directory to archive
+         * @param attributes the file's basic attributes
+         * @param isDirectory whether the file is a directory
+         * @throws IllegalArgumentException if the given path cannot be made relative to the base directory
+         */
+        void add(Path item, BasicFileAttributes attributes, boolean isDirectory) {
+            TimestampCheck tc = existingJAR;
+            if (tc != null && tc.isUpdated(item, attributes, isDirectory)) {
+                existingJAR = null; // Signal that the existing file is outdated.
+            }
+            item = directory.relativize(item);
+            if (item.getNameCount() <= 1 && item.toString().isEmpty()) {
+                /*
+                 * The item is the `-C` directory itself (e.g. a `META-INF/versions/<n>` directory
+                 * added as a whole). An empty file argument is invalid for the `jar` tool
+                 * (some implementations reject it, others silently misbehave),
+                 * so archive the whole directory content with ".".
+                 */
+                item = Path.of(".");
+            }
+            files.add(item);
+        }
+
+        /**
+         * Adds to the given list the arguments to provide to the "jar" tool for this version.
+         * Elements added to the list shall be instances of {@link String} or {@link Path}.
+         *
+         * @param addTo the list where to add the arguments as {@link String} or {@link Path} instances
+         * @param version the target Java release, or {@code null} for the base version of the <abbr>JAR</abbr> file
+         */
+        private void arguments(List<Object> addTo, Runtime.Version version) {
+            if (!files.isEmpty()) {
+                if (version != null) {
+                    addTo.add("--release");
+                    addTo.add(version);
+                }
+                if (isReproducible) {
+                    files.sort(REPRODUCIBLE_ORDER);
+                }
+                if (REPEAT_C) {
+                    for (Path file : files) {
+                        addTo.add("-C");
+                        addTo.add(directory);
+                        addTo.add(file);
+                    }
+                } else {
+                    addTo.add("-C");
+                    addTo.add(directory);
+                    addTo.addAll(files);
+                }
+            }
+        }
+
+        /**
+         * {@return a string representation for debugging purposes}
+         */
+        @Override
+        public String toString() {
+            return getClass().getSimpleName() + '[' + directory.getFileName() + ": " + files.size() + " files]";
+        }
+    }
+
+    /**
+     * Whether reproducible build was requested.
+     */
+    private final boolean isReproducible;
+
+    /**
+     * Creates an initially empty set of files or directories.
+     *
+     * @param jarFile path to the <abbr>JAR</abbr> file to create
+     * @param moduleName the module name if using module hierarchy, or {@code null} if using package hierarchy
+     * @param version the target Java release, or {@code null} for the base version
+     * @param directory the directory of the classes targeting the base Java release
+     * @param forceCreation whether to force a new <abbr>JAR</abbr> file even if the content seems unchanged
+     * @param isReproducible whether reproducible build was requested
+     * @param logger where to send a warning if an error occurred while checking an existing <abbr>JAR</abbr> file
+     */
+    @SuppressWarnings("checkstyle:NeedBraces")
+    Archive(
+            final Path jarFile,
+            final String moduleName,
+            final Runtime.Version version,
+            final Path directory,
+            final boolean forceCreation,
+            final boolean isReproducible,
+            final Log logger) {
+        this.jarFile = jarFile;
+        this.moduleName = moduleName;
+        this.isReproducible = isReproducible;
+        filesetForRelease = new TreeMap<>((v1, v2) -> {
+            if (v1 == v2) return 0;
+            if (v1 == null) return -1;
+            if (v2 == null) return +1;
+            return v1.compareTo(v2);
+        });
+        filesetForRelease.put(version, new FileSet(directory));
+        if (!forceCreation && Files.isRegularFile(jarFile)) {
+            try {
+                existingJAR = new TimestampCheck(jarFile, directory, logger);
+            } catch (IOException e) {
+                // Ignore, we will regenerate the JAR file.
+                logger.warn(e);
+            }
+        }
+    }
+
+    /**
+     * {@return the files or directories to store in the <abbr>JAR</abbr> file for targeting the base Java release}
+     *
+     * @throws NoSuchElementException should not happen unless {@link #prune(boolean)} has been invoked
+     */
+    FileSet baseRelease() {
+        Map.Entry<Runtime.Version, FileSet> entry = filesetForRelease.firstEntry();
+        String message = null;
+        if (entry != null) {
+            Runtime.Version version = entry.getKey();
+            if (version == null) {
+                return entry.getValue();
+            }
+            message = "Expected base version but found version " + version;
+        }
+        throw new NoSuchElementException(message);
+    }
+
+    /**
+     * Returns the {@code module-info.class} files. Conceptually, there is at most once such file per module.
+     * However, more than one file may exist if additional files are provided for additional Java releases.
+     * This method returns only the files that exist.
+     *
+     * @return all {@code module-info.class} files found for all target Java releases
+     */
+    public List<Path> moduleInfoFiles() {
+        var files = new ArrayList<Path>();
+        filesetForRelease.values().forEach((release) -> {
+            Path file = release.directory.resolve(FileCollector.MODULE_DESCRIPTOR_FILE_NAME);
+            if (Files.isRegularFile(file)) {
+                files.add(file);
+            }
+        });
+        return files;
+    }
+
+    /**
+     * Discards all files in this archive, normally because those files are not in any module.
+     * This method returns a common parent directory for all the files that were discarded.
+     * The caller should use that common directory for logging a warning message.
+     *
+     * @return common directory of discarded files, or {@code null} if none
+     */
+    Path discardAllFiles() {
+        Path base = null;
+        for (FileSet release : filesetForRelease.values()) {
+            base = release.discardAllFiles(base);
+        }
+        filesetForRelease.clear();
+        return base;
+    }
+
+    /**
+     * Removes all empty file sets 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}, then this method ensures that at least one file set
+     * remains even if that file set is empty.
+     *
+     * @param skipIfEmpty value of {@link AbstractJarMojo#skipIfEmpty}
+     */
+    public void prune(final boolean skipIfEmpty) {
+        FileSet keep = (skipIfEmpty || isEmpty())
+                ? null
+                : filesetForRelease.firstEntry().getValue();
+        filesetForRelease.values().removeIf((fs) -> fs.files.isEmpty());
+        Iterator<Map.Entry<Runtime.Version, FileSet>> it =
+                filesetForRelease.entrySet().iterator();
+        if (it.hasNext()) {
+            Map.Entry<Runtime.Version, FileSet> first = it.next();
+            if (first.getKey() == null) {
+                return; // Already contains an entry for the base version, nothing to do.
+            }
+            keep = first.getValue();
+            it.remove();
+        }
+        if (keep != null) {
+            filesetForRelease.put(null, keep);
+        }
+    }
+
+    /**
+     * {@return whether this archive has nothing to archive}
+     * Note that this method may return {@code false} even when there is zero file to archive.
+     * It may happen if {@link AbstractJarMojo#skipIfEmpty} is {@code false}. In such case, the
+     * "empty" <abbr>JAR</abbr> file will still contain at {@code META-INF/MANIFEST.MF} file.
+     *
+     * <h4>Prerequisites</h4>
+     * The {@link #prune(boolean)} method should be invoked before this method for accurate result.
+     */
+    public boolean isEmpty() {
+        return filesetForRelease.isEmpty();
+    }
+
+    /**
+     * Checks whether the <abbr>JAR</abbr> file already exists and can be reused.
+     * This method verifies that the <abbr>JAR</abbr> file contains all the files to archive,
+     * contains no extra file, and no file to archive is newer than the <abbr>JAR</abbr> file.
+     *
+     * <p>This method can be invoked only once.
+     * If invoked more often, it returns {@code false} on all subsequent invocations.</p>
+     *
+     * @return whether the <abbr>JAR</abbr> file already exists and can be reused
+     */
+    public boolean isUpToDateJAR() {
+        final TimestampCheck tc = existingJAR;
+        if (tc == null) {
+            return false;
+        }
+        existingJAR = null; // Let GC do its job.
+        return tc.isUpToDateJAR(filesetForRelease.values());
+    }
+
+    /**
+     * Returns an initially empty set of files or directories for the specified target Java release.
+     *
+     * @param directory the base directory of the files to archive
+     * @param version the target Java release, or {@code null} for the base version
+     * @return container where to declare files and directories to archive
+     */
+    FileSet newTargetRelease(Path directory, Runtime.Version version) {
+        return filesetForRelease.computeIfAbsent(version, (key) -> new FileSet(directory));
+    }
+
+    /**
+     * Sets the {@code --main-class} option to the value of the {@code Main-Class} entry of the given manifest.
+     * As an extension, this method accepts the {@code module/classname} syntax (a syntax already used in some
+     * Java tools). If a module is specified, the main class is kept only if the module match. The intent is to
+     * allow users to specify on which module the main class applies when they use plugin configuration.
+     *
+     * <p>This method may modify the {@code content} manifest. Caller shall ensure that the given manifest
+     * is not a shared instance. This method returns whether a change has actually been done.</p>
+     *
+     * @param content combination of existing {@code MANIFEST.MF} and manifest inferred from configuration, or null
+     * @return whether the given manifest has been modified by this method
+     */
+    boolean setMainClass(Manifest content) {
+        if (content == null || mainClass != null) {
+            return false;
+        }
+        // We need to remove the attribute, otherwise it will conflict with `--main-class`.
+        mainClass = (String) content.getMainAttributes().remove(Attributes.Name.MAIN_CLASS);
+        if (mainClass != null) {
+            int s = mainClass.indexOf('/');
+            if (s >= 0) {
+                if (mainClass.substring(0, s).strip().equals(moduleName)) {
+                    mainClass = mainClass.substring(s + 1).strip();
+                } else {
+                    mainClass = null; // Main class is defined for another module.
+                }
+            }
+        }
+        return mainClass != null;
+    }
+
+    /**
+     * Sets the {@code --manifest} option to the given value if that option was not already set.
+     *
+     * @param file path to the manifest file
+     * @param force whether to set the manifest even if already set
+     * @return whether the manifest has been set
+     */
+    boolean setManifest(Path file, boolean force) {
+        if (manifest == null || force) {
+            manifest = file;
+            return true;
+        }
+        return false;
+    }
+
+    /**
+     * Merges the manifest of this module with the manifest specified in plugin configuration.
+     * If both {@code file} and {@code content} are non-null, then {@code content} must be the
+     * result of reading {@code file}.
+     *
+     * <p>This method never modifies the given {@code content} object. If manifest are merged,
+     * a new {@link Manifest} instance is created. Therefore, caller can check whether this
+     * method returned a new instance as a way to recognize that a merge occurred.</p>
+     *
+     * <p>If a merge occurs, the content specified to {@link #setManifest(Path)} has precedence.
+     * It should be the {@code target/classes/META-INF/MANIFEST.MF} file (or modular equivalent).</p>
+     *
+     * @param  file     an additional manifest file, or {@code null}
+     * @param  content  the content of {@code file}, or a standalone manifest produced at runtime
+     * @return the merged manifest as a new instance if some changes were necessary
+     * @throws IOException if an error occurred while reading a manifest file
+     */
+    Manifest mergeManifest(Path file, Manifest content) throws IOException {
+        if (manifest == null) {
+            manifest = file;
+        } else if (file != null && Files.isSameFile(file, manifest)) {
+            // Nothing to merge because of the constraint that `content` must be the content of `file`.
+        } else {
+            try (InputStream in = Files.newInputStream(manifest)) {
+                // No need to wrap in `BufferedInputStream`.
+                if (content != null) {
+                    content = new Manifest(content);
+                    content.read(in);
+                } else {
+                    content = new Manifest(in);
+                }
+            }
+        }
+        return content;
+    }
+
+    /**
+     * Adds to the given list the arguments to provide to the "jar" tool for each version.
+     * Elements added to the list shall be instances of {@link String} or {@link Path}.
+     * Callers should have added the following options (if applicable) before to invoke this method:
+     *
+     * <ul>
+     *   <li>{@code --create}</li>
+     *   <li>{@code --no-compress}</li>
+     *   <li>{@code --date} followed by the output time stamp</li>
+     *   <li>{@code --module-version} followed by module version</li>
+     *   <li>{@code --hash-modules} followed by patters of module names</li>
+     *   <li>{@code --module-path} followed by module path</li>
+     * </ul>
+     *
+     * This method adds the following options:
+     *
+     * <ul>
+     *   <li>{@code --file} followed by the path to the <abbr>JAR</abbr> file</li>
+     *   <li>{@code --manifest} followed by path to the manifest file</li>
+     *   <li>{@code --main-class} followed by fully qualified name class</li>
+     *   <li>{@code --release} followed by Java target release</li>
+     *   <li>{@code -C} followed by directory</li>
+     *   <li>files or directories to archive</li>
+     * </ul>
+     *
+     * @param addTo the list where to add the arguments as {@link String} or {@link Path} instances
+     */
+    void arguments(final List<Object> addTo) {
+        addTo.add("--file");
+        addTo.add(jarFile);
+        if (manifest != null) {
+            addTo.add("--manifest");
+            addTo.add(manifest);
+        }
+        if (mainClass != null) {
+            addTo.add("--main-class");
+            addTo.add(mainClass);
+        }
+        if (mavenFiles != null) {
+            addTo.add("-C");
+            addTo.addAll(mavenFiles);
+        }
+        for (Map.Entry<Runtime.Version, FileSet> entry : filesetForRelease.entrySet()) {
+            entry.getValue().arguments(addTo, entry.getKey());
+        }
+    }
+
+    /**
+     * Adds to the given list the arguments to provide to the "jar" tool for validating the <abbr>JAR</abbr> file.
+     * The file is validated only if the validation was not done implicitly at <abbr>JAR</abbr> creation time.
+     * This is the case if no {@code --release} option was used.
+     * This method adds the following options:
+     *
+     * <ul>
+     *   <li>{@code --validate} operation mode</li>
+     *   <li>{@code --file} followed by the path to the <abbr>JAR</abbr> file</li>
+     * </ul>
+     *
+     * @param  addTo the list where to add the arguments as {@link String} or {@link Path} instances

Review Comment:
   Done



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3891938195


##########
src/main/java/org/apache/maven/plugins/jar/Archive.java:
##########
@@ -0,0 +1,692 @@
+/*
+ * 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.jar;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.TreeMap;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.Type;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.MojoException;
+
+/**
+ * Files or root directories to archive for a single module.
+ * A single instance of {@code Archive} may contain many directories for different target Java releases.
+ * Many instances of {@code Archive} may exist when archiving a multi-modules project.
+ */
+final class Archive {
+    /**
+     * Whether to repeat the {@code -C} option before each file.
+     * Doing so makes the command-line very verbose while the documentation of
+     * <a href="https://docs.oracle.com/en/java/javase/25/docs/specs/man/jar.html">The jar Command</a>
+     * gives the impression that this option can be provided only once.
+     * However, our tests suggest that the first file after the directory specified by the {@code -C} option
+     * must be relative to that directory and all files after the first one must be prefixed by the directory
+     * which was specified in the {@code -C} option. This behavior is not documented, but we couldn't get the
+     * {@code jar} tool to work otherwise (except by repeating {@code -C} before each file).
+     * Furthermore, it seems that the relativized file needs to be the shortest one,
+     * otherwise the {@code jar} tool rejects files after the first one with "names do not match".
+     * Which file is first depends on the unspecified directory-iteration order.
+     *
+     * <p>If this flag is {@code true}, the plugin repeats {@code -C} before each file.
+     * This flag should be set to {@code false} if a future version of the {@code jar}
+     * tool allows to specify {@code -C} only once.</p>
+     *
+     * <p><b>Historical note:</b> we also tried to relativize only the first file after {@code -C}
+     * and keep all subsequent files as absolute. It works, but because we have to repeat the directory
+     * in the file name, it saves only 3 or 4 characters per file compared to repeating {@code -C}.</p>
+     */
+    private static final boolean REPEAT_C = true;
+
+    /**
+     * Path to the <abbr>POM</abbr> file generated for this archive, or {@code null} if none.
+     * This is non-null only if module source hierarchy is used, in which case the dependencies
+     * declared in this file are the intersection of the project dependencies and the content of
+     * the {@code module-info.class} file.
+     */
+    @Nullable
+    Path pomFile;
+
+    /**
+     * The <var>JAR</var> file to create. May be an existing file,
+     * in which case the file creation may be skipped if the file is still up-to-date.
+     */
+    @Nonnull
+    final Path jarFile;
+
+    /**
+     * A helper class for checking whether an existing <abbr>JAR</abbr> file is still up-to-date.
+     * This is null if there is no existing JAR file, or if we determined that the file is outdated.
+     */
+    private TimestampCheck existingJAR;
+
+    /**
+     * Name of the module being archived when the project is using module hierarchy.
+     * This is {@code null} if the project is using package hierarchy, either because it is a classical
+     * class-path project or because it is a single module compiled without using the module hierarchy.
+     * When using module source hierarchy, {@code javac} guarantees that the module name in the output
+     * directory is the name of the parent directory of {@code module-info.class}.
+     */
+    @Nullable
+    final String moduleName;
+
+    /**
+     * Path to {@code META-INF/MANIFEST.MF}, or {@code null} if none.
+     * If non-null, this value will be given to the {@code --manifest} option.
+     * The use of this option is preferable to adding {@code MANIFEST.MF} as an ordinary file.
+     *
+     * @see #setManifest(Path, boolean)
+     * @see #mergeManifest(Path, Manifest)
+     */
+    @Nullable
+    private Path manifest;
+
+    /**
+     * The Maven generated {@code pom.xml} and {@code pom.properties} files, or {@code null} if none.
+     * This first item shall be the base directory where the files are located.
+     */
+    @Nullable
+    List<Path> mavenFiles;
+
+    /**
+     * Fully-qualified name of the main class, or {@code null} if none.
+     * This is the value to provide to the {@code --main-class} option.
+     */
+    private String mainClass;
+
+    /**
+     * Files or root directories to store in the <abbr>JAR</abbr> file for each target Java release
+     * other than the base release. Keys are the target Java release with {@code null} for the base
+     * release.
+     */
+    @Nonnull
+    private final NavigableMap<Runtime.Version, FileSet> filesetForRelease;
+
+    /**
+     * Files or root directories to archive for a single target Java release of a single module.
+     * The {@link Archive} enclosing shall contain at least one instance of {@code FileSet} for
+     * the base release, and an arbitrary amount of other instances for other target releases.
+     */
+    final class FileSet {
+        /**
+         * A comparator for sorting paths in a reproducible order.
+         * This comparator assumes that all paths are relative to the same base directory (this is not verified).
+         * Note: we do not use {@link Path#compareTo(Path)} because the Javadoc said that it is platform dependent.
+         */
+        private static final Comparator<Path> REPRODUCIBLE_ORDER = (p1, p2) -> {
+            final int c1 = p1.getNameCount();
+            final int c2 = p2.getNameCount();
+            final int c = Math.min(c1, c2);
+            for (int i = 0; i < c; i++) {
+                String n1 = p1.getName(i).toString();
+                String n2 = p2.getName(i).toString();
+                int r = n1.compareTo(n2); // Case-sensitive comparison on all platforms.
+                if (r != 0) {
+                    return r;
+                }
+            }
+            return c1 - c2;
+        };
+
+        /**
+         * The root directory of all files or directories to archive.
+         * This is the value to pass to the {@code -C} tool option.
+         */
+        @Nonnull
+        final Path directory;
+
+        /**
+         * The files or directories to include in the <var>JAR</var> file.
+         * May be absolute paths or paths relative to {@link #directory}.
+         */
+        @Nonnull
+        final List<Path> files;
+
+        /**
+         * Creates an initially empty set of files or directories for a specific target Java release.
+         *
+         * @param directory the base directory of the files or directories to archive
+         */
+        private FileSet(Path directory) {
+            this.directory = directory;
+            this.files = new ArrayList<>();
+        }
+
+        /**
+         * 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.
+         * The caller should use that common directory for logging a warning message.
+         *
+         * @param base base directory found by previous invocations of this method, or {@code null} if none
+         * @return common directory of discarded files
+         */
+        private Path discardAllFiles(Path base) {
+            for (Path file : files) {
+                file = directory.resolve(file);
+                if (base == null) {
+                    base = file.getParent();
+                } else {
+                    while (!file.startsWith(base)) {
+                        base = base.getParent();
+                        if (base == null) {
+                            break;
+                        }
+                    }
+                }
+            }
+            files.clear();
+            return base;
+        }
+
+        /**
+         * Adds the given path to the list of files or directories to archive.
+         * This method may store a relative path instead of the absolute path.
+         *
+         * @param item a file or directory to archive
+         * @param attributes the file's basic attributes
+         * @param isDirectory whether the file is a directory
+         * @throws IllegalArgumentException if the given path cannot be made relative to the base directory
+         */
+        void add(Path item, BasicFileAttributes attributes, boolean isDirectory) {
+            TimestampCheck tc = existingJAR;
+            if (tc != null && tc.isUpdated(item, attributes, isDirectory)) {
+                existingJAR = null; // Signal that the existing file is outdated.
+            }
+            item = directory.relativize(item);
+            if (item.getNameCount() <= 1 && item.toString().isEmpty()) {
+                /*
+                 * The item is the `-C` directory itself (e.g. a `META-INF/versions/<n>` directory
+                 * added as a whole). An empty file argument is invalid for the `jar` tool
+                 * (some implementations reject it, others silently misbehave),
+                 * so archive the whole directory content with ".".
+                 */
+                item = Path.of(".");
+            }
+            files.add(item);
+        }
+
+        /**
+         * Adds to the given list the arguments to provide to the "jar" tool for this version.
+         * Elements added to the list shall be instances of {@link String} or {@link Path}.
+         *
+         * @param addTo the list where to add the arguments as {@link String} or {@link Path} instances
+         * @param version the target Java release, or {@code null} for the base version of the <abbr>JAR</abbr> file
+         */
+        private void arguments(List<Object> addTo, Runtime.Version version) {
+            if (!files.isEmpty()) {
+                if (version != null) {
+                    addTo.add("--release");
+                    addTo.add(version);
+                }
+                if (isReproducible) {
+                    files.sort(REPRODUCIBLE_ORDER);
+                }
+                if (REPEAT_C) {
+                    for (Path file : files) {
+                        addTo.add("-C");
+                        addTo.add(directory);
+                        addTo.add(file);
+                    }
+                } else {
+                    addTo.add("-C");
+                    addTo.add(directory);
+                    addTo.addAll(files);
+                }
+            }
+        }
+
+        /**
+         * {@return a string representation for debugging purposes}
+         */
+        @Override
+        public String toString() {
+            return getClass().getSimpleName() + '[' + directory.getFileName() + ": " + files.size() + " files]";
+        }
+    }
+
+    /**
+     * Whether reproducible build was requested.
+     */
+    private final boolean isReproducible;
+
+    /**
+     * Creates an initially empty set of files or directories.
+     *
+     * @param jarFile path to the <abbr>JAR</abbr> file to create
+     * @param moduleName the module name if using module hierarchy, or {@code null} if using package hierarchy
+     * @param version the target Java release, or {@code null} for the base version
+     * @param directory the directory of the classes targeting the base Java release
+     * @param forceCreation whether to force a new <abbr>JAR</abbr> file even if the content seems unchanged
+     * @param isReproducible whether reproducible build was requested
+     * @param logger where to send a warning if an error occurred while checking an existing <abbr>JAR</abbr> file
+     */
+    @SuppressWarnings("checkstyle:NeedBraces")
+    Archive(
+            final Path jarFile,
+            final String moduleName,
+            final Runtime.Version version,
+            final Path directory,
+            final boolean forceCreation,
+            final boolean isReproducible,
+            final Log logger) {
+        this.jarFile = jarFile;
+        this.moduleName = moduleName;
+        this.isReproducible = isReproducible;
+        filesetForRelease = new TreeMap<>((v1, v2) -> {
+            if (v1 == v2) return 0;
+            if (v1 == null) return -1;
+            if (v2 == null) return +1;
+            return v1.compareTo(v2);
+        });
+        filesetForRelease.put(version, new FileSet(directory));
+        if (!forceCreation && Files.isRegularFile(jarFile)) {
+            try {
+                existingJAR = new TimestampCheck(jarFile, directory, logger);
+            } catch (IOException e) {
+                // Ignore, we will regenerate the JAR file.
+                logger.warn(e);
+            }
+        }
+    }
+
+    /**
+     * {@return the files or directories to store in the <abbr>JAR</abbr> file for targeting the base Java release}
+     *
+     * @throws NoSuchElementException should not happen unless {@link #prune(boolean)} has been invoked
+     */
+    FileSet baseRelease() {
+        Map.Entry<Runtime.Version, FileSet> entry = filesetForRelease.firstEntry();
+        String message = null;
+        if (entry != null) {
+            Runtime.Version version = entry.getKey();
+            if (version == null) {
+                return entry.getValue();
+            }
+            message = "Expected base version but found version " + version;
+        }
+        throw new NoSuchElementException(message);
+    }
+
+    /**
+     * Returns the {@code module-info.class} files. Conceptually, there is at most once such file per module.
+     * However, more than one file may exist if additional files are provided for additional Java releases.
+     * This method returns only the files that exist.
+     *
+     * @return all {@code module-info.class} files found for all target Java releases
+     */
+    public List<Path> moduleInfoFiles() {
+        var files = new ArrayList<Path>();
+        filesetForRelease.values().forEach((release) -> {
+            Path file = release.directory.resolve(FileCollector.MODULE_DESCRIPTOR_FILE_NAME);
+            if (Files.isRegularFile(file)) {
+                files.add(file);
+            }
+        });
+        return files;
+    }
+
+    /**
+     * Discards all files in this archive, normally because those files are not in any module.
+     * This method returns a common parent directory for all the files that were discarded.
+     * The caller should use that common directory for logging a warning message.
+     *
+     * @return common directory of discarded files, or {@code null} if none
+     */
+    Path discardAllFiles() {
+        Path base = null;
+        for (FileSet release : filesetForRelease.values()) {
+            base = release.discardAllFiles(base);
+        }
+        filesetForRelease.clear();
+        return base;
+    }
+
+    /**
+     * Removes all empty file sets 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}, then this method ensures that at least one file set
+     * remains even if that file set is empty.
+     *
+     * @param skipIfEmpty value of {@link AbstractJarMojo#skipIfEmpty}
+     */
+    public void prune(final boolean skipIfEmpty) {
+        FileSet keep = (skipIfEmpty || isEmpty())
+                ? null
+                : filesetForRelease.firstEntry().getValue();
+        filesetForRelease.values().removeIf((fs) -> fs.files.isEmpty());
+        Iterator<Map.Entry<Runtime.Version, FileSet>> it =
+                filesetForRelease.entrySet().iterator();
+        if (it.hasNext()) {
+            Map.Entry<Runtime.Version, FileSet> first = it.next();
+            if (first.getKey() == null) {
+                return; // Already contains an entry for the base version, nothing to do.
+            }
+            keep = first.getValue();
+            it.remove();
+        }
+        if (keep != null) {
+            filesetForRelease.put(null, keep);
+        }
+    }
+
+    /**
+     * {@return whether this archive has nothing to archive}
+     * Note that this method may return {@code false} even when there is zero file to archive.
+     * It may happen if {@link AbstractJarMojo#skipIfEmpty} is {@code false}. In such case, the
+     * "empty" <abbr>JAR</abbr> file will still contain at {@code META-INF/MANIFEST.MF} file.
+     *
+     * <h4>Prerequisites</h4>
+     * The {@link #prune(boolean)} method should be invoked before this method for accurate result.
+     */
+    public boolean isEmpty() {
+        return filesetForRelease.isEmpty();
+    }
+
+    /**
+     * Checks whether the <abbr>JAR</abbr> file already exists and can be reused.
+     * This method verifies that the <abbr>JAR</abbr> file contains all the files to archive,
+     * contains no extra file, and no file to archive is newer than the <abbr>JAR</abbr> file.
+     *
+     * <p>This method can be invoked only once.
+     * If invoked more often, it returns {@code false} on all subsequent invocations.</p>
+     *
+     * @return whether the <abbr>JAR</abbr> file already exists and can be reused
+     */
+    public boolean isUpToDateJAR() {
+        final TimestampCheck tc = existingJAR;
+        if (tc == null) {
+            return false;
+        }
+        existingJAR = null; // Let GC do its job.
+        return tc.isUpToDateJAR(filesetForRelease.values());
+    }
+
+    /**
+     * Returns an initially empty set of files or directories for the specified target Java release.
+     *
+     * @param directory the base directory of the files to archive
+     * @param version the target Java release, or {@code null} for the base version
+     * @return container where to declare files and directories to archive
+     */
+    FileSet newTargetRelease(Path directory, Runtime.Version version) {
+        return filesetForRelease.computeIfAbsent(version, (key) -> new FileSet(directory));
+    }
+
+    /**
+     * Sets the {@code --main-class} option to the value of the {@code Main-Class} entry of the given manifest.
+     * As an extension, this method accepts the {@code module/classname} syntax (a syntax already used in some
+     * Java tools). If a module is specified, the main class is kept only if the module match. The intent is to
+     * allow users to specify on which module the main class applies when they use plugin configuration.
+     *
+     * <p>This method may modify the {@code content} manifest. Caller shall ensure that the given manifest
+     * is not a shared instance. This method returns whether a change has actually been done.</p>
+     *
+     * @param content combination of existing {@code MANIFEST.MF} and manifest inferred from configuration, or null
+     * @return whether the given manifest has been modified by this method
+     */
+    boolean setMainClass(Manifest content) {
+        if (content == null || mainClass != null) {
+            return false;
+        }
+        // We need to remove the attribute, otherwise it will conflict with `--main-class`.
+        mainClass = (String) content.getMainAttributes().remove(Attributes.Name.MAIN_CLASS);
+        if (mainClass != null) {
+            int s = mainClass.indexOf('/');
+            if (s >= 0) {
+                if (mainClass.substring(0, s).strip().equals(moduleName)) {
+                    mainClass = mainClass.substring(s + 1).strip();
+                } else {
+                    mainClass = null; // Main class is defined for another module.
+                }
+            }
+        }
+        return mainClass != null;
+    }
+
+    /**
+     * Sets the {@code --manifest} option to the given value if that option was not already set.
+     *
+     * @param file path to the manifest file
+     * @param force whether to set the manifest even if already set
+     * @return whether the manifest has been set
+     */
+    boolean setManifest(Path file, boolean force) {
+        if (manifest == null || force) {
+            manifest = file;
+            return true;
+        }
+        return false;
+    }
+
+    /**
+     * Merges the manifest of this module with the manifest specified in plugin configuration.
+     * If both {@code file} and {@code content} are non-null, then {@code content} must be the
+     * result of reading {@code file}.
+     *
+     * <p>This method never modifies the given {@code content} object. If manifest are merged,
+     * a new {@link Manifest} instance is created. Therefore, caller can check whether this
+     * method returned a new instance as a way to recognize that a merge occurred.</p>
+     *
+     * <p>If a merge occurs, the content specified to {@link #setManifest(Path)} has precedence.
+     * It should be the {@code target/classes/META-INF/MANIFEST.MF} file (or modular equivalent).</p>
+     *
+     * @param  file     an additional manifest file, or {@code null}
+     * @param  content  the content of {@code file}, or a standalone manifest produced at runtime
+     * @return the merged manifest as a new instance if some changes were necessary
+     * @throws IOException if an error occurred while reading a manifest file
+     */
+    Manifest mergeManifest(Path file, Manifest content) throws IOException {
+        if (manifest == null) {
+            manifest = file;
+        } else if (file != null && Files.isSameFile(file, manifest)) {
+            // Nothing to merge because of the constraint that `content` must be the content of `file`.
+        } else {
+            try (InputStream in = Files.newInputStream(manifest)) {
+                // No need to wrap in `BufferedInputStream`.
+                if (content != null) {
+                    content = new Manifest(content);
+                    content.read(in);
+                } else {
+                    content = new Manifest(in);
+                }
+            }
+        }
+        return content;
+    }
+
+    /**
+     * Adds to the given list the arguments to provide to the "jar" tool for each version.
+     * Elements added to the list shall be instances of {@link String} or {@link Path}.
+     * Callers should have added the following options (if applicable) before to invoke this method:
+     *
+     * <ul>
+     *   <li>{@code --create}</li>
+     *   <li>{@code --no-compress}</li>
+     *   <li>{@code --date} followed by the output time stamp</li>
+     *   <li>{@code --module-version} followed by module version</li>
+     *   <li>{@code --hash-modules} followed by patters of module names</li>
+     *   <li>{@code --module-path} followed by module path</li>
+     * </ul>
+     *
+     * This method adds the following options:
+     *
+     * <ul>
+     *   <li>{@code --file} followed by the path to the <abbr>JAR</abbr> file</li>
+     *   <li>{@code --manifest} followed by path to the manifest file</li>
+     *   <li>{@code --main-class} followed by fully qualified name class</li>
+     *   <li>{@code --release} followed by Java target release</li>
+     *   <li>{@code -C} followed by directory</li>
+     *   <li>files or directories to archive</li>
+     * </ul>
+     *
+     * @param addTo the list where to add the arguments as {@link String} or {@link Path} instances

Review Comment:
   Done



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3891958434


##########
src/main/java/org/apache/maven/plugins/jar/DirectoryRole.java:
##########
@@ -0,0 +1,73 @@
+/*
+ * 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.jar;
+
+/**
+ * Directories that the archiver needs to handle in a special way.
+ */
+enum DirectoryRole {
+    /**
+     * The root directory. This is usually {@code "target/classes"}.
+     * The next locations can be {@link #META_INF}, {@link #NAMED_MODULE} or {@link #RESOURCES}.
+     */
+    ROOT,
+
+    /**
+     * The {@code "META-INF"} or {@code "<module>/META-INF"} directory.
+     * This is part of the <abbr>JAR</abbr> specification.
+     * The next locations can be {@link #VERSIONS} or {@link #VERSIONS_MODULAR}.
+     */
+    META_INF,
+
+    /**
+     * The {@code "META-INF/versions"} or {@code "<module>/META-INF/versions"} directory.
+     * This is part of the <abbr>JAR</abbr> specification, except the {@code <module>} prefix.
+     * The sub-directories are named according Java releases such as "21".

Review Comment:
   Done



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3891599580


##########
src/main/java/org/apache/maven/plugins/jar/AbstractJarMojo.java:
##########
@@ -108,13 +105,22 @@ public abstract class AbstractJarMojo implements org.apache.maven.api.plugin.Moj
     @Parameter
     protected MavenArchiveConfiguration archive = new MavenArchiveConfiguration();
 
+    /**
+     * The service to use for attaching the artifacts produced by this plugin.

Review Comment:
   `ProjectManager` is an interface from the `org.apache.maven.api.services` package and extends the `Service` interface. It can be obtained by `Session.getService(Class)`.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#issuecomment-5331743397

   We may not be able to enable reproducible build at all with the `jar` tool at it stands today because the `jar` tool does not seem to be designed for an explicit enumeration of files to include. It seems to be designed for working on directories only, in which case the entry order may depend on the tool or the platform. Reference:
   
   * [Obligation to repeat the -C option for each file](https://github.com/apache/maven-jar-plugin/pull/508/changes/00b5e534619b1e63fdebdc9a3575ac4b23efd614)
   * [Analysis of missing directory entries problem reported on the mailing list](https://lists.apache.org/thread/9rqskbq13xpy1woxxykl7b6f5fmy2ylq)
   
   While I agree that we need a way to verify the integrity of a JAR file, I disagree that every bits must be identical. I think that we should write a tool comparing two JAR files ignoring dates, compression and entry order.


-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3891614804


##########
src/main/java/org/apache/maven/plugins/jar/AbstractJarMojo.java:
##########
@@ -136,18 +142,26 @@ public abstract class AbstractJarMojo implements org.apache.maven.api.plugin.Moj
      * Timestamp for reproducible output archive entries.
      * This is either formatted as ISO 8601 extended offset date-time
      * (e.g. in UTC such as '2011-12-03T10:15:30Z' or with an offset '2019-10-05T20:37:42+06:00'),
-     * or as an integer representing seconds since the epoch
-     * (like <a href="https://reproducible-builds.org/docs/source-date-epoch/">SOURCE_DATE_EPOCH</a>).
+     * or as an integer representing seconds since the Java epoch (January 1st, 1970).
+     * If not configured or disabled,
+     * the <a href="https://reproducible-builds.org/docs/source-date-epoch/">SOURCE_DATE_EPOCH</a>
+     * environment variable is used as a fallback value,
+     * to ease forcing Reproducible Build externally when the build has not enabled it natively in <abbr>POM</abbr>.
+     *
+     * <p>This property is supported only with Java Development Kit (<abbr>JDK</abbr>) version 19 or later.</p>

Review Comment:
   Replacement done as suggested.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3858093521


##########
src/main/java/org/apache/maven/plugins/jar/ExcludedFiles.java:
##########
@@ -0,0 +1,129 @@
+/*
+ * 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.jar;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardCopyOption;
+import java.util.List;
+
+/**
+ * A list of files to temporarily move outside the directory to package in a <abbr>JAR</abbr> archive.
+ * This is used for excluding files from the <abbr>JAR</abbr> archive according include/exclude filters.
+ * We move these files for making possible to specify the whole directory to the {@code jar} tool.
+ * This approach is used instead of enumerating files in arguments given to the {@code jar} tool because
+ * such enumeration can not contain directory entries (otherwise the whole directory would be included).
+ * Some software such as Spring applications component scan relies on the presence of directory entries.
+ */
+final class ExcludedFiles implements Closeable {
+    /**
+     * The paths of files or directories to temporarily move in another directory.
+     */
+    private final Path[] original;
+
+    /**
+     * The paths where files or directories were moved.
+     * For each index <var>i</var>, the original path of {@code moved[i]} was {@code original[i]}.
+     */
+    private final Path[] moved;
+
+    /**
+     * Temporary directory which will contain the {@code moved} files.
+     * It should be a parent directory of {@link #original} files for
+     * increasing the chances that it is on the same file system.
+     */
+    private final Path temporaryDirectory;
+
+    /**
+     * Creates a new list of files to move in a temporary directory.
+     *
+     * @param directory the directory which was scanned for files to include in the <abbr>JAR</abbr>
+     * @param files paths of files or directories to temporarily move in another directory
+     * @throws IOException if an error occurred while creating the temporary directory.
+     */
+    ExcludedFiles(final Path directory, final List<Path> files) throws IOException {
+        original = files.toArray(Path[]::new);
+        moved = new Path[original.length];
+        temporaryDirectory = Files.createTempDirectory(directory, "excluded-");
+    }
+
+    /**
+     * Moves the files now. This method should be invoked inside the "try with resource" block.
+     *
+     * @throws IOException if an error occurred while moving a file.
+     */
+    public void move() throws IOException {
+        for (int i = 0; i < original.length; i++) {
+            final Path source = original[i];
+            String prefix = source.getFileName().toString();
+            String suffix = null;
+            int s = prefix.lastIndexOf('.');
+            if (s > 0) {
+                suffix = prefix.substring(s);
+                prefix = prefix.substring(0, s);
+            }
+            Path target = Files.createTempFile(temporaryDirectory, prefix, suffix);
+            try {
+                moved[i] = Files.move(source, target, StandardCopyOption.REPLACE_EXISTING);

Review Comment:
   Duplicate of [above](https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3857395405).



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3923348734


##########
src/main/java/org/apache/maven/plugins/jar/ExcludedFiles.java:
##########
@@ -0,0 +1,145 @@
+/*
+ * 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.jar;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardCopyOption;
+import java.util.List;
+
+/**
+ * A list of files to temporarily move outside the directory to package in a <abbr>JAR</abbr> archive.
+ * This is used for excluding files from the <abbr>JAR</abbr> archive according to include/exclude filters.
+ * We move these files for making possible to specify the whole directory to the {@code jar} tool.
+ * This approach is used instead of enumerating files in arguments given to the {@code jar} tool because
+ * such enumeration can not contain directory entries (otherwise the whole directory would be included).
+ * Some software such as Spring applications component scan relies on the presence of directory entries.
+ */
+final class ExcludedFiles implements Closeable {
+    /**
+     * The paths of files or directories to temporarily move in another directory.
+     */
+    private final Path[] original;
+
+    /**
+     * The paths where files or directories were moved.
+     * For each index <var>i</var>, the original path of {@code moved[i]} was {@code original[i]}.
+     */
+    private final Path[] moved;
+
+    /**
+     * Temporary directory which will contain the {@code moved} files.
+     * It should be a parent directory of {@link #original} files for
+     * increasing the chances that it is on the same file system.
+     */
+    private final Path temporaryDirectory;
+
+    /**
+     * Index of the first path which is a directory instead of a file.
+     * All paths before this index in the {@link #original} and {@link #moved} arrays are files.
+     * All paths at this index and after this index are directories.
+     */
+    private final int indexOfFirstDirectory;
+
+    /**
+     * Creates a new list of files to move in a temporary directory.
+     *
+     * @param directory the directory which was scanned for files to include in the <abbr>JAR</abbr>
+     * @param excludedFiles paths of files to temporarily move in another directory
+     * @param excludedDirectories paths of directories to temporarily move in another directory
+     * @throws IOException if an error occurred while creating the temporary directory.
+     */
+    ExcludedFiles(Path directory, List<Path> excludedFiles, List<Path> excludedDirectories) throws IOException {
+        indexOfFirstDirectory = excludedFiles.size();
+        final int nd = excludedDirectories.size();

Review Comment:
   Yes. Renamed `numDirs`.



##########
src/main/java/org/apache/maven/plugins/jar/ExcludedFiles.java:
##########
@@ -0,0 +1,145 @@
+/*
+ * 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.jar;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardCopyOption;
+import java.util.List;
+
+/**
+ * A list of files to temporarily move outside the directory to package in a <abbr>JAR</abbr> archive.
+ * This is used for excluding files from the <abbr>JAR</abbr> archive according to include/exclude filters.
+ * We move these files for making possible to specify the whole directory to the {@code jar} tool.
+ * This approach is used instead of enumerating files in arguments given to the {@code jar} tool because
+ * such enumeration can not contain directory entries (otherwise the whole directory would be included).

Review Comment:
   Done.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3921920588


##########
src/main/java/org/apache/maven/plugins/jar/Archive.java:
##########
@@ -0,0 +1,655 @@
+/*
+ * 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.jar;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.TreeMap;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.Type;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.MojoException;
+
+/**
+ * Files or root directories to archive for a single module.
+ * A single instance of {@code Archive} can contain many directories for different target Java releases.
+ * Many instances of {@code Archive} can exist when archiving a multi-modules project.
+ */
+final class Archive {
+    /**
+     * Path to the <abbr>POM</abbr> file generated for this archive, or {@code null} if none.
+     * This is non-null only if module source hierarchy is used, in which case the dependencies
+     * declared in this file are the intersection of the project dependencies and the content of
+     * the {@code module-info.class} file.
+     */
+    @Nullable
+    Path pomFile;
+
+    /**
+     * The <var>JAR</var> file to create. Can be an existing file,
+     * in which case the file creation can be skipped if the file is still up-to-date.
+     */
+    @Nonnull
+    final Path jarFile;
+
+    /**
+     * A helper class for checking whether an existing <abbr>JAR</abbr> file is still up-to-date.
+     * This is null if there is no existing JAR file, or if we determined that the file is outdated.
+     */
+    private TimestampCheck existingJAR;
+
+    /**
+     * Name of the module being archived when the project is using module hierarchy.
+     * This is {@code null} if the project is using package hierarchy, either because it is a classical
+     * class-path project or because it is a single module compiled without using the module hierarchy.
+     * When using module source hierarchy, {@code javac} guarantees that the module name in the output
+     * directory is the name of the parent directory of {@code module-info.class}.
+     */
+    @Nullable
+    final String moduleName;
+
+    /**
+     * Path to {@code META-INF/MANIFEST.MF}, or {@code null} if none.
+     * If non-null, this value will be given to the {@code --manifest} option.
+     * The use of this option is preferable to adding {@code MANIFEST.MF} as an ordinary file.
+     *
+     * @see #setManifest(Path, boolean)
+     * @see #mergeManifest(Path, Manifest)
+     */
+    @Nullable
+    private Path manifest;
+
+    /**
+     * The Maven generated {@code pom.xml} and {@code pom.properties} files, or {@code null} if none.
+     * This first item must be the base directory where the files are located.
+     */
+    @Nullable
+    List<Path> mavenFiles;
+
+    /**
+     * Fully-qualified name of the main class, or {@code null} if none.
+     * This is the value to provide to the {@code --main-class} option.
+     */
+    private String mainClass;
+
+    /**
+     * Files or root directories to store in the <abbr>JAR</abbr> file for each target Java release
+     * other than the base release. Keys are the target Java release with {@code null} for the base
+     * release.
+     */
+    @Nonnull
+    private final NavigableMap<Runtime.Version, FileSet> filesetForRelease;
+
+    /**
+     * Files or root directories to archive for a single target Java release of a single module.
+     * The {@link Archive} enclosing must contain at least one instance of {@code FileSet} for
+     * the base release, and an arbitrary amount of other instances for other target releases.
+     */
+    final class FileSet {
+        /**
+         * The root directory of all files or directories to archive.
+         * This is the value to pass to the {@code -C} tool option.
+         */
+        @Nonnull
+        final Path directory;
+
+        /**
+         * The files or directories to include in the <var>JAR</var> file.
+         * Can be absolute paths or paths relative to {@link #directory}.
+         * It usually contains only the files or directories directly in
+         * the root {@linkplain #directory}, not in sub-directories.
+         */
+        @Nonnull
+        final List<Path> files;
+
+        /**
+         * Creates an initially empty set of files or directories for a specific target Java release.
+         *
+         * @param directory the base directory of the files or directories to archive
+         */
+        private FileSet(Path directory) {
+            this.directory = directory;
+            this.files = new ArrayList<>();
+        }
+
+        /**
+         * 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.
+         * The caller should use that common directory for logging a warning message.
+         *
+         * @param base base directory found by previous invocations of this method, or {@code null} if none
+         * @return common directory of discarded files
+         */
+        private Path discardAllFiles(Path base) {
+            for (Path file : files) {
+                if (base == null) {
+                    base = file.getParent();
+                } else {
+                    while (!file.startsWith(base)) {
+                        base = base.getParent();
+                        if (base == null) {
+                            break;
+                        }
+                    }
+                }
+            }
+            files.clear();
+            return base;
+        }
+
+        /**
+         * Adds the given path to the list of files or directories to archive.
+         * If the given path is a directory, then all children will be included.
+         * Children to exclude, if any, should be managed by {@link ExcludedFiles}.
+         *
+         * @param item a file or directory to archive
+         * @param attributes the file's basic attributes
+         * @param isDirectory whether the file is a directory
+         */
+        void add(Path item, BasicFileAttributes attributes, boolean isDirectory) {
+            TimestampCheck tc = existingJAR;
+            if (tc != null && tc.isUpdated(item, attributes, isDirectory)) {
+                existingJAR = null; // Signal that the existing file is outdated.
+            }
+            files.add(item);
+        }
+
+        /**
+         * Adds to the given list the arguments to provide to the "jar" tool for this version.
+         * The elements added to the list will be instances of {@link String} or {@link Path}.
+         *
+         * <h4>Note about the {@code -C} option</h4>
+         * This method repeats the {@code -C} option before each file.
+         * Our tests suggest that the first file after the directory specified by the {@code -C} option must
+         * be relative to that directory and all files after the first one must be prefixed by the directory
+         * which was specified in the {@code -C} option. This behavior is not very intuitive and replying on
+         * it can be fragile. Furthermore, it seems that the relativized file needs to be the shortest one,
+         * otherwise the {@code jar} tool rejects files after the first one with "names do not match".
+         * Which file is first depends on the unspecified directory-iteration order.
+         * Repeating the {@code -C} option for each file seems safer.
+         *
+         * @param addTo the list to add the arguments as {@link String} or {@link Path} instances to
+         * @param version the target Java release, or {@code null} for the base version of the <abbr>JAR</abbr> file
+         * @throws IllegalArgumentException if a path cannot be made relative to the base directory
+         */
+        private void arguments(List<Object> addTo, Runtime.Version version) {
+            if (files.isEmpty()) {
+                return;
+            }
+            if (version != null) {
+                addTo.add("--release");
+                addTo.add(version);
+            }
+            Path previous = null;
+            for (Path file : files) {
+                if (previous != null && file.startsWith(previous)) {
+                    // Already added a parent directory.
+                    continue;
+                }
+                previous = file;
+                file = directory.relativize(file);
+                if (file.getNameCount() <= 1 && file.toString().isEmpty()) {
+                    /*
+                     * The `-C` directory itself (e.g. a "META-INF/versions/<n>" directory added as a whole).
+                     * An empty file argument is invalid for the `jar` tool (some implementations reject it,
+                     * others silently misbehave), so archive the whole directory content with ".".
+                     */
+                    file = Path.of(".");
+                }
+                addTo.add("-C");
+                addTo.add(directory);
+                addTo.add(file);
+            }
+        }
+
+        /**
+         * {@return a string representation for debugging purposes}
+         */
+        @Override
+        public String toString() {
+            return getClass().getSimpleName() + '[' + directory.getFileName() + ": " + files.size() + " files]";
+        }
+    }
+
+    /**
+     * Creates an initially empty set of files or directories.
+     *
+     * @param jarFile path to the <abbr>JAR</abbr> file to create
+     * @param moduleName the module name if using module hierarchy, or {@code null} if using package hierarchy
+     * @param version the target Java release, or {@code null} for the base version
+     * @param directory the directory of the classes targeting the base Java release
+     * @param forceCreation whether to force a new <abbr>JAR</abbr> file even if the content seems unchanged
+     * @param logger where to send a warning if an error occurred while checking an existing <abbr>JAR</abbr> file
+     */
+    @SuppressWarnings("checkstyle:NeedBraces")
+    Archive(
+            final Path jarFile,
+            final String moduleName,
+            final Runtime.Version version,
+            final Path directory,
+            final boolean forceCreation,
+            final Log logger) {
+        this.jarFile = jarFile;
+        this.moduleName = moduleName;
+        filesetForRelease = new TreeMap<>((v1, v2) -> {
+            if (v1 == v2) return 0;
+            if (v1 == null) return -1;
+            if (v2 == null) return +1;
+            return v1.compareTo(v2);
+        });
+        filesetForRelease.put(version, new FileSet(directory));
+        if (!forceCreation && Files.isRegularFile(jarFile)) {
+            try {
+                existingJAR = new TimestampCheck(jarFile, directory, logger);
+            } catch (IOException e) {
+                // Ignore, we will regenerate the JAR file.
+                logger.warn(e);
+            }
+        }
+    }
+
+    /**
+     * {@return the files or directories to store in the <abbr>JAR</abbr> file for targeting the base Java release}
+     *
+     * @throws NoSuchElementException should not happen unless {@link #prune(boolean)} has been invoked
+     */
+    FileSet baseRelease() {
+        Map.Entry<Runtime.Version, FileSet> entry = filesetForRelease.firstEntry();
+        String message = null;
+        if (entry != null) {
+            Runtime.Version version = entry.getKey();
+            if (version == null) {
+                return entry.getValue();
+            }
+            message = "Expected base version but found version " + version;
+        }
+        throw new NoSuchElementException(message);
+    }
+
+    /**
+     * Returns the {@code module-info.class} files. Conceptually, there is at most once such file per module.
+     * However, more than one file can exist if additional files are provided for additional Java releases.
+     * This method returns only the files that exist.
+     *
+     * @return all {@code module-info.class} files found for all target Java releases
+     */
+    public List<Path> moduleInfoFiles() {
+        var files = new ArrayList<Path>();
+        filesetForRelease.values().forEach((release) -> {
+            Path file = release.directory.resolve(FileCollector.MODULE_DESCRIPTOR_FILE_NAME);
+            if (Files.isRegularFile(file)) {
+                files.add(file);
+            }
+        });
+        return files;
+    }
+
+    /**
+     * Discards all files in this archive, normally because those files are not in any module.
+     * This method returns a common parent directory for all the files that were discarded.
+     * The caller should use that common directory for logging a warning message.
+     *
+     * @return common directory of discarded files, or {@code null} if none
+     */
+    Path discardAllFiles() {
+        Path base = null;
+        for (FileSet release : filesetForRelease.values()) {
+            base = release.discardAllFiles(base);
+        }
+        filesetForRelease.clear();
+        return base;
+    }
+
+    /**
+     * Removes all empty file sets 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}, then this method ensures that at least one file set
+     * remains even if that file set is empty.
+     *
+     * @param skipIfEmpty value of {@link AbstractJarMojo#skipIfEmpty}
+     */
+    public void prune(final boolean skipIfEmpty) {
+        FileSet keep = (skipIfEmpty || isEmpty())
+                ? null
+                : filesetForRelease.firstEntry().getValue();
+        filesetForRelease.values().removeIf((fs) -> fs.files.isEmpty());
+        Iterator<Map.Entry<Runtime.Version, FileSet>> it =
+                filesetForRelease.entrySet().iterator();
+        if (it.hasNext()) {
+            Map.Entry<Runtime.Version, FileSet> first = it.next();
+            if (first.getKey() == null) {
+                return; // Already contains an entry for the base version, nothing to do.
+            }
+            keep = first.getValue();
+            it.remove();
+        }
+        if (keep != null) {
+            filesetForRelease.put(null, keep);
+        }
+    }
+
+    /**
+     * {@return whether this archive has nothing to archive}
+     * This method can return {@code false} even when there is zero file to archive.
+     * It can happen if {@link AbstractJarMojo#skipIfEmpty} is {@code false}. In such case, the
+     * "empty" <abbr>JAR</abbr> file will still contain at {@code META-INF/MANIFEST.MF} file.
+     *
+     * <h4>Prerequisites</h4>
+     * The {@link #prune(boolean)} method should be invoked before this method for accurate result.
+     */
+    public boolean isEmpty() {
+        return filesetForRelease.isEmpty();
+    }
+
+    /**
+     * Checks whether the <abbr>JAR</abbr> file already exists and can be reused.
+     * This method verifies that the <abbr>JAR</abbr> file contains all the files to archive,
+     * contains no extra file, and no file to archive is newer than the <abbr>JAR</abbr> file.
+     *
+     * <p>This method can be invoked only once.
+     * If invoked more often, it returns {@code false} on all subsequent invocations.</p>
+     *
+     * @return whether the <abbr>JAR</abbr> file already exists and can be reused
+     */
+    public boolean isUpToDateJAR() {
+        final TimestampCheck tc = existingJAR;
+        if (tc == null) {
+            return false;
+        }
+        existingJAR = null; // Let GC do its job.
+        return tc.isUpToDateJAR(filesetForRelease.values());
+    }
+
+    /**
+     * Returns an initially empty set of files or directories for the specified target Java release.
+     *
+     * @param directory the base directory of the files to archive
+     * @param version the target Java release, or {@code null} for the base version
+     * @return container where to declare files and directories to archive
+     */
+    FileSet newTargetRelease(Path directory, Runtime.Version version) {
+        return filesetForRelease.computeIfAbsent(version, (key) -> new FileSet(directory));
+    }
+
+    /**
+     * Sets the {@code --main-class} option to the value of the {@code Main-Class} entry of the given manifest.
+     * As an extension, this method accepts the {@code module/classname} syntax (a syntax already used in some
+     * Java tools). If a module is specified, the main class is kept only if the module match. The intent is to
+     * allow users to specify on which module the main class applies when they use plugin configuration.
+     *
+     * <p>This method may modify the {@code content} manifest. Caller must ensure that the given manifest

Review Comment:
   Done.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "gnodet (via GitHub)" <gi...@apache.org>.
gnodet commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3857395405


##########
src/main/java/org/apache/maven/plugins/jar/ExcludedFiles.java:
##########
@@ -0,0 +1,129 @@
+/*
+ * 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.jar;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardCopyOption;
+import java.util.List;
+
+/**
+ * A list of files to temporarily move outside the directory to package in a <abbr>JAR</abbr> archive.
+ * This is used for excluding files from the <abbr>JAR</abbr> archive according include/exclude filters.
+ * We move these files for making possible to specify the whole directory to the {@code jar} tool.
+ * This approach is used instead of enumerating files in arguments given to the {@code jar} tool because
+ * such enumeration can not contain directory entries (otherwise the whole directory would be included).
+ * Some software such as Spring applications component scan relies on the presence of directory entries.
+ */
+final class ExcludedFiles implements Closeable {
+    /**
+     * The paths of files or directories to temporarily move in another directory.
+     */
+    private final Path[] original;
+
+    /**
+     * The paths where files or directories were moved.
+     * For each index <var>i</var>, the original path of {@code moved[i]} was {@code original[i]}.
+     */
+    private final Path[] moved;
+
+    /**
+     * Temporary directory which will contain the {@code moved} files.
+     * It should be a parent directory of {@link #original} files for
+     * increasing the chances that it is on the same file system.
+     */
+    private final Path temporaryDirectory;
+
+    /**
+     * Creates a new list of files to move in a temporary directory.
+     *
+     * @param directory the directory which was scanned for files to include in the <abbr>JAR</abbr>
+     * @param files paths of files or directories to temporarily move in another directory
+     * @throws IOException if an error occurred while creating the temporary directory.
+     */
+    ExcludedFiles(final Path directory, final List<Path> files) throws IOException {
+        original = files.toArray(Path[]::new);
+        moved = new Path[original.length];
+        temporaryDirectory = Files.createTempDirectory(directory, "excluded-");
+    }
+
+    /**
+     * Moves the files now. This method should be invoked inside the "try with resource" block.
+     *
+     * @throws IOException if an error occurred while moving a file.
+     */
+    public void move() throws IOException {
+        for (int i = 0; i < original.length; i++) {
+            final Path source = original[i];
+            String prefix = source.getFileName().toString();
+            String suffix = null;
+            int s = prefix.lastIndexOf('.');
+            if (s > 0) {
+                suffix = prefix.substring(s);
+                prefix = prefix.substring(0, s);
+            }
+            Path target = Files.createTempFile(temporaryDirectory, prefix, suffix);
+            try {
+                moved[i] = Files.move(source, target, StandardCopyOption.REPLACE_EXISTING);

Review Comment:
   **[Important]** `Files.move(source, target, REPLACE_EXISTING)` may fail when `source` is a **directory** and `target` is a regular file (created by `createTempFile` on line 83).
   
   On POSIX systems, `rename(2)` returns `ENOTDIR` when the old path is a directory and the new path is a non-directory. This code path is reachable: `FileCollector.preVisitDirectory()` adds excluded directories to the `exclusion` list (line 252), which are then passed to `ExcludedFiles`.
   
   Concrete scenario — an exclude pattern like `**/internal/**` matching a directory:
   ```
   FileCollector.preVisitDirectory() → exclusion.add(directory)
   → ExcludedFiles.move() → createTempFile (regular file) → Files.move(dir, file) → ENOTDIR
   ```
   
   The current ITs only exclude individual files (`ExcludedByFilter.class`), so this path is untested.
   
   **Suggested fix** — delete the temp file before moving when the source is a directory:
   ```java
   Path target = Files.createTempFile(temporaryDirectory, prefix, suffix);
   if (Files.isDirectory(source)) {
       Files.delete(target); // rename(dir → file) fails on POSIX
   }
   try {
       moved[i] = Files.move(source, target, StandardCopyOption.REPLACE_EXISTING);
   ```
   
   Or alternatively, use `createTempDirectory()` for directory sources.



##########
src/main/java/org/apache/maven/plugins/jar/PomDerivation.java:
##########
@@ -0,0 +1,528 @@
+/*
+ * 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.jar;
+
+import javax.xml.stream.XMLStreamException;
+
+import java.io.BufferedInputStream;
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.UncheckedIOException;
+import java.lang.module.ModuleDescriptor;
+import java.lang.module.ModuleFinder;
+import java.lang.module.ModuleReference;
+import java.net.URI;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.DependencyCoordinates;
+import org.apache.maven.api.JavaPathType;
+import org.apache.maven.api.Session;
+import org.apache.maven.api.Type;
+import org.apache.maven.api.model.Dependency;
+import org.apache.maven.api.model.Model;
+import org.apache.maven.api.model.Parent;
+import org.apache.maven.api.plugin.MojoException;
+import org.apache.maven.api.services.DependencyCoordinatesFactory;
+import org.apache.maven.api.services.DependencyCoordinatesFactoryRequest;
+import org.apache.maven.api.services.DependencyResolver;
+import org.apache.maven.api.services.DependencyResolverRequest;
+import org.apache.maven.api.services.DependencyResolverResult;
+import org.apache.maven.api.services.ModelBuilderException;
+import org.apache.maven.model.v4.MavenStaxWriter;
+
+/**
+ * A mapper from Maven model dependencies to Java module names.
+ * A single instance of this class is created for a Maven project,
+ * then shared by all {@link ForModule} instances (one per module to archive).
+ */
+final class PomDerivation {
+    /**
+     * Whether to expand the list of transitive dependencies in the generated <abbr>POM</abbr>.
+     */
+    private static final boolean EXPAND_TRANSITIVE = false;
+
+    /**
+     * Copy of {@link AbstractJarMojo#session}.
+     */
+    private final Session session;
+
+    /**
+     * The project model, which includes dependencies of all modules.
+     */
+    private final Model projectModel;
+
+    /**
+     * The factory to use for creating temporary {@link DependencyCoordinates} instances.
+     */
+    private final DependencyCoordinatesFactory coordinateFactory;
+
+    /**
+     * Provide module descriptors from module names.
+     * May be {@code null} if no {@code module-info} was found.
+     */
+    private final ModuleFinder moduleFinder;
+
+    /**
+     * Module references from paths to the <abbr>JAR</abbr> file or root directory.
+     */
+    private final Map<URI, ModuleReference> fromURI;
+
+    /**
+     * Module names associated to Maven dependencies.
+     * This map contains {@link DependencyCoordinates#getId()} as keys and module references as values.
+     * This is used for detecting which dependencies are really used according {@code module-info.class}.
+     *
+     * @todo The keys should be instances of {@link DependencyCoordinates}. Unfortunately, as of Maven 4.0.0-rc-5
+     *       that interface does not define the {@code equals} and {@code hashCode} contracts.
+     */
+    private final Map<String, ModuleReference> fromDependency;
+
+    /**
+     * Modules that are built by the project. Keys are module names.
+     */
+    private final Map<String, Dependency> builtModules;
+
+    /**
+     * Creates a new mapper from Maven dependency to module name.
+     *
+     * @param mojo the enclosing <abbr>MOJO</abbr>
+     * @param moduleRoots paths to root directories of each module to archive in a module hierarchy
+     * @throws IOException if an I/O error occurred while fetching dependencies
+     * @throws MavenException if an error occurred while fetching dependencies for a reason other than I/O.
+     */
+    PomDerivation(final AbstractJarMojo mojo, final List<Path> moduleRoots) throws IOException {
+        this.session = mojo.session;
+        projectModel = mojo.project.getModel();
+        coordinateFactory = session.getService(DependencyCoordinatesFactory.class);
+        DependencyResolver resolver = session.getService(DependencyResolver.class);
+        DependencyResolverResult result = resolver.resolve(DependencyResolverRequest.builder()
+                .session(session)
+                .project(mojo.project)
+                .requestType(DependencyResolverRequest.RequestType.RESOLVE)
+                .pathScope(mojo.getDependencyScope())
+                .pathTypeFilter(Set.of(JavaPathType.MODULES, JavaPathType.CLASSES))
+                .build());
+
+        rethrow(result);
+        final Map<org.apache.maven.api.Dependency, Path> dependencies = result.getDependencies();
+        final Path[] allModulePaths = toRealPaths(moduleRoots, dependencies.values());
+        fromURI = new HashMap<>(allModulePaths.length); // TODO: use newHashMap with JDK19.
+        moduleFinder = ModuleFinder.of(allModulePaths);
+        if (moduleFinder != null) {
+            for (ModuleReference reference : moduleFinder.findAll()) {
+                reference.location().ifPresent((location) -> fromURI.put(location, reference));
+            }
+        }
+        fromDependency = new HashMap<>(dependencies.size()); // TODO: use newHashMap with JDK19.
+        for (Map.Entry<org.apache.maven.api.Dependency, Path> entry : dependencies.entrySet()) {
+            Path modulePath = entry.getValue().toRealPath();
+            ModuleReference reference = fromURI.get(modulePath.toUri());
+            if (reference != null) {
+                DependencyCoordinates coordinates = entry.getKey().toCoordinates();
+                String id = coordinates.getId();
+                ModuleReference old = fromDependency.putIfAbsent(id, reference);
+                if (old == null) {
+                    coordinates = withoutVersion(coordinates);
+                    id = coordinates.getId();
+                    old = fromDependency.putIfAbsent(id, reference);
+                }
+                if (old != null && !old.equals(reference)) {
+                    mojo.log.warn("The \"" + id + "\" dependency is declared twice with different module names: \""
+                            + old.descriptor().name() + "\" and \""
+                            + reference.descriptor().name() + "\".");
+                }
+            }
+        }
+        builtModules = new HashMap<>(moduleRoots.size()); // TODO: use newHashMap with JDK19.
+        for (Path root : moduleRoots) {
+            root = root.toRealPath();
+            ModuleDescriptor descriptor = fromURI.get(root.toUri()).descriptor();

Review Comment:
   **[Important]** The `toRealPath()` fix from the previous review is correct, but `fromURI.get(root.toUri())` can still return `null` here — e.g., if `ModuleFinder` could not parse a corrupt `module-info.class`. Calling `.descriptor()` on `null` throws NPE before the null check on line 171 is reached.
   
   **Suggested fix:**
   ```java
   root = root.toRealPath();
   ModuleReference ref = fromURI.get(root.toUri());
   if (ref != null) {
       ModuleDescriptor descriptor = ref.descriptor();
       if (descriptor != null) {
           builtModules.put(
                   descriptor.name(),
                   ...
       }
   }
   ```



##########
src/main/java/org/apache/maven/plugins/jar/ExcludedFiles.java:
##########
@@ -0,0 +1,129 @@
+/*
+ * 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.jar;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardCopyOption;
+import java.util.List;
+
+/**
+ * A list of files to temporarily move outside the directory to package in a <abbr>JAR</abbr> archive.
+ * This is used for excluding files from the <abbr>JAR</abbr> archive according include/exclude filters.
+ * We move these files for making possible to specify the whole directory to the {@code jar} tool.
+ * This approach is used instead of enumerating files in arguments given to the {@code jar} tool because
+ * such enumeration can not contain directory entries (otherwise the whole directory would be included).
+ * Some software such as Spring applications component scan relies on the presence of directory entries.
+ */
+final class ExcludedFiles implements Closeable {
+    /**
+     * The paths of files or directories to temporarily move in another directory.
+     */
+    private final Path[] original;
+
+    /**
+     * The paths where files or directories were moved.
+     * For each index <var>i</var>, the original path of {@code moved[i]} was {@code original[i]}.
+     */
+    private final Path[] moved;
+
+    /**
+     * Temporary directory which will contain the {@code moved} files.
+     * It should be a parent directory of {@link #original} files for
+     * increasing the chances that it is on the same file system.
+     */
+    private final Path temporaryDirectory;
+
+    /**
+     * Creates a new list of files to move in a temporary directory.
+     *
+     * @param directory the directory which was scanned for files to include in the <abbr>JAR</abbr>
+     * @param files paths of files or directories to temporarily move in another directory
+     * @throws IOException if an error occurred while creating the temporary directory.
+     */
+    ExcludedFiles(final Path directory, final List<Path> files) throws IOException {
+        original = files.toArray(Path[]::new);
+        moved = new Path[original.length];
+        temporaryDirectory = Files.createTempDirectory(directory, "excluded-");
+    }
+
+    /**
+     * Moves the files now. This method should be invoked inside the "try with resource" block.
+     *
+     * @throws IOException if an error occurred while moving a file.
+     */
+    public void move() throws IOException {
+        for (int i = 0; i < original.length; i++) {
+            final Path source = original[i];
+            String prefix = source.getFileName().toString();
+            String suffix = null;
+            int s = prefix.lastIndexOf('.');
+            if (s > 0) {
+                suffix = prefix.substring(s);
+                prefix = prefix.substring(0, s);
+            }
+            Path target = Files.createTempFile(temporaryDirectory, prefix, suffix);
+            try {
+                moved[i] = Files.move(source, target, StandardCopyOption.REPLACE_EXISTING);

Review Comment:
   **[Important]** `Files.move(source, target, REPLACE_EXISTING)` may fail when `source` is a **directory** and `target` is a regular file (created by `createTempFile` on line 83).
   
   On POSIX systems, `rename(2)` returns `ENOTDIR` when the old path is a directory and the new path is a non-directory. This code path is reachable: `FileCollector.preVisitDirectory()` adds excluded directories to the `exclusion` list (line 252), which are then passed to `ExcludedFiles`.
   
   Concrete scenario — an exclude pattern like `**/internal/**` matching a directory:
   ```
   FileCollector.preVisitDirectory() → exclusion.add(directory)
   → ExcludedFiles.move() → createTempFile (regular file) → Files.move(dir, file) → ENOTDIR
   ```
   
   The current ITs only exclude individual files (`ExcludedByFilter.class`), so this path is untested.
   
   **Suggested fix** — delete the temp file before moving when the source is a directory:
   ```java
   Path target = Files.createTempFile(temporaryDirectory, prefix, suffix);
   if (Files.isDirectory(source)) {
       Files.delete(target); // rename(dir → file) fails on POSIX
   }
   try {
       moved[i] = Files.move(source, target, StandardCopyOption.REPLACE_EXISTING);
   ```
   
   Or alternatively, use `createTempDirectory()` for directory sources.



##########
src/main/java/org/apache/maven/plugins/jar/PomDerivation.java:
##########
@@ -0,0 +1,528 @@
+/*
+ * 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.jar;
+
+import javax.xml.stream.XMLStreamException;
+
+import java.io.BufferedInputStream;
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.UncheckedIOException;
+import java.lang.module.ModuleDescriptor;
+import java.lang.module.ModuleFinder;
+import java.lang.module.ModuleReference;
+import java.net.URI;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.DependencyCoordinates;
+import org.apache.maven.api.JavaPathType;
+import org.apache.maven.api.Session;
+import org.apache.maven.api.Type;
+import org.apache.maven.api.model.Dependency;
+import org.apache.maven.api.model.Model;
+import org.apache.maven.api.model.Parent;
+import org.apache.maven.api.plugin.MojoException;
+import org.apache.maven.api.services.DependencyCoordinatesFactory;
+import org.apache.maven.api.services.DependencyCoordinatesFactoryRequest;
+import org.apache.maven.api.services.DependencyResolver;
+import org.apache.maven.api.services.DependencyResolverRequest;
+import org.apache.maven.api.services.DependencyResolverResult;
+import org.apache.maven.api.services.ModelBuilderException;
+import org.apache.maven.model.v4.MavenStaxWriter;
+
+/**
+ * A mapper from Maven model dependencies to Java module names.
+ * A single instance of this class is created for a Maven project,
+ * then shared by all {@link ForModule} instances (one per module to archive).
+ */
+final class PomDerivation {
+    /**
+     * Whether to expand the list of transitive dependencies in the generated <abbr>POM</abbr>.
+     */
+    private static final boolean EXPAND_TRANSITIVE = false;
+
+    /**
+     * Copy of {@link AbstractJarMojo#session}.
+     */
+    private final Session session;
+
+    /**
+     * The project model, which includes dependencies of all modules.
+     */
+    private final Model projectModel;
+
+    /**
+     * The factory to use for creating temporary {@link DependencyCoordinates} instances.
+     */
+    private final DependencyCoordinatesFactory coordinateFactory;
+
+    /**
+     * Provide module descriptors from module names.
+     * May be {@code null} if no {@code module-info} was found.
+     */
+    private final ModuleFinder moduleFinder;
+
+    /**
+     * Module references from paths to the <abbr>JAR</abbr> file or root directory.
+     */
+    private final Map<URI, ModuleReference> fromURI;
+
+    /**
+     * Module names associated to Maven dependencies.
+     * This map contains {@link DependencyCoordinates#getId()} as keys and module references as values.
+     * This is used for detecting which dependencies are really used according {@code module-info.class}.
+     *
+     * @todo The keys should be instances of {@link DependencyCoordinates}. Unfortunately, as of Maven 4.0.0-rc-5
+     *       that interface does not define the {@code equals} and {@code hashCode} contracts.
+     */
+    private final Map<String, ModuleReference> fromDependency;
+
+    /**
+     * Modules that are built by the project. Keys are module names.
+     */
+    private final Map<String, Dependency> builtModules;
+
+    /**
+     * Creates a new mapper from Maven dependency to module name.
+     *
+     * @param mojo the enclosing <abbr>MOJO</abbr>
+     * @param moduleRoots paths to root directories of each module to archive in a module hierarchy
+     * @throws IOException if an I/O error occurred while fetching dependencies
+     * @throws MavenException if an error occurred while fetching dependencies for a reason other than I/O.
+     */
+    PomDerivation(final AbstractJarMojo mojo, final List<Path> moduleRoots) throws IOException {
+        this.session = mojo.session;
+        projectModel = mojo.project.getModel();
+        coordinateFactory = session.getService(DependencyCoordinatesFactory.class);
+        DependencyResolver resolver = session.getService(DependencyResolver.class);
+        DependencyResolverResult result = resolver.resolve(DependencyResolverRequest.builder()
+                .session(session)
+                .project(mojo.project)
+                .requestType(DependencyResolverRequest.RequestType.RESOLVE)
+                .pathScope(mojo.getDependencyScope())
+                .pathTypeFilter(Set.of(JavaPathType.MODULES, JavaPathType.CLASSES))
+                .build());
+
+        rethrow(result);
+        final Map<org.apache.maven.api.Dependency, Path> dependencies = result.getDependencies();
+        final Path[] allModulePaths = toRealPaths(moduleRoots, dependencies.values());
+        fromURI = new HashMap<>(allModulePaths.length); // TODO: use newHashMap with JDK19.
+        moduleFinder = ModuleFinder.of(allModulePaths);
+        if (moduleFinder != null) {
+            for (ModuleReference reference : moduleFinder.findAll()) {
+                reference.location().ifPresent((location) -> fromURI.put(location, reference));
+            }
+        }
+        fromDependency = new HashMap<>(dependencies.size()); // TODO: use newHashMap with JDK19.
+        for (Map.Entry<org.apache.maven.api.Dependency, Path> entry : dependencies.entrySet()) {
+            Path modulePath = entry.getValue().toRealPath();
+            ModuleReference reference = fromURI.get(modulePath.toUri());
+            if (reference != null) {
+                DependencyCoordinates coordinates = entry.getKey().toCoordinates();
+                String id = coordinates.getId();
+                ModuleReference old = fromDependency.putIfAbsent(id, reference);
+                if (old == null) {
+                    coordinates = withoutVersion(coordinates);
+                    id = coordinates.getId();
+                    old = fromDependency.putIfAbsent(id, reference);
+                }
+                if (old != null && !old.equals(reference)) {
+                    mojo.log.warn("The \"" + id + "\" dependency is declared twice with different module names: \""
+                            + old.descriptor().name() + "\" and \""
+                            + reference.descriptor().name() + "\".");
+                }
+            }
+        }
+        builtModules = new HashMap<>(moduleRoots.size()); // TODO: use newHashMap with JDK19.
+        for (Path root : moduleRoots) {
+            root = root.toRealPath();
+            ModuleDescriptor descriptor = fromURI.get(root.toUri()).descriptor();

Review Comment:
   **[Important]** The `toRealPath()` fix from the previous review is correct, but `fromURI.get(root.toUri())` can still return `null` here — e.g., if `ModuleFinder` could not parse a corrupt `module-info.class`. Calling `.descriptor()` on `null` throws NPE before the null check on line 171 is reached.
   
   **Suggested fix:**
   ```java
   root = root.toRealPath();
   ModuleReference ref = fromURI.get(root.toUri());
   if (ref != null) {
       ModuleDescriptor descriptor = ref.descriptor();
       if (descriptor != null) {
           builtModules.put(
                   descriptor.name(),
                   ...
       }
   }
   ```



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3858098813


##########
src/main/java/org/apache/maven/plugins/jar/PomDerivation.java:
##########
@@ -0,0 +1,528 @@
+/*
+ * 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.jar;
+
+import javax.xml.stream.XMLStreamException;
+
+import java.io.BufferedInputStream;
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.UncheckedIOException;
+import java.lang.module.ModuleDescriptor;
+import java.lang.module.ModuleFinder;
+import java.lang.module.ModuleReference;
+import java.net.URI;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.DependencyCoordinates;
+import org.apache.maven.api.JavaPathType;
+import org.apache.maven.api.Session;
+import org.apache.maven.api.Type;
+import org.apache.maven.api.model.Dependency;
+import org.apache.maven.api.model.Model;
+import org.apache.maven.api.model.Parent;
+import org.apache.maven.api.plugin.MojoException;
+import org.apache.maven.api.services.DependencyCoordinatesFactory;
+import org.apache.maven.api.services.DependencyCoordinatesFactoryRequest;
+import org.apache.maven.api.services.DependencyResolver;
+import org.apache.maven.api.services.DependencyResolverRequest;
+import org.apache.maven.api.services.DependencyResolverResult;
+import org.apache.maven.api.services.ModelBuilderException;
+import org.apache.maven.model.v4.MavenStaxWriter;
+
+/**
+ * A mapper from Maven model dependencies to Java module names.
+ * A single instance of this class is created for a Maven project,
+ * then shared by all {@link ForModule} instances (one per module to archive).
+ */
+final class PomDerivation {
+    /**
+     * Whether to expand the list of transitive dependencies in the generated <abbr>POM</abbr>.
+     */
+    private static final boolean EXPAND_TRANSITIVE = false;
+
+    /**
+     * Copy of {@link AbstractJarMojo#session}.
+     */
+    private final Session session;
+
+    /**
+     * The project model, which includes dependencies of all modules.
+     */
+    private final Model projectModel;
+
+    /**
+     * The factory to use for creating temporary {@link DependencyCoordinates} instances.
+     */
+    private final DependencyCoordinatesFactory coordinateFactory;
+
+    /**
+     * Provide module descriptors from module names.
+     * May be {@code null} if no {@code module-info} was found.
+     */
+    private final ModuleFinder moduleFinder;
+
+    /**
+     * Module references from paths to the <abbr>JAR</abbr> file or root directory.
+     */
+    private final Map<URI, ModuleReference> fromURI;
+
+    /**
+     * Module names associated to Maven dependencies.
+     * This map contains {@link DependencyCoordinates#getId()} as keys and module references as values.
+     * This is used for detecting which dependencies are really used according {@code module-info.class}.
+     *
+     * @todo The keys should be instances of {@link DependencyCoordinates}. Unfortunately, as of Maven 4.0.0-rc-5
+     *       that interface does not define the {@code equals} and {@code hashCode} contracts.
+     */
+    private final Map<String, ModuleReference> fromDependency;
+
+    /**
+     * Modules that are built by the project. Keys are module names.
+     */
+    private final Map<String, Dependency> builtModules;
+
+    /**
+     * Creates a new mapper from Maven dependency to module name.
+     *
+     * @param mojo the enclosing <abbr>MOJO</abbr>
+     * @param moduleRoots paths to root directories of each module to archive in a module hierarchy
+     * @throws IOException if an I/O error occurred while fetching dependencies
+     * @throws MavenException if an error occurred while fetching dependencies for a reason other than I/O.
+     */
+    PomDerivation(final AbstractJarMojo mojo, final List<Path> moduleRoots) throws IOException {
+        this.session = mojo.session;
+        projectModel = mojo.project.getModel();
+        coordinateFactory = session.getService(DependencyCoordinatesFactory.class);
+        DependencyResolver resolver = session.getService(DependencyResolver.class);
+        DependencyResolverResult result = resolver.resolve(DependencyResolverRequest.builder()
+                .session(session)
+                .project(mojo.project)
+                .requestType(DependencyResolverRequest.RequestType.RESOLVE)
+                .pathScope(mojo.getDependencyScope())
+                .pathTypeFilter(Set.of(JavaPathType.MODULES, JavaPathType.CLASSES))
+                .build());
+
+        rethrow(result);
+        final Map<org.apache.maven.api.Dependency, Path> dependencies = result.getDependencies();
+        final Path[] allModulePaths = toRealPaths(moduleRoots, dependencies.values());
+        fromURI = new HashMap<>(allModulePaths.length); // TODO: use newHashMap with JDK19.
+        moduleFinder = ModuleFinder.of(allModulePaths);
+        if (moduleFinder != null) {
+            for (ModuleReference reference : moduleFinder.findAll()) {
+                reference.location().ifPresent((location) -> fromURI.put(location, reference));
+            }
+        }
+        fromDependency = new HashMap<>(dependencies.size()); // TODO: use newHashMap with JDK19.
+        for (Map.Entry<org.apache.maven.api.Dependency, Path> entry : dependencies.entrySet()) {
+            Path modulePath = entry.getValue().toRealPath();
+            ModuleReference reference = fromURI.get(modulePath.toUri());
+            if (reference != null) {
+                DependencyCoordinates coordinates = entry.getKey().toCoordinates();
+                String id = coordinates.getId();
+                ModuleReference old = fromDependency.putIfAbsent(id, reference);
+                if (old == null) {
+                    coordinates = withoutVersion(coordinates);
+                    id = coordinates.getId();
+                    old = fromDependency.putIfAbsent(id, reference);
+                }
+                if (old != null && !old.equals(reference)) {
+                    mojo.log.warn("The \"" + id + "\" dependency is declared twice with different module names: \""
+                            + old.descriptor().name() + "\" and \""
+                            + reference.descriptor().name() + "\".");
+                }
+            }
+        }
+        builtModules = new HashMap<>(moduleRoots.size()); // TODO: use newHashMap with JDK19.
+        for (Path root : moduleRoots) {
+            root = root.toRealPath();
+            ModuleDescriptor descriptor = fromURI.get(root.toUri()).descriptor();

Review Comment:
   Duplicate of [above](https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3857395421).



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "seregamorph (via GitHub)" <gi...@apache.org>.
seregamorph commented on PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#issuecomment-5314113997

   The `/target` directory does not exist indeed, as there is no src/main that was compiled. Earlier versions of the maven-jar-plugin create an empty JAR (has only manifest).
   
   > We could create the target directory by the plugin. But can we assume that the `data-migration-impl-e2e-test` directory exists? 
   
   IMO, it's okay to create `target` directory by the plugin which outputs there. The `data-migration-impl-e2e-test` is assumed to be existing, as it's a module directory with the `pom.xml`


-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "hboutemy (via GitHub)" <gi...@apache.org>.
hboutemy commented on PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#issuecomment-5324235647

   > Preparing a MANIFEST.MF is the only functionality of MavenArchiver that the new implementation is still using. We could bring that functionality in the plugin, which would remove the dependency to Archiver. But I keep that for a separated discussion later.
   
   there are many other packaging plugins that benefit from Maven Archiver: war, etc... I'm not convinced. But we'll have a deeper discussion if you really still feel this is a good idea


-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "seregamorph (via GitHub)" <gi...@apache.org>.
seregamorph commented on PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#issuecomment-5339152783

   Regarding the target directory creation. The target directory should be only created if the JAR is to be produced. Now the pom assemblies create redundant empty `target` directories


-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "ascheman (via GitHub)" <gi...@apache.org>.
ascheman commented on PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#issuecomment-5344803684

   @seregamorph @desruisseaux @hboutemy
   
   > what I've noticed is that MANIFEST.MF are now having two entries `Manifest-Version: 1.0` / `Created-By: 25.0.3 (Amazon.com Inc.)` while the original MANIFEST had only `Manifest-Version: 1.0`
   
   Confirmed, and it is worth pinning down precisely because it is a **reproducibility** regression, not just a cosmetic one.
   
   **Root cause.** The JDK `jar` tool stamps its own `Created-By: <java.version> (<java.vendor>)` into any manifest that does not already contain one — there is no way to suppress it short of `-M/--no-manifest`. Reproduced in isolation:
   
   | JDK | `jar --create --manifest=<minimal>` yields |
   |-----|--------------------------------------------|
   | Temurin 17.0.18 | `Created-By: 17.0.18 (Eclipse Adoptium)` |
   | Corretto 21.0.10 | `Created-By: 21.0.10 (Amazon.com Inc.)` |
   
   So the same sources produce **different manifest bytes on different JDK distributions** — Corretto's `(Amazon.com Inc.)` matches exactly what you see. With `addDefaultEntries=true` this never surfaces, because Maven archiver supplies a stable `Created-By` (`Maven JAR Plugin <version>`) and the jar tool keeps it. It only bites with `addDefaultEntries=false`, where Maven archiver deliberately omits it and the jar tool fills the gap with its JDK-specific value.
   
   **The decision (and its alternative).** There are two ways to fix it, and they differ in what `addDefaultEntries=false` should mean under the jar tool:
   
   - **(a) Always write a stable, JDK-independent `Created-By`.** Even with `addDefaultEntries=false`, have the plugin set `Created-By: Maven JAR Plugin <version>` (the same value archiver uses with default entries) *before* handing the manifest to the jar tool, so the tool keeps ours. This keeps the artifact reproducible across JDK distributions. Trade-off: the manifest is not literally the `Manifest-Version`-only one you had — it carries a (JDK-independent) `Created-By`.
   - **(b) Truly minimal manifest.** Reproduce the exact pre-4.x output (no `Created-By` at all). Since the jar tool cannot be told to omit it, this needs either `-M/--no-manifest` with the manifest supplied as a regular entry (I verified this yields byte-identical manifests across Temurin and Corretto), or a post-generation manifest rewrite.
   
   I went with **(a)** as a candidate on my branch [`bugfix/508-preserve-directory-entries`](https://github.com/aschemaven/maven-jar-plugin/tree/bugfix/508-preserve-directory-entries) — a small change in `ToolExecutor` plus a `manifest-created-by` integration test that fails if the final `Created-By` is the JDK-specific value. @desruisseaux, cherry-pick, adapt, or drop as you see fit — you may prefer (b) to honor `addDefaultEntries=false` literally.
   
   One nuance for the record: strictly, reproducible builds are defined against a *pinned* build environment (the JDK included), so cross-JDK divergence is not a definitional violation. But Maven's own convention is deliberately JDK-independent manifests (archiver uses `Apache Maven` / `Maven JAR Plugin`, never the JDK string), and there are real practical costs to re-introducing the coupling — e.g. Docker layer dedup across CI runners on different JDK patch/vendor. That is why keeping `Created-By` JDK-independent seems worth it either way.
   


-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3844473279


##########
src/main/java/org/apache/maven/plugins/jar/AbstractJarMojo.java:
##########
@@ -207,167 +205,208 @@ protected final Log getLog() {
     protected abstract String getType();
 
     /**
-     * Returns the JAR file to generate, based on an optional classifier.
+     * {@return the scope of dependencies}
+     * It should be {@link PathScope#MAIN_COMPILE} or {@link PathScope#TEST_COMPILE}.
+     * Note that we use compile scope rather than runtime scope because dependencies
+     * cannot appear in {@code requires} statement if they didn't had compile scope.
+     */
+    protected abstract PathScope getDependencyScope();
+
+    /**
+     * {@return the JAR tool to use for archiving the code}
      *
-     * @param basedir the output directory
-     * @param resultFinalName the name of the JAR file
-     * @param classifier an optional classifier
-     * @return the file to generate
+     * @throws MojoException if no JAR tool was found
+     *
+     * @since 4.0.0-beta-2
      */
-    protected Path getJarFile(Path basedir, String resultFinalName, String classifier) {
-        Objects.requireNonNull(basedir, "basedir is not allowed to be null");
-        Objects.requireNonNull(resultFinalName, "finalName is not allowed to be null");
-        String fileName = resultFinalName + (hasClassifier(classifier) ? '-' + classifier : "") + ".jar";
-        return basedir.resolve(fileName);
+    protected ToolProvider getJarTool() throws MojoException {
+        return ToolProvider.findFirst(toolId).orElseThrow(() -> new MojoException("No such \"" + toolId + "\" tool."));
     }
 
     /**
-     * Generates the JAR.
+     * Returns the output time stamp or, as a fallback, the {@code SOURCE_DATE_EPOCH} environment variable.
+     * If the time stamp is expressed in seconds, it is converted to ISO 8601 format. Otherwise it is returned as-is.
      *
-     * @return the path to the created archive file
-     * @throws MojoException in case of an error
+     * @return the time stamp in presumed ISO 8601 format, or {@code null} if none
+     *
+     * @since 4.0.0-beta-2
      */
-    public Path createArchive() throws MojoException {
-        Path basedir = outputDirectory != null
-                ? outputDirectory
-                : Path.of(project.getBuild().getDirectory());
-        String resultFinalName =
-                finalName != null ? finalName : project.getBuild().getFinalName();
-        Path jarFile = getJarFile(basedir, resultFinalName, getClassifier());
-
-        FileSetManager fileSetManager = new FileSetManager();
-        FileSet jarContentFileSet = new FileSet();
-        jarContentFileSet.setDirectory(getClassesDirectory().toAbsolutePath().toString());
-        jarContentFileSet.setIncludes(Arrays.asList(getIncludes()));
-        jarContentFileSet.setExcludes(Arrays.asList(getExcludes()));
-
-        String[] includedFiles = fileSetManager.getIncludedFiles(jarContentFileSet);
-
-        if (detectMultiReleaseJar
-                && Arrays.stream(includedFiles)
-                        .anyMatch(
-                                p -> p.startsWith("META-INF" + File.separatorChar + "versions" + File.separatorChar))) {
-            getLog().debug("Adding 'Multi-Release: true' manifest entry.");
-            archive.addManifestEntry(Attributes.Name.MULTI_RELEASE.toString(), "true");
+    protected String getOutputTimestamp() {
+        String time = nullIfAbsent(outputTimestamp);
+        if (time == null) {
+            time = nullIfAbsent(System.getenv("SOURCE_DATE_EPOCH"));
+            if (time == null) {
+                return null;
+            }
         }
+        if (Runtime.version().feature() < ToolExecutor.JDK_SUPPORT_DATE) {
+            log.warn("Reproducible build requires Java " + ToolExecutor.JDK_SUPPORT_DATE + " or later.");

Review Comment:
   Actually reproducible builds are never explicitly requested. We only infer that requirement from whether a value has been specified to the `outputTimestamp` property. By relaxing the coupling between whether reproducible builds is requested and whether the `--date` option is supported, we can address some of the issues.
   
   For the last remaining issue, when `--date` is not supported, we tried to replace the warning by an exception. But because `outputTimestamp` is defined in the super-POM since Maven 4,0.0, it causes all builds to fail by default on Java 17/18. It is not so easy to opt-out, as clearing the ` outputTimestamp` causes exceptions to be thrown in some combinations of Maven core and Maven Compiler Plugins 3.x, and users wanting reproducible builds on a "best effort" basis have to setup profiles.
   
   In the case of Maven JAR plugin, this proposal causes many integration tests to fail, even with opt-out. I think that throwing an exception here causes more difficulties than benefits.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3892035505


##########
src/main/java/org/apache/maven/plugins/jar/FileCollector.java:
##########
@@ -0,0 +1,496 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.PathMatcher;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayDeque;
+import java.util.Deque;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.services.PathMatcherFactory;
+
+/**
+ * Dispatch the files in the output directory into the <abbr>JAR</abbr> files to create.
+ * Instead of just archiving as-is the content of the output directory, this class separates
+ * the following subdirectories to the options listed below:
+ *
+ * <ul>
+ *   <li>The {@code META-INF/MANIFEST.MF} file will be given to the {@code --manifest} option.</li>
+ *   <li>Files in the following directories will be given to the {@code --release} option:
+ *     <ul>
+ *       <li>{@code META-INF/versions/}</li>
+ *       <li>{@code META-INF/versions-modular/<module>/}</li>
+ *       <li>{@code <module>/META-INF/versions/}</li>
+ *     </ul>
+ *   </li>
+ * </ul>
+ *
+ * The reason for using the options is that they allow the {@code jar} tool to perform additional verifications.
+ * For example, when using the {@code --release} option, {@code jar} verifies the <abbr>API</abbr> compatibility.
+ */
+final class FileCollector extends SimpleFileVisitor<Path> {
+    /**
+     * The file to check for deciding whether the <abbr>JAR</abbr> is modular.
+     */
+    static final String MODULE_DESCRIPTOR_FILE_NAME = "module-info.class";
+
+    /**
+     * The {@value} directory.
+     * This is part of <abbr>JAR</abbr> file specification.
+     */
+    private static final String VERSIONS = "versions";
+
+    /**
+     * The {@value} directory.
+     * This is Maven-specific.
+     */
+    private static final String VERSIONS_MODULAR = "versions-modular";
+
+    /**
+     * Context (logger, configuration) in which the <abbr>JAR</abbr> file are created.
+     */
+    private final ToolExecutor context;
+
+    /**
+     * Whether to detect multi-release <abbr>JAR</abbr> files.
+     * The default value is {@code true}.
+     *
+     * @see AbstractJarMojo#detectMultiReleaseJar
+     */
+    private final boolean detectMultiReleaseJar;
+
+    /**
+     * Combination of includes and excludes path matcher applied on files.
+     */
+    @Nonnull
+    private final PathMatcher fileMatcher;
+
+    /**
+     * Combination of includes and excludes path matcher applied on directories.
+     */
+    @Nonnull
+    private final PathMatcher directoryMatcher;
+
+    /**
+     * Whether the matchers accept all files and there is no need to sort the files.
+     * In such case, we can declare whole directories to the {@code jar} tool instead
+     * of scanning the directory tree ourselves.
+     */
+    private final boolean addDirectories;
+
+    /**
+     * Files found in the output directory when package hierarchy is used.
+     * At most one of {@code packageHierarchy} and {@link #moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Archive packageHierarchy;
+
+    /**
+     * Files found in the output directory when module hierarchy is used. Keys are module names.
+     * At most one of {@link #packageHierarchy} and {@code moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Map<String, Archive> moduleHierarchy;
+
+    /**
+     * The current module being archived. This field is updated every times that {@code FileCollector}
+     * enters in a new module directory.
+     */
+    @Nonnull
+    private Archive currentModule;
+
+    /**
+     * The module and target Java release currently being scanned. This field is updated every times that
+     * {@code FileCollector} enters in a new module directory or in a new target Java release for a given module.
+     */
+    @Nonnull
+    private Archive.FileSet currentFilesToArchive;
+
+    /**
+     * The current target Java release, or {@code null} if none.
+     */
+    @Nullable
+    private Runtime.Version currentTargetVersion;
+
+    /**
+     * Identification of the kinds of directories being traversed.
+     * The length of this list is the depth in the directory hierarchy.
+     * The last element identifies the type of the current directory.
+     */
+    private final Deque<DirectoryRole> directoryRoles;
+
+    /**
+     * Whether to check when a file is the {@code MANIFEST.MF} file.
+     * This is allowed only when scanning the content of a {@code META-INF} directory.
+     */
+    private boolean checkForManifest;
+
+    /**
+     * Creates a new file collector.
+     *
+     * @param mojo the <abbr>MOJO</abbr> from which to get the configuration
+     * @param context context (logger, configuration) in which the <abbr>JAR</abbr> file are created
+     * @param directory the base directory of the files to archive
+     */
+    FileCollector(AbstractJarMojo mojo, ToolExecutor context, Path directory, PathMatcherFactory matcherFactory) {
+        this.context = context;
+        detectMultiReleaseJar = mojo.detectMultiReleaseJar;
+        directoryRoles = new ArrayDeque<>();
+        fileMatcher = matcherFactory.createPathMatcher(directory, mojo.getIncludes(), mojo.getExcludes(), false);
+        directoryMatcher = matcherFactory.deriveDirectoryMatcher(fileMatcher);
+        addDirectories = !context.isReproducible()
+                && matcherFactory.isIncludesAll(fileMatcher)
+                && matcherFactory.isIncludesAll(directoryMatcher);
+        packageHierarchy = context.newArchive(null, null, directory);
+        moduleHierarchy = new LinkedHashMap<>();
+        resetToPackageHierarchy();
+    }
+
+    /**
+     * Resets this {@code FileCollector} to the state where a package hierarchy is presumed.
+     */
+    private void resetToPackageHierarchy() {
+        currentModule = packageHierarchy;
+        currentFilesToArchive = currentModule.baseRelease();
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a module.
+     * For an output generated by {@code javac} from a module source hierarchy,
+     * the directory name is guaranteed to be the module name.
+     *
+     * @param directory a {@code "<module>"} or {@code "META-INF/versions-modular/<module>"} directory
+     */
+    private void enterModuleDirectory(final Path directory) {
+        String moduleName = directory.getFileName().toString();
+        currentModule = moduleHierarchy.computeIfAbsent(
+                moduleName, (name) -> context.newArchive(name, currentTargetVersion, directory));
+        currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a target Java version.
+     * The {@code useDirectly} argument tells whether the content of this directory will be specified directly
+     * as the content to add in the <abbr>JAR</abbr> file. This argument should be {@code false} when there is
+     * another directory level (the module names) to process before to add content.
+     *
+     * @param directory a {@code "META-INF/versions/<n>"} or {@code "META-INF/versions-modular/<n>"} directory
+     * @param useDirectly whether the directory is {@code "META-INF/versions/<n>"}
+     * @return whether to skip the directory because of invalid version number
+     */
+    private boolean enterVersionDirectory(final Path directory, final boolean useDirectly) {
+        try {
+            currentTargetVersion = Runtime.Version.parse(directory.getFileName().toString());
+        } catch (IllegalArgumentException e) {
+            context.warnInvalidVersion(directory, e);
+            return true;
+        }
+        if (useDirectly) {
+            currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+        }
+        return false;
+    }
+
+    /**
+     * Determines if the given directory should be scanned for files to archive.
+     * This method may also update {@link #currentFilesToArchive} if it detects
+     * that we are entering in a new module or a new target Java release.
+     *
+     * @param directory the directory which will be traversed
+     * @param attributes the directory's basic attributes
+     */
+    @Override
+    @SuppressWarnings("checkstyle:MissingSwitchDefault")
+    public FileVisitResult preVisitDirectory(final Path directory, final BasicFileAttributes attributes)
+            throws IOException {
+        DirectoryRole role;
+        if (directoryRoles.isEmpty()) {
+            role = DirectoryRole.ROOT;
+        } else {
+            if (!directoryMatcher.matches(directory)) {
+                return FileVisitResult.SKIP_SUBTREE;
+            }
+            checkForManifest = false;
+            role = directoryRoles.getLast();
+            switch (role) {
+                case ROOT:
+                    /*
+                     * Entering in any subdirectory of `target/classes` (or other directory to archive).
+                     * We need to handle `META-INF` and modules in a special way, and archive the rest.
+                     */
+                    if (directory.endsWith(MetadataFiles.META_INF)) {
+                        role = DirectoryRole.META_INF;
+                        checkForManifest = true;
+                    } else if (Files.isRegularFile(directory.resolve(MODULE_DESCRIPTOR_FILE_NAME))) {
+                        role = DirectoryRole.NAMED_MODULE;
+                        enterModuleDirectory(directory);
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case META_INF:
+                    /*
+                     * Entering in a subdirectory of `META-INF` or `<module>/META-INF`. We will need to handle
+                     * `MANIFEST.MF`, `versions` and `versions-modular` in a special way, and archive the rest.
+                     */
+                    if (detectMultiReleaseJar && directory.endsWith(VERSIONS)) {
+                        role = DirectoryRole.VERSIONS;
+                    } else if (directory.endsWith(VERSIONS_MODULAR)) {
+                        if (!detectMultiReleaseJar) {
+                            // Used asked for no multi-release JAR.
+                            return FileVisitResult.SKIP_SUBTREE;
+                        }
+                        role = DirectoryRole.VERSIONS_MODULAR;
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case VERSIONS:
+                    /*
+                     * Entering in a `META-INF/versions/<n>/` directory for a specific target Java release.
+                     * May also be a `<module>/META-INF/versions/<n>/` directory, even if the latter is not
+                     * the layout generated by Maven Compiler Plugin.
+                     */
+                    if (enterVersionDirectory(directory, true)) {
+                        // An error occurred while parsing the version number.
+                        return FileVisitResult.SKIP_SUBTREE;
+                    }
+                    role = DirectoryRole.RESOURCES;
+                    break;
+
+                case VERSIONS_MODULAR:
+                    /*
+                     * Entering in a `META-INF/versions-modular/<n>/` directory for a specific target Java release.
+                     * That directory contains all modules for the version.
+                     */
+                    resetToPackageHierarchy(); // No module in particular yet.
+                    if (enterVersionDirectory(directory, false)) {
+                        // An error occurred while parsing the version number.
+                        return FileVisitResult.SKIP_SUBTREE;
+                    }
+                    role = DirectoryRole.MODULES;
+                    break;
+
+                case MODULES:
+                    /*
+                     * Entering in a `META-INF/versions-modular/<n>/<module>` directory.
+                     */
+                    enterModuleDirectory(directory);
+                    role = DirectoryRole.NAMED_MODULE;
+                    break;
+
+                case NAMED_MODULE:
+                    /*
+                     * Entering in a `<module>` or `META-INF/versions-modular/<n>/<module>` subdirectory.
+                     * A module could have its own `META-INF` subdirectory, so we need to check again.
+                     */
+                    if (directory.endsWith(MetadataFiles.META_INF)) {
+                        role = DirectoryRole.META_INF;
+                        checkForManifest = true;
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+            }
+        }
+        /*
+         * Do not move this condition inside the `switch` block because `role` may have been modified.
+         * The `role` value is now the role of `directory`, not anymore the role of parent directory.
+         */
+        if (addDirectories && role == DirectoryRole.RESOURCES) {
+            currentFilesToArchive.add(directory, attributes, true);
+            /*
+             * Since we are skipping the whole directory, `postVisitDirectory(…)` will not be invoked.
+             * We must reset `currentFilesToArchive` and `currentTargetVersion` by an explicit call.
+             * This is important mostly after we added a whole `META-INF/versions/<n>` directory,
+             * otherwise base files visited afterwards (directory iteration order is unspecified)
+             * would be added to this version's file set instead of the base release.
+             */
+            resetToParentDirectoryState();
+            return FileVisitResult.SKIP_SUBTREE;
+        } else {
+            directoryRoles.addLast(role);
+            return FileVisitResult.CONTINUE;
+        }
+    }
+
+    /**
+     * Updates the {@code FileCollector} state after we finished to scan the content of a directory.
+     * The fields to update depend on which directory has been visited (module, version, <i>etc.</i>).
+     *
+     * @param directory the directory which has been traversed
+     * @param error the error that occurred while traversing the directory, or {@code null} if none
+     */
+    @Override
+    public FileVisitResult postVisitDirectory(final Path directory, final IOException error) throws IOException {
+        if (error != null) {
+            throw error;
+        }
+        switch (directoryRoles.removeLast()) {
+            case NAMED_MODULE:
+                // Exited the directory of a single module.
+                resetToPackageHierarchy();
+                break;
+
+            case ROOT:
+                break;
+
+            default:
+                resetToParentDirectoryState();
+        }
+        return FileVisitResult.CONTINUE;
+    }
+
+    /**
+     * Updates {@code FileCollector} to a state suitable to the parent of the directory that we finished to scan.
+     * Contrarily to {@link #postVisitDirectory(Path, IOException)}, this method expects the last element of
+     * {@link #directoryRoles} to describe the parent directory, not the directory that we finished to visit.
+     */
+    @SuppressWarnings("checkstyle:MissingSwitchDefault")
+    private void resetToParentDirectoryState() {
+        switch (directoryRoles.getLast()) {
+            case VERSIONS:
+            case VERSIONS_MODULAR:
+                // Exited the directory for one target Java release.
+                currentFilesToArchive = currentModule.baseRelease();
+                currentTargetVersion = null;
+                break;
+
+            case META_INF:
+                checkForManifest = true;
+                break;
+        }
+    }
+
+    /**
+     * Archives a single file if accepted by the matcher.
+     *
+     * @param file the file
+     * @param attributes the file's basic attributes
+     */
+    @Override
+    public FileVisitResult visitFile(final Path file, final BasicFileAttributes attributes) {
+        if (fileMatcher.matches(file)) {
+            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.add(file, attributes, false);
+            }
+        }
+        return FileVisitResult.CONTINUE;
+    }
+
+    /**
+     * 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}, then this method ensures that at least one archive
+     * remains even if that archive is empty.
+     *
+     * @param skipIfEmpty value of {@link AbstractJarMojo#skipIfEmpty}
+     */
+    public void prune(boolean skipIfEmpty) {
+        boolean isModuleHierarchy = !moduleHierarchy.isEmpty();
+        moduleHierarchy.values().forEach((archive) -> archive.prune(skipIfEmpty));
+        moduleHierarchy.values().removeIf(Archive::isEmpty);
+        packageHierarchy.prune(isModuleHierarchy || skipIfEmpty);
+    }
+
+    /**
+     * Moves, copies or ignores orphan files.
+     * An orphan file is a file which is not in any module when module hierarchy is used.
+     * For example, some Maven plugins may create files such as {@code META-INF/LICENSE},
+     * {@code META-INF/NOTICE} or {@code META-INF/DEPENDENCIES}. These files are not in
+     * the correct directory (they should be in a {@code "<module>/META-INF"} directory)
+     * because the plugin may not be aware of module hierarchy.
+     *
+     * <p>A possible strategy could be to copy the {@code LICENSE} and {@code NOTICE} files
+     * in each module, and ignore the {@code DEPENDENCIES} file because its content is not
+     * correct for a module. For now, we just log a warning an ignore.</p>
+     *
+     * <h4>Prerequisites</h4>
+     * The {@link #prune(boolean)} method should have been invoked once before to invoke this method.
+     *
+     * @return if this method ignored some files, the root directory of those files
+     */
+    Path handleOrphanFiles() {
+        if (moduleHierarchy.isEmpty() || packageHierarchy.isEmpty()) {
+            // Classpath project or module-project without orphan files. Nothing to do.
+            return null;
+        }
+        // TODO: we may want to copy LICENSE and NOTICE files here.
+        return packageHierarchy.discardAllFiles();
+    }
+
+    /**
+     * Writes all <abbr>JAR</abbr> files.
+     * If the project is multi-module, then this method returns the path to the generated parent <abbr>POM</abbr> file.
+     *
+     * <h4>Prerequisites</h4>
+     * The {@link #prune(boolean)} method should have been invoked once before to invoke this method.
+     *
+     * @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
+     * @throws IOException if an error occurred while reading or writing a manifest file
+     */
+    Path writeAllJARs(final ToolExecutor executor) throws IOException {
+        for (Archive module : moduleHierarchy.values()) {
+            executor.writeSingleJAR(this, module);
+        }
+        if (executor.pomDerivation != null) {
+            return executor.pomDerivation.writeParentPOM(packageHierarchy);
+        }
+        if (!packageHierarchy.isEmpty()) {
+            executor.writeSingleJAR(this, packageHierarchy);
+        }
+        return null;
+    }
+
+    /**
+     * {@return the paths to all root directories of modules in a module hierarchy}
+     * They are usually {@code target/classes/<module>} directories, but could also
+     * be sub-directories in the {@code META-INF/modular-versions/<n>/} directory.
+     * If the project does not use module hierarchy, then this method returns an empty list.
+     *
+     * <h4>Ignored package hierarchy</h4>
+     * Note that an empty list does not necessarily means that the <abbr>JAR</abbr> is not modular,
+     * as a modular <abbr>JAR</abbr> can also be built from package hierarchy. But we intentionally
+     * ignore the latter case because this method is used for deriving <abbr>POM</abbr> files, and
+     * we do not perform such derivation for projects organized in the classical Maven 3 way.

Review Comment:
   Done



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3891858555


##########
src/main/java/org/apache/maven/plugins/jar/AbstractJarMojo.java:
##########
@@ -207,167 +205,208 @@ protected final Log getLog() {
     protected abstract String getType();
 
     /**
-     * Returns the JAR file to generate, based on an optional classifier.
+     * {@return the scope of dependencies}
+     * It should be {@link PathScope#MAIN_COMPILE} or {@link PathScope#TEST_COMPILE}.
+     * Note that we use compile scope rather than runtime scope because dependencies
+     * cannot appear in {@code requires} statement if they didn't had compile scope.
+     */
+    protected abstract PathScope getDependencyScope();
+
+    /**
+     * {@return the JAR tool to use for archiving the code}
      *
-     * @param basedir the output directory
-     * @param resultFinalName the name of the JAR file
-     * @param classifier an optional classifier
-     * @return the file to generate
+     * @throws MojoException if no JAR tool was found
+     *
+     * @since 4.0.0-beta-2
      */
-    protected Path getJarFile(Path basedir, String resultFinalName, String classifier) {
-        Objects.requireNonNull(basedir, "basedir is not allowed to be null");
-        Objects.requireNonNull(resultFinalName, "finalName is not allowed to be null");
-        String fileName = resultFinalName + (hasClassifier(classifier) ? '-' + classifier : "") + ".jar";
-        return basedir.resolve(fileName);
+    protected ToolProvider getJarTool() throws MojoException {
+        return ToolProvider.findFirst(toolId).orElseThrow(() -> new MojoException("No such \"" + toolId + "\" tool."));
     }
 
     /**
-     * Generates the JAR.
+     * Returns the output time stamp or, as a fallback, the {@code SOURCE_DATE_EPOCH} environment variable.
+     * If the time stamp is expressed in seconds, it is converted to ISO 8601 format. Otherwise it is returned as-is.
      *
-     * @return the path to the created archive file
-     * @throws MojoException in case of an error
+     * @return the time stamp in presumed ISO 8601 format, or {@code null} if none
+     *
+     * @since 4.0.0-beta-2
      */
-    public Path createArchive() throws MojoException {
-        Path basedir = outputDirectory != null
-                ? outputDirectory
-                : Path.of(project.getBuild().getDirectory());
-        String resultFinalName =
-                finalName != null ? finalName : project.getBuild().getFinalName();
-        Path jarFile = getJarFile(basedir, resultFinalName, getClassifier());
-
-        FileSetManager fileSetManager = new FileSetManager();
-        FileSet jarContentFileSet = new FileSet();
-        jarContentFileSet.setDirectory(getClassesDirectory().toAbsolutePath().toString());
-        jarContentFileSet.setIncludes(Arrays.asList(getIncludes()));
-        jarContentFileSet.setExcludes(Arrays.asList(getExcludes()));
-
-        String[] includedFiles = fileSetManager.getIncludedFiles(jarContentFileSet);
-
-        if (detectMultiReleaseJar
-                && Arrays.stream(includedFiles)
-                        .anyMatch(
-                                p -> p.startsWith("META-INF" + File.separatorChar + "versions" + File.separatorChar))) {
-            getLog().debug("Adding 'Multi-Release: true' manifest entry.");
-            archive.addManifestEntry(Attributes.Name.MULTI_RELEASE.toString(), "true");
+    protected String getOutputTimestamp() {
+        String time = nullIfAbsent(outputTimestamp);
+        if (time == null) {
+            time = nullIfAbsent(System.getenv("SOURCE_DATE_EPOCH"));
+            if (time == null) {
+                return null;
+            }
         }
+        if (Runtime.version().feature() < ToolExecutor.JDK_SUPPORT_DATE) {
+            log.warn("Reproducible build requires Java " + ToolExecutor.JDK_SUPPORT_DATE + " or later.");
+            return null;
+        }
+        for (int i = time.length(); --i >= 0; ) {
+            char c = time.charAt(i);
+            if ((c < '0' || c > '9') && (i != 0 || c != '-')) {
+                return time;
+            }
+        }
+        return Instant.ofEpochSecond(Long.parseLong(time)).toString();
+    }
 
-        // May give false positives if the files is named as module descriptor
-        // but is not in the root of the archive or in the versioned area
-        // (and hence not actually a module descriptor).
-        // That is fine since the modular Jar archiver will gracefully
-        // handle such case.
-        // And also such case is unlikely to happen as file ending
-        // with "module-info.class" is unlikely to be included in Jar file
-        // unless it is a module descriptor.
-        boolean containsModuleDescriptor =
-                Arrays.stream(includedFiles).anyMatch(p -> p.endsWith(MODULE_DESCRIPTOR_FILE_NAME));
-
-        String archiverName = containsModuleDescriptor ? "mjar" : "jar";
+    /**
+     * {@return the patterns of files to include, or an empty list if no include pattern was specified}
+     */
+    protected List<String> getIncludes() {
+        return asList(includes);
+    }
 
-        MavenArchiver archiver = new MavenArchiver();
-        archiver.setCreatedBy("Maven JAR Plugin", "org.apache.maven.plugins", "maven-jar-plugin");
-        archiver.setBuildJdkSpecDefaultEntry(archive.getManifest().isAddBuildEnvironmentEntries());
-        archiver.setArchiver((JarArchiver) archivers.get(archiverName));
-        archiver.setOutputFile(jarFile.toFile());
+    /**
+     * {@return the patterns of files to exclude, or an empty list if no exclude pattern was specified}
+     */
+    protected List<String> getExcludes() {
+        return asList(excludes);
+    }
 
-        // configure for Reproducible Builds based on outputTimestamp value
-        archiver.configureReproducibleBuild(outputTimestamp);
+    /**
+     * Returns the output directory and ensures that the directory exists.
+     * The returned directory will be either {@link #outputDirectory} if non-null,
+     * or {@link org.apache.maven.api.model.Build#getDirectory()} otherwise.
+     *
+     * <p>The directory is usually {@code target} and should always exist since it is usually the output
+     * of the compiler plugin. If nevertheless the directory does not exist, then this method creates it.
+     * However, this method does not try to create the parent directory, which should be the Maven sub-project.</p>
+     *
+     * @return the directory containing the generated <abbr>JAR</abbr> files.
+     * @throws IOException if the output directory did not existed and could not be created

Review Comment:
   Done.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3892127127


##########
src/main/java/org/apache/maven/plugins/jar/TimestampCheck.java:
##########
@@ -0,0 +1,237 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.nio.file.attribute.FileTime;
+import java.util.Collection;
+import java.util.Enumeration;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+
+import org.apache.maven.api.plugin.Log;
+
+/**
+ * Checks file timestamps in order to determine if anything changed compared to an existing <abbr>JAR</abbr> file.
+ * This class may scan directories, but only if they have not already been visited by {@link FileCollector}.
+ * Note that the latter can occur only if {@link FileCollector} has no {@code PathMatcher}.
+ * Therefore, this class uses no {@code PathMatcher} neither.
+ *
+ * <h2>Ignore files</h2>
+ * The {@code META-INF/MANIFEST.MF} file and the {@code META-INF/maven/} directory are ignored.
+ * See {@link #isIgnored(Path)} for the rational.
+ */
+final class TimestampCheck extends SimpleFileVisitor<Path> {
+    /**
+     * The base directory of archived files.
+     */
+    private final Path classesDir;
+
+    /**
+     * Path to the existing <abbr>JAR</abbr> file.
+     */
+    private final Path jarFile;
+
+    /**
+     * The last modified time of the <abbr>JAR</abbr> file.
+     */
+    private final FileTime jarFileTime;
+
+    /**
+     * Where to send non-fatal error messages.
+     */
+    private final Log logger;
+
+    /**
+     * Entries of the <abbr>JAR</abbr> file. Note that getting elements from this enumeration can be costly.
+     * Therefore, we do not fetch all elements in advance but only when needed.
+     */
+    private Enumeration<? extends ZipEntry> entries;
+
+    /**
+     * Files found in the <abbr>JAR</abbr> file but not yet traversed by the file visitor.
+     * Files are added lazily only when needed, and removed as soon as they have been traversed.
+     * Path are absolute (resolved with {@link #classesDir}).
+     */
+    private final Set<Path> filesInJAR;
+
+    /**
+     * Some of the files in the build directory. This list contains only the files for which we have already
+     * verified the timestamp. We store them in a separated list for avoiding to check the timestamp twice.
+     * We need this list because we still need to verify if the files are in the {@link #jarFile}.
+     */
+    private final Set<Path> filesInBuild;
+
+    /**
+     * Whether at least one file is more recent than the <abbr>JAR</abbr> file.
+     * The scan of files will stop quickly after this flag become {@code true}.
+     */
+    private boolean hasUpdates;
+
+    /**
+     * Creates a new visitor for checking the validity of a <abbr>JAR</abbr> file.
+     *
+     * @param jarFile the existing <abbr>JAR</abbr> file
+     * @param jarFileTime the last modified time of the <abbr>JAR</abbr> file
+     * @param classesDir base directory of archived files
+     * @param logger where to send a warning if an error occurred while checking an existing <abbr>JAR</abbr> file
+     * @throws IOException if an error occurred while fetching the <abbr>JAR</abbr> file modification time
+     */
+    TimestampCheck(final Path jarFile, final Path classesDir, final Log logger) throws IOException {
+        this.classesDir = classesDir;
+        this.jarFile = jarFile;
+        this.logger = logger;
+        jarFileTime = Files.getLastModifiedTime(jarFile);
+        filesInJAR = new HashSet<>();
+        filesInBuild = new HashSet<>();
+    }
+
+    /**
+     * Returns {@code true} if the given file is more recent that the <abbr>JAR</abbr> file.
+     *
+     * @param file the file to check
+     * @param attributes the file's basic attributes
+     * @param isDirectory whether the file is a directory
+     * @return whether the modification time is more recent that the <abbr>JAR</abbr> file
+     */
+    boolean isUpdated(final Path file, final BasicFileAttributes attributes, final boolean isDirectory) {
+        if (jarFileTime.compareTo(attributes.lastModifiedTime()) < 0) {
+            return true;
+        }
+        if (!isDirectory) {
+            filesInBuild.add(file);
+        }
+        return false;
+    }
+
+    /**
+     * Checks if the <abbr>JAR</abbr> file contains all the given files, no extra entry, and no outdated entry.
+     *
+     * @param fileSets pairs of base directory and files potentially relative to the base directory
+     * @return whether the <abbr>JAR</abbr> file is up-to-date
+     */
+    boolean isUpToDateJAR(final Collection<Archive.FileSet> fileSets) {
+        // No need to use JarFile because no need to handle META-INF in a special way.
+        try (ZipFile jar = new ZipFile(jarFile.toFile())) {
+            entries = jar.entries();
+            for (Path file : filesInBuild) {
+                if (!isFoundInJAR(file)) {
+                    return false;
+                }
+            }
+            for (Archive.FileSet fileSet : fileSets) {
+                final Path baseDir = fileSet.directory;
+                for (Path file : fileSet.files) {
+                    file = baseDir.resolve(file);
+                    if (!filesInBuild.remove(file)) { // For skipping the files already verified by above loop.
+                        Files.walkFileTree(file, this);
+                        if (hasUpdates) {
+                            return false;
+                        }
+                    }
+                }
+            }
+            // Check for remaining files in the JAR which were not in the build directory.
+            for (Path file : filesInJAR) {
+                if (!isIgnored(classesDir.relativize(file))) {
+                    return false;
+                }
+            }
+            while (entries.hasMoreElements()) {
+                ZipEntry entry = entries.nextElement();
+                if (!(entry.isDirectory() || isIgnored(Path.of(entry.getName())))) {
+                    return false;
+                }
+            }
+        } catch (IOException e) {
+            logger.warn(e);
+            return false;
+        } finally {
+            entries = null;
+        }
+        return true;
+    }
+
+    /**
+     * Returns whether the given file in a <abbr>JAR</abbr> file should be ignored.
+     * We have to ignore the files that are generated in a temporary directory
+     * because they do not exist yet when the directory is traversed. Furthermore,
+     * their timestamp would always be newer then the <abbr>JAR</abbr> file anyway.
+     *
+     * @param file path to a file relative to the root of the <abbr>JAR</abbr> file
+     */
+    private static boolean isIgnored(Path file) {
+        if (file.startsWith(MetadataFiles.META_INF)) {
+            file = file.subpath(1, file.getNameCount());
+            if (file.startsWith(MetadataFiles.MANIFEST)) {
+                return file.getNameCount() == 1;
+            } else if (file.startsWith(MetadataFiles.MAVEN_DIR)) {
+                return true; // Ignore all subdirectories.
+            }
+        }
+        return false;
+    }
+
+    /**
+     * Checks if the given file is new or more recent than the <abbr>JAR</abbr> file.
+     * Checks also if the file exists in the <abbr>JAR</abbr> file.
+     *
+     * @param file the traversed file
+     * @param attributes the file's basic attributes
+     */
+    @Override
+    public FileVisitResult visitFile(final Path file, final BasicFileAttributes attributes) {
+        if (jarFileTime.compareTo(attributes.lastModifiedTime()) >= 0 && isFoundInJAR(file)) {
+            return FileVisitResult.CONTINUE;
+        } else {
+            hasUpdates = true;
+            return FileVisitResult.TERMINATE;
+        }
+    }
+
+    /**
+     * Returns whether the given file is found in the <abbr>JAR</abbr> file.
+     *
+     * @param file the file to check
+     * @return whether the given file was found in the <abbr>JAR</abbr> file
+     */
+    private boolean isFoundInJAR(final Path file) {
+        if (filesInJAR.remove(file)) {

Review Comment:
   Renamed.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3892134202


##########
src/test/java/org/apache/maven/plugins/jar/ArchiveTest.java:
##########
@@ -0,0 +1,264 @@
+/*
+ * 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.jar;
+
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Unit tests for {@link Archive}, focused on the two behaviours that are otherwise only
+ * exercised by integration tests whose outcome depends on the (unspecified) filesystem
+ * directory-iteration order, and therefore pass on some platforms while failing on others.
+ */
+class ArchiveTest {
+
+    /**
+     * Creates an {@code Archive} suitable for a unit test. {@code forceCreation = true} skips the
+     * existing-JAR timestamp check, so the (here {@code null}) logger is never dereferenced.
+     */
+    private static Archive archive(String moduleName, Runtime.Version version, Path directory, boolean isReproducible) {
+        return new Archive(directory.resolve("out.jar"), moduleName, version, directory, true, isReproducible, null);
+    }
+
+    /**
+     * Creates a manifest with the main class attribute set to the given value.
+     *
+     * @param value value of the main class attribute
+     * @return a new manifest with the given attribute value
+     */
+    private static Manifest manifestWithMainClass(String value) {
+        Manifest m = new Manifest();
+        Attributes attributes = m.getMainAttributes();
+        attributes.put(Attributes.Name.MANIFEST_VERSION, "1.0");
+        attributes.put(Attributes.Name.MAIN_CLASS, value);
+        return m;
+    }
+
+    /**
+     * Returns the value of the main class attribute.
+     *
+     * @param m the manifest from which to get the value
+     * @return the main class attribute value, or {@code null} if none
+     */
+    private static Object mainClassOf(Manifest m) {
+        return m.getMainAttributes().get(Attributes.Name.MAIN_CLASS);
+    }
+
+    /**
+     * Verifies that {@link Archive#setMainClass(Manifest)} takes ownership for a module-qualified
+     * {@code "module/Class"} main class.
+     *
+     * Note that the {@code "foo.bar/"} prefix in this test (the module name) is a Maven extension.
+     * The standard <abbr>JAR</abbr> specification accepts only the {@code "foo.MainFile"} class name.
+     */
+    @Test
+    void owningModuleClaimsMainClassAndRemovesItFromManifest() {
+        Archive owner = archive("foo.bar", null, Path.of("."), false);
+        Manifest m = manifestWithMainClass("foo.bar/foo.MainFile");
+        // The owner keeps the main class (emitted via --main-class) ...
+        assertTrue(owner.setMainClass(m));
+        // ... and the raw `module/Class` value is removed from the written manifest.
+        assertNull(mainClassOf(m));
+    }
+
+    /**
+     * Verifies that {@link Archive#setMainClass(Manifest)} does <em>not</em> take ownership fo
+     * a module-qualified {@code "module/Class"} main class when the module name does not match.
+     * Note that the {@code "foo.bar/"} prefix in this test (the module name) is a Maven extension.

Review Comment:
   Done



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3921697371


##########
src/main/java/org/apache/maven/plugins/jar/Archive.java:
##########
@@ -0,0 +1,655 @@
+/*
+ * 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.jar;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.TreeMap;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.Type;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.MojoException;
+
+/**
+ * Files or root directories to archive for a single module.
+ * A single instance of {@code Archive} can contain many directories for different target Java releases.
+ * Many instances of {@code Archive} can exist when archiving a multi-modules project.
+ */
+final class Archive {
+    /**
+     * Path to the <abbr>POM</abbr> file generated for this archive, or {@code null} if none.
+     * This is non-null only if module source hierarchy is used, in which case the dependencies
+     * declared in this file are the intersection of the project dependencies and the content of
+     * the {@code module-info.class} file.
+     */
+    @Nullable
+    Path pomFile;
+
+    /**
+     * The <var>JAR</var> file to create. Can be an existing file,
+     * in which case the file creation can be skipped if the file is still up-to-date.
+     */
+    @Nonnull
+    final Path jarFile;
+
+    /**
+     * A helper class for checking whether an existing <abbr>JAR</abbr> file is still up-to-date.
+     * This is null if there is no existing JAR file, or if we determined that the file is outdated.
+     */
+    private TimestampCheck existingJAR;
+
+    /**
+     * Name of the module being archived when the project is using module hierarchy.
+     * This is {@code null} if the project is using package hierarchy, either because it is a classical
+     * class-path project or because it is a single module compiled without using the module hierarchy.
+     * When using module source hierarchy, {@code javac} guarantees that the module name in the output
+     * directory is the name of the parent directory of {@code module-info.class}.
+     */
+    @Nullable
+    final String moduleName;
+
+    /**
+     * Path to {@code META-INF/MANIFEST.MF}, or {@code null} if none.
+     * If non-null, this value will be given to the {@code --manifest} option.
+     * The use of this option is preferable to adding {@code MANIFEST.MF} as an ordinary file.
+     *
+     * @see #setManifest(Path, boolean)
+     * @see #mergeManifest(Path, Manifest)
+     */
+    @Nullable
+    private Path manifest;
+
+    /**
+     * The Maven generated {@code pom.xml} and {@code pom.properties} files, or {@code null} if none.
+     * This first item must be the base directory where the files are located.
+     */
+    @Nullable
+    List<Path> mavenFiles;
+
+    /**
+     * Fully-qualified name of the main class, or {@code null} if none.
+     * This is the value to provide to the {@code --main-class} option.
+     */
+    private String mainClass;
+
+    /**
+     * Files or root directories to store in the <abbr>JAR</abbr> file for each target Java release
+     * other than the base release. Keys are the target Java release with {@code null} for the base
+     * release.
+     */
+    @Nonnull
+    private final NavigableMap<Runtime.Version, FileSet> filesetForRelease;
+
+    /**
+     * Files or root directories to archive for a single target Java release of a single module.
+     * The {@link Archive} enclosing must contain at least one instance of {@code FileSet} for
+     * the base release, and an arbitrary amount of other instances for other target releases.
+     */
+    final class FileSet {
+        /**
+         * The root directory of all files or directories to archive.
+         * This is the value to pass to the {@code -C} tool option.
+         */
+        @Nonnull
+        final Path directory;
+
+        /**
+         * The files or directories to include in the <var>JAR</var> file.

Review Comment:
   ok



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3921806897


##########
src/main/java/org/apache/maven/plugins/jar/Archive.java:
##########
@@ -0,0 +1,655 @@
+/*
+ * 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.jar;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.TreeMap;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.Type;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.MojoException;
+
+/**
+ * Files or root directories to archive for a single module.
+ * A single instance of {@code Archive} can contain many directories for different target Java releases.
+ * Many instances of {@code Archive} can exist when archiving a multi-modules project.
+ */
+final class Archive {
+    /**
+     * Path to the <abbr>POM</abbr> file generated for this archive, or {@code null} if none.
+     * This is non-null only if module source hierarchy is used, in which case the dependencies
+     * declared in this file are the intersection of the project dependencies and the content of
+     * the {@code module-info.class} file.
+     */
+    @Nullable
+    Path pomFile;
+
+    /**
+     * The <var>JAR</var> file to create. Can be an existing file,
+     * in which case the file creation can be skipped if the file is still up-to-date.
+     */
+    @Nonnull
+    final Path jarFile;
+
+    /**
+     * A helper class for checking whether an existing <abbr>JAR</abbr> file is still up-to-date.
+     * This is null if there is no existing JAR file, or if we determined that the file is outdated.
+     */
+    private TimestampCheck existingJAR;
+
+    /**
+     * Name of the module being archived when the project is using module hierarchy.
+     * This is {@code null} if the project is using package hierarchy, either because it is a classical
+     * class-path project or because it is a single module compiled without using the module hierarchy.
+     * When using module source hierarchy, {@code javac} guarantees that the module name in the output
+     * directory is the name of the parent directory of {@code module-info.class}.
+     */
+    @Nullable
+    final String moduleName;
+
+    /**
+     * Path to {@code META-INF/MANIFEST.MF}, or {@code null} if none.
+     * If non-null, this value will be given to the {@code --manifest} option.
+     * The use of this option is preferable to adding {@code MANIFEST.MF} as an ordinary file.
+     *
+     * @see #setManifest(Path, boolean)
+     * @see #mergeManifest(Path, Manifest)
+     */
+    @Nullable
+    private Path manifest;
+
+    /**
+     * The Maven generated {@code pom.xml} and {@code pom.properties} files, or {@code null} if none.
+     * This first item must be the base directory where the files are located.
+     */
+    @Nullable
+    List<Path> mavenFiles;
+
+    /**
+     * Fully-qualified name of the main class, or {@code null} if none.
+     * This is the value to provide to the {@code --main-class} option.
+     */
+    private String mainClass;
+
+    /**
+     * Files or root directories to store in the <abbr>JAR</abbr> file for each target Java release
+     * other than the base release. Keys are the target Java release with {@code null} for the base
+     * release.
+     */
+    @Nonnull
+    private final NavigableMap<Runtime.Version, FileSet> filesetForRelease;
+
+    /**
+     * Files or root directories to archive for a single target Java release of a single module.
+     * The {@link Archive} enclosing must contain at least one instance of {@code FileSet} for
+     * the base release, and an arbitrary amount of other instances for other target releases.
+     */
+    final class FileSet {
+        /**
+         * The root directory of all files or directories to archive.
+         * This is the value to pass to the {@code -C} tool option.
+         */
+        @Nonnull
+        final Path directory;
+
+        /**
+         * The files or directories to include in the <var>JAR</var> file.
+         * Can be absolute paths or paths relative to {@link #directory}.
+         * It usually contains only the files or directories directly in
+         * the root {@linkplain #directory}, not in sub-directories.
+         */
+        @Nonnull
+        final List<Path> files;
+
+        /**
+         * Creates an initially empty set of files or directories for a specific target Java release.
+         *
+         * @param directory the base directory of the files or directories to archive
+         */
+        private FileSet(Path directory) {
+            this.directory = directory;
+            this.files = new ArrayList<>();
+        }
+
+        /**
+         * 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.
+         * The caller should use that common directory for logging a warning message.
+         *
+         * @param base base directory found by previous invocations of this method, or {@code null} if none
+         * @return common directory of discarded files
+         */
+        private Path discardAllFiles(Path base) {
+            for (Path file : files) {
+                if (base == null) {
+                    base = file.getParent();
+                } else {
+                    while (!file.startsWith(base)) {
+                        base = base.getParent();
+                        if (base == null) {
+                            break;
+                        }
+                    }
+                }
+            }
+            files.clear();
+            return base;
+        }
+
+        /**
+         * Adds the given path to the list of files or directories to archive.
+         * If the given path is a directory, then all children will be included.
+         * Children to exclude, if any, should be managed by {@link ExcludedFiles}.
+         *
+         * @param item a file or directory to archive
+         * @param attributes the file's basic attributes
+         * @param isDirectory whether the file is a directory
+         */
+        void add(Path item, BasicFileAttributes attributes, boolean isDirectory) {
+            TimestampCheck tc = existingJAR;
+            if (tc != null && tc.isUpdated(item, attributes, isDirectory)) {
+                existingJAR = null; // Signal that the existing file is outdated.
+            }
+            files.add(item);
+        }
+
+        /**
+         * Adds to the given list the arguments to provide to the "jar" tool for this version.
+         * The elements added to the list will be instances of {@link String} or {@link Path}.
+         *
+         * <h4>Note about the {@code -C} option</h4>
+         * This method repeats the {@code -C} option before each file.
+         * Our tests suggest that the first file after the directory specified by the {@code -C} option must
+         * be relative to that directory and all files after the first one must be prefixed by the directory
+         * which was specified in the {@code -C} option. This behavior is not very intuitive and replying on
+         * it can be fragile. Furthermore, it seems that the relativized file needs to be the shortest one,
+         * otherwise the {@code jar} tool rejects files after the first one with "names do not match".
+         * Which file is first depends on the unspecified directory-iteration order.
+         * Repeating the {@code -C} option for each file seems safer.
+         *
+         * @param addTo the list to add the arguments as {@link String} or {@link Path} instances to
+         * @param version the target Java release, or {@code null} for the base version of the <abbr>JAR</abbr> file
+         * @throws IllegalArgumentException if a path cannot be made relative to the base directory
+         */
+        private void arguments(List<Object> addTo, Runtime.Version version) {
+            if (files.isEmpty()) {
+                return;
+            }
+            if (version != null) {
+                addTo.add("--release");
+                addTo.add(version);
+            }
+            Path previous = null;
+            for (Path file : files) {
+                if (previous != null && file.startsWith(previous)) {
+                    // Already added a parent directory.
+                    continue;
+                }
+                previous = file;
+                file = directory.relativize(file);
+                if (file.getNameCount() <= 1 && file.toString().isEmpty()) {
+                    /*
+                     * The `-C` directory itself (e.g. a "META-INF/versions/<n>" directory added as a whole).
+                     * An empty file argument is invalid for the `jar` tool (some implementations reject it,
+                     * others silently misbehave), so archive the whole directory content with ".".
+                     */
+                    file = Path.of(".");
+                }
+                addTo.add("-C");
+                addTo.add(directory);
+                addTo.add(file);
+            }
+        }
+
+        /**
+         * {@return a string representation for debugging purposes}
+         */
+        @Override
+        public String toString() {
+            return getClass().getSimpleName() + '[' + directory.getFileName() + ": " + files.size() + " files]";
+        }
+    }
+
+    /**
+     * Creates an initially empty set of files or directories.
+     *
+     * @param jarFile path to the <abbr>JAR</abbr> file to create
+     * @param moduleName the module name if using module hierarchy, or {@code null} if using package hierarchy
+     * @param version the target Java release, or {@code null} for the base version
+     * @param directory the directory of the classes targeting the base Java release
+     * @param forceCreation whether to force a new <abbr>JAR</abbr> file even if the content seems unchanged
+     * @param logger where to send a warning if an error occurred while checking an existing <abbr>JAR</abbr> file
+     */
+    @SuppressWarnings("checkstyle:NeedBraces")
+    Archive(
+            final Path jarFile,
+            final String moduleName,
+            final Runtime.Version version,
+            final Path directory,
+            final boolean forceCreation,
+            final Log logger) {
+        this.jarFile = jarFile;
+        this.moduleName = moduleName;
+        filesetForRelease = new TreeMap<>((v1, v2) -> {
+            if (v1 == v2) return 0;
+            if (v1 == null) return -1;
+            if (v2 == null) return +1;
+            return v1.compareTo(v2);
+        });
+        filesetForRelease.put(version, new FileSet(directory));
+        if (!forceCreation && Files.isRegularFile(jarFile)) {
+            try {
+                existingJAR = new TimestampCheck(jarFile, directory, logger);
+            } catch (IOException e) {
+                // Ignore, we will regenerate the JAR file.
+                logger.warn(e);
+            }
+        }
+    }
+
+    /**
+     * {@return the files or directories to store in the <abbr>JAR</abbr> file for targeting the base Java release}
+     *
+     * @throws NoSuchElementException should not happen unless {@link #prune(boolean)} has been invoked
+     */
+    FileSet baseRelease() {
+        Map.Entry<Runtime.Version, FileSet> entry = filesetForRelease.firstEntry();
+        String message = null;
+        if (entry != null) {
+            Runtime.Version version = entry.getKey();
+            if (version == null) {
+                return entry.getValue();
+            }
+            message = "Expected base version but found version " + version;
+        }
+        throw new NoSuchElementException(message);
+    }
+
+    /**
+     * Returns the {@code module-info.class} files. Conceptually, there is at most once such file per module.
+     * However, more than one file can exist if additional files are provided for additional Java releases.
+     * This method returns only the files that exist.
+     *
+     * @return all {@code module-info.class} files found for all target Java releases
+     */
+    public List<Path> moduleInfoFiles() {
+        var files = new ArrayList<Path>();
+        filesetForRelease.values().forEach((release) -> {
+            Path file = release.directory.resolve(FileCollector.MODULE_DESCRIPTOR_FILE_NAME);
+            if (Files.isRegularFile(file)) {
+                files.add(file);
+            }
+        });
+        return files;
+    }
+
+    /**
+     * Discards all files in this archive, normally because those files are not in any module.
+     * This method returns a common parent directory for all the files that were discarded.
+     * The caller should use that common directory for logging a warning message.
+     *
+     * @return common directory of discarded files, or {@code null} if none
+     */
+    Path discardAllFiles() {
+        Path base = null;
+        for (FileSet release : filesetForRelease.values()) {
+            base = release.discardAllFiles(base);
+        }
+        filesetForRelease.clear();
+        return base;
+    }
+
+    /**
+     * Removes all empty file sets 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}, then this method ensures that at least one file set
+     * remains even if that file set is empty.
+     *
+     * @param skipIfEmpty value of {@link AbstractJarMojo#skipIfEmpty}
+     */
+    public void prune(final boolean skipIfEmpty) {
+        FileSet keep = (skipIfEmpty || isEmpty())
+                ? null
+                : filesetForRelease.firstEntry().getValue();
+        filesetForRelease.values().removeIf((fs) -> fs.files.isEmpty());
+        Iterator<Map.Entry<Runtime.Version, FileSet>> it =
+                filesetForRelease.entrySet().iterator();
+        if (it.hasNext()) {
+            Map.Entry<Runtime.Version, FileSet> first = it.next();
+            if (first.getKey() == null) {
+                return; // Already contains an entry for the base version, nothing to do.
+            }
+            keep = first.getValue();
+            it.remove();
+        }
+        if (keep != null) {
+            filesetForRelease.put(null, keep);
+        }
+    }
+
+    /**
+     * {@return whether this archive has nothing to archive}
+     * This method can return {@code false} even when there is zero file to archive.

Review Comment:
   Done.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3921945038


##########
src/main/java/org/apache/maven/plugins/jar/Archive.java:
##########
@@ -0,0 +1,655 @@
+/*
+ * 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.jar;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.TreeMap;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.Type;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.MojoException;
+
+/**
+ * Files or root directories to archive for a single module.
+ * A single instance of {@code Archive} can contain many directories for different target Java releases.
+ * Many instances of {@code Archive} can exist when archiving a multi-modules project.
+ */
+final class Archive {
+    /**
+     * Path to the <abbr>POM</abbr> file generated for this archive, or {@code null} if none.
+     * This is non-null only if module source hierarchy is used, in which case the dependencies
+     * declared in this file are the intersection of the project dependencies and the content of
+     * the {@code module-info.class} file.
+     */
+    @Nullable
+    Path pomFile;
+
+    /**
+     * The <var>JAR</var> file to create. Can be an existing file,
+     * in which case the file creation can be skipped if the file is still up-to-date.
+     */
+    @Nonnull
+    final Path jarFile;
+
+    /**
+     * A helper class for checking whether an existing <abbr>JAR</abbr> file is still up-to-date.
+     * This is null if there is no existing JAR file, or if we determined that the file is outdated.
+     */
+    private TimestampCheck existingJAR;
+
+    /**
+     * Name of the module being archived when the project is using module hierarchy.
+     * This is {@code null} if the project is using package hierarchy, either because it is a classical
+     * class-path project or because it is a single module compiled without using the module hierarchy.
+     * When using module source hierarchy, {@code javac} guarantees that the module name in the output
+     * directory is the name of the parent directory of {@code module-info.class}.
+     */
+    @Nullable
+    final String moduleName;
+
+    /**
+     * Path to {@code META-INF/MANIFEST.MF}, or {@code null} if none.
+     * If non-null, this value will be given to the {@code --manifest} option.
+     * The use of this option is preferable to adding {@code MANIFEST.MF} as an ordinary file.
+     *
+     * @see #setManifest(Path, boolean)
+     * @see #mergeManifest(Path, Manifest)
+     */
+    @Nullable
+    private Path manifest;
+
+    /**
+     * The Maven generated {@code pom.xml} and {@code pom.properties} files, or {@code null} if none.
+     * This first item must be the base directory where the files are located.
+     */
+    @Nullable
+    List<Path> mavenFiles;
+
+    /**
+     * Fully-qualified name of the main class, or {@code null} if none.
+     * This is the value to provide to the {@code --main-class} option.
+     */
+    private String mainClass;
+
+    /**
+     * Files or root directories to store in the <abbr>JAR</abbr> file for each target Java release
+     * other than the base release. Keys are the target Java release with {@code null} for the base
+     * release.
+     */
+    @Nonnull
+    private final NavigableMap<Runtime.Version, FileSet> filesetForRelease;
+
+    /**
+     * Files or root directories to archive for a single target Java release of a single module.
+     * The {@link Archive} enclosing must contain at least one instance of {@code FileSet} for
+     * the base release, and an arbitrary amount of other instances for other target releases.
+     */
+    final class FileSet {
+        /**
+         * The root directory of all files or directories to archive.
+         * This is the value to pass to the {@code -C} tool option.
+         */
+        @Nonnull
+        final Path directory;
+
+        /**
+         * The files or directories to include in the <var>JAR</var> file.
+         * Can be absolute paths or paths relative to {@link #directory}.
+         * It usually contains only the files or directories directly in
+         * the root {@linkplain #directory}, not in sub-directories.
+         */
+        @Nonnull
+        final List<Path> files;
+
+        /**
+         * Creates an initially empty set of files or directories for a specific target Java release.
+         *
+         * @param directory the base directory of the files or directories to archive
+         */
+        private FileSet(Path directory) {
+            this.directory = directory;
+            this.files = new ArrayList<>();
+        }
+
+        /**
+         * 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.
+         * The caller should use that common directory for logging a warning message.
+         *
+         * @param base base directory found by previous invocations of this method, or {@code null} if none
+         * @return common directory of discarded files
+         */
+        private Path discardAllFiles(Path base) {
+            for (Path file : files) {
+                if (base == null) {
+                    base = file.getParent();
+                } else {
+                    while (!file.startsWith(base)) {
+                        base = base.getParent();
+                        if (base == null) {
+                            break;
+                        }
+                    }
+                }
+            }
+            files.clear();
+            return base;
+        }
+
+        /**
+         * Adds the given path to the list of files or directories to archive.
+         * If the given path is a directory, then all children will be included.
+         * Children to exclude, if any, should be managed by {@link ExcludedFiles}.
+         *
+         * @param item a file or directory to archive
+         * @param attributes the file's basic attributes
+         * @param isDirectory whether the file is a directory
+         */
+        void add(Path item, BasicFileAttributes attributes, boolean isDirectory) {
+            TimestampCheck tc = existingJAR;
+            if (tc != null && tc.isUpdated(item, attributes, isDirectory)) {
+                existingJAR = null; // Signal that the existing file is outdated.
+            }
+            files.add(item);
+        }
+
+        /**
+         * Adds to the given list the arguments to provide to the "jar" tool for this version.
+         * The elements added to the list will be instances of {@link String} or {@link Path}.
+         *
+         * <h4>Note about the {@code -C} option</h4>
+         * This method repeats the {@code -C} option before each file.
+         * Our tests suggest that the first file after the directory specified by the {@code -C} option must
+         * be relative to that directory and all files after the first one must be prefixed by the directory
+         * which was specified in the {@code -C} option. This behavior is not very intuitive and replying on
+         * it can be fragile. Furthermore, it seems that the relativized file needs to be the shortest one,
+         * otherwise the {@code jar} tool rejects files after the first one with "names do not match".
+         * Which file is first depends on the unspecified directory-iteration order.
+         * Repeating the {@code -C} option for each file seems safer.
+         *
+         * @param addTo the list to add the arguments as {@link String} or {@link Path} instances to
+         * @param version the target Java release, or {@code null} for the base version of the <abbr>JAR</abbr> file
+         * @throws IllegalArgumentException if a path cannot be made relative to the base directory
+         */
+        private void arguments(List<Object> addTo, Runtime.Version version) {
+            if (files.isEmpty()) {
+                return;
+            }
+            if (version != null) {
+                addTo.add("--release");
+                addTo.add(version);
+            }
+            Path previous = null;
+            for (Path file : files) {
+                if (previous != null && file.startsWith(previous)) {
+                    // Already added a parent directory.
+                    continue;
+                }
+                previous = file;
+                file = directory.relativize(file);
+                if (file.getNameCount() <= 1 && file.toString().isEmpty()) {
+                    /*
+                     * The `-C` directory itself (e.g. a "META-INF/versions/<n>" directory added as a whole).
+                     * An empty file argument is invalid for the `jar` tool (some implementations reject it,
+                     * others silently misbehave), so archive the whole directory content with ".".
+                     */
+                    file = Path.of(".");
+                }
+                addTo.add("-C");
+                addTo.add(directory);
+                addTo.add(file);
+            }
+        }
+
+        /**
+         * {@return a string representation for debugging purposes}
+         */
+        @Override
+        public String toString() {
+            return getClass().getSimpleName() + '[' + directory.getFileName() + ": " + files.size() + " files]";
+        }
+    }
+
+    /**
+     * Creates an initially empty set of files or directories.
+     *
+     * @param jarFile path to the <abbr>JAR</abbr> file to create
+     * @param moduleName the module name if using module hierarchy, or {@code null} if using package hierarchy
+     * @param version the target Java release, or {@code null} for the base version
+     * @param directory the directory of the classes targeting the base Java release
+     * @param forceCreation whether to force a new <abbr>JAR</abbr> file even if the content seems unchanged
+     * @param logger where to send a warning if an error occurred while checking an existing <abbr>JAR</abbr> file
+     */
+    @SuppressWarnings("checkstyle:NeedBraces")
+    Archive(
+            final Path jarFile,
+            final String moduleName,
+            final Runtime.Version version,
+            final Path directory,
+            final boolean forceCreation,
+            final Log logger) {
+        this.jarFile = jarFile;
+        this.moduleName = moduleName;
+        filesetForRelease = new TreeMap<>((v1, v2) -> {
+            if (v1 == v2) return 0;
+            if (v1 == null) return -1;
+            if (v2 == null) return +1;
+            return v1.compareTo(v2);
+        });
+        filesetForRelease.put(version, new FileSet(directory));
+        if (!forceCreation && Files.isRegularFile(jarFile)) {
+            try {
+                existingJAR = new TimestampCheck(jarFile, directory, logger);
+            } catch (IOException e) {
+                // Ignore, we will regenerate the JAR file.
+                logger.warn(e);
+            }
+        }
+    }
+
+    /**
+     * {@return the files or directories to store in the <abbr>JAR</abbr> file for targeting the base Java release}
+     *
+     * @throws NoSuchElementException should not happen unless {@link #prune(boolean)} has been invoked
+     */
+    FileSet baseRelease() {
+        Map.Entry<Runtime.Version, FileSet> entry = filesetForRelease.firstEntry();
+        String message = null;
+        if (entry != null) {
+            Runtime.Version version = entry.getKey();
+            if (version == null) {
+                return entry.getValue();
+            }
+            message = "Expected base version but found version " + version;
+        }
+        throw new NoSuchElementException(message);
+    }
+
+    /**
+     * Returns the {@code module-info.class} files. Conceptually, there is at most once such file per module.
+     * However, more than one file can exist if additional files are provided for additional Java releases.
+     * This method returns only the files that exist.
+     *
+     * @return all {@code module-info.class} files found for all target Java releases
+     */
+    public List<Path> moduleInfoFiles() {
+        var files = new ArrayList<Path>();
+        filesetForRelease.values().forEach((release) -> {
+            Path file = release.directory.resolve(FileCollector.MODULE_DESCRIPTOR_FILE_NAME);
+            if (Files.isRegularFile(file)) {
+                files.add(file);
+            }
+        });
+        return files;
+    }
+
+    /**
+     * Discards all files in this archive, normally because those files are not in any module.
+     * This method returns a common parent directory for all the files that were discarded.
+     * The caller should use that common directory for logging a warning message.
+     *
+     * @return common directory of discarded files, or {@code null} if none
+     */
+    Path discardAllFiles() {
+        Path base = null;
+        for (FileSet release : filesetForRelease.values()) {
+            base = release.discardAllFiles(base);
+        }
+        filesetForRelease.clear();
+        return base;
+    }
+
+    /**
+     * Removes all empty file sets 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}, then this method ensures that at least one file set
+     * remains even if that file set is empty.
+     *
+     * @param skipIfEmpty value of {@link AbstractJarMojo#skipIfEmpty}
+     */
+    public void prune(final boolean skipIfEmpty) {
+        FileSet keep = (skipIfEmpty || isEmpty())
+                ? null
+                : filesetForRelease.firstEntry().getValue();
+        filesetForRelease.values().removeIf((fs) -> fs.files.isEmpty());
+        Iterator<Map.Entry<Runtime.Version, FileSet>> it =
+                filesetForRelease.entrySet().iterator();
+        if (it.hasNext()) {
+            Map.Entry<Runtime.Version, FileSet> first = it.next();
+            if (first.getKey() == null) {
+                return; // Already contains an entry for the base version, nothing to do.
+            }
+            keep = first.getValue();
+            it.remove();
+        }
+        if (keep != null) {
+            filesetForRelease.put(null, keep);
+        }
+    }
+
+    /**
+     * {@return whether this archive has nothing to archive}
+     * This method can return {@code false} even when there is zero file to archive.
+     * It can happen if {@link AbstractJarMojo#skipIfEmpty} is {@code false}. In such case, the
+     * "empty" <abbr>JAR</abbr> file will still contain at {@code META-INF/MANIFEST.MF} file.
+     *
+     * <h4>Prerequisites</h4>
+     * The {@link #prune(boolean)} method should be invoked before this method for accurate result.
+     */
+    public boolean isEmpty() {
+        return filesetForRelease.isEmpty();
+    }
+
+    /**
+     * Checks whether the <abbr>JAR</abbr> file already exists and can be reused.
+     * This method verifies that the <abbr>JAR</abbr> file contains all the files to archive,
+     * contains no extra file, and no file to archive is newer than the <abbr>JAR</abbr> file.
+     *
+     * <p>This method can be invoked only once.
+     * If invoked more often, it returns {@code false} on all subsequent invocations.</p>
+     *
+     * @return whether the <abbr>JAR</abbr> file already exists and can be reused
+     */
+    public boolean isUpToDateJAR() {
+        final TimestampCheck tc = existingJAR;
+        if (tc == null) {
+            return false;
+        }
+        existingJAR = null; // Let GC do its job.
+        return tc.isUpToDateJAR(filesetForRelease.values());
+    }
+
+    /**
+     * Returns an initially empty set of files or directories for the specified target Java release.
+     *
+     * @param directory the base directory of the files to archive
+     * @param version the target Java release, or {@code null} for the base version
+     * @return container where to declare files and directories to archive
+     */
+    FileSet newTargetRelease(Path directory, Runtime.Version version) {
+        return filesetForRelease.computeIfAbsent(version, (key) -> new FileSet(directory));
+    }
+
+    /**
+     * Sets the {@code --main-class} option to the value of the {@code Main-Class} entry of the given manifest.
+     * As an extension, this method accepts the {@code module/classname} syntax (a syntax already used in some
+     * Java tools). If a module is specified, the main class is kept only if the module match. The intent is to
+     * allow users to specify on which module the main class applies when they use plugin configuration.
+     *
+     * <p>This method may modify the {@code content} manifest. Caller must ensure that the given manifest
+     * is not a shared instance. This method returns whether a change has actually been done.</p>
+     *
+     * @param content combination of existing {@code MANIFEST.MF} and manifest inferred from configuration, or null
+     * @return whether the given manifest has been modified by this method
+     */
+    boolean setMainClass(Manifest content) {
+        if (content == null || mainClass != null) {
+            return false;
+        }
+        // We need to remove the attribute, otherwise it will conflict with `--main-class`.
+        mainClass = (String) content.getMainAttributes().remove(Attributes.Name.MAIN_CLASS);
+        if (mainClass != null) {
+            int s = mainClass.indexOf('/');
+            if (s >= 0) {
+                if (mainClass.substring(0, s).strip().equals(moduleName)) {
+                    mainClass = mainClass.substring(s + 1).strip();
+                } else {
+                    mainClass = null; // Main class is defined for another module.
+                }
+            }
+        }
+        return mainClass != null;
+    }
+
+    /**
+     * Sets the {@code --manifest} option to the given value if that option was not already set.
+     *
+     * @param file path to the manifest file
+     * @param force whether to set the manifest even if already set
+     * @return whether the manifest has been set
+     */
+    boolean setManifest(Path file, boolean force) {
+        if (manifest == null || force) {
+            manifest = file;
+            return true;
+        }
+        return false;
+    }
+
+    /**
+     * Merges the manifest of this module with the manifest specified in plugin configuration.
+     * If both {@code file} and {@code content} are non-null, then {@code content} must be the
+     * result of reading {@code file}.
+     *
+     * <p>This method never modifies the given {@code content} object. If manifest are merged,
+     * a new {@link Manifest} instance is created. Therefore, caller can check whether this
+     * method returned a new instance as a way to recognize that a merge occurred.</p>
+     *
+     * <p>If a merge occurs, the content specified to {@link #setManifest(Path)} has precedence.
+     * It should be the {@code target/classes/META-INF/MANIFEST.MF} file (or modular equivalent).</p>
+     *
+     * @param  file     an additional manifest file, or {@code null}
+     * @param  content  the content of {@code file}, or a standalone manifest produced at runtime
+     * @return the merged manifest as a new instance if some changes were necessary
+     * @throws IOException if an error occurred while reading a manifest file
+     */
+    Manifest mergeManifest(Path file, Manifest content) throws IOException {
+        if (manifest == null) {
+            manifest = file;
+        } else if (file != null && Files.isSameFile(file, manifest)) {
+            // Nothing to merge because of the constraint that `content` must be the content of `file`.
+        } else {
+            try (InputStream in = Files.newInputStream(manifest)) {
+                // No need to wrap in `BufferedInputStream`.
+                if (content != null) {
+                    content = new Manifest(content);
+                    content.read(in);
+                } else {
+                    content = new Manifest(in);
+                }
+            }
+        }
+        return content;
+    }
+
+    /**
+     * Adds to the given list the arguments to provide to the "jar" tool for each version.
+     * Elements added to the list must be instances of {@link String} or {@link Path}.
+     * Callers should have added the following options (if applicable) before to invoke this method:
+     *
+     * <ul>
+     *   <li>{@code --create}</li>
+     *   <li>{@code --no-compress}</li>
+     *   <li>{@code --date} followed by the output time stamp</li>
+     *   <li>{@code --module-version} followed by module version</li>
+     *   <li>{@code --hash-modules} followed by patters of module names</li>
+     *   <li>{@code --module-path} followed by module path</li>
+     * </ul>
+     *
+     * This method adds the following options:
+     *
+     * <ul>
+     *   <li>{@code --file} followed by the path to the <abbr>JAR</abbr> file</li>
+     *   <li>{@code --manifest} followed by path to the manifest file</li>
+     *   <li>{@code --main-class} followed by fully qualified name class</li>
+     *   <li>{@code --release} followed by Java target release</li>
+     *   <li>{@code -C} followed by directory</li>
+     *   <li>files or directories to archive</li>
+     * </ul>
+     *
+     * @param addTo the list where to add the arguments as {@link String} or {@link Path} instances
+     */
+    void arguments(final List<Object> addTo) {
+        addTo.add("--file");
+        addTo.add(jarFile);
+        if (manifest != null) {
+            addTo.add("--manifest");
+            addTo.add(manifest);
+        }
+        if (mainClass != null) {
+            addTo.add("--main-class");
+            addTo.add(mainClass);
+        }
+        if (mavenFiles != null) {
+            addTo.add("-C");
+            addTo.addAll(mavenFiles);
+        }
+        for (Map.Entry<Runtime.Version, FileSet> entry : filesetForRelease.entrySet()) {
+            entry.getValue().arguments(addTo, entry.getKey());
+        }
+    }
+
+    /**
+     * Adds to the given list the arguments to provide to the "jar" tool for validating the <abbr>JAR</abbr> file.
+     * The file is validated only if requested or, in automatic mode, if the validation was not done implicitly at
+     * <abbr>JAR</abbr> creation time. Implicit validation happens if some {@code --release} options were used.
+     * If {@code true}, this method adds the following options:
+     *
+     * <ul>
+     *   <li>{@code --validate} operation mode</li>
+     *   <li>{@code --file} followed by the path to the <abbr>JAR</abbr> file</li>
+     * </ul>
+     *
+     * @param  validate whether to validate, or {@code null} for automatic based on heuristic rules
+     * @param  addTo the list to add the arguments as {@link String} or {@link Path} instances to
+     * @return whether a validation should be run

Review Comment:
   Renamed `addValidateArgumentsTo`



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3923464184


##########
src/main/java/org/apache/maven/plugins/jar/FileCollector.java:
##########
@@ -0,0 +1,541 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.PathMatcher;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Deque;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.services.PathMatcherFactory;
+
+/**
+ * Dispatch the files from the output directory into the <abbr>JAR</abbr> files to create.
+ * Instead of just archiving as-is the content of the output directory, this class separates
+ * the following subdirectories to the options listed below:
+ *
+ * <ul>
+ *   <li>The {@code META-INF/MANIFEST.MF} file will be given to the {@code --manifest} option.</li>
+ *   <li>Files in the following directories will be given to the {@code --release} option:
+ *     <ul>
+ *       <li>{@code META-INF/versions/}</li>
+ *       <li>{@code META-INF/versions-modular/<module>/}</li>
+ *       <li>{@code <module>/META-INF/versions/}</li>
+ *     </ul>
+ *   </li>
+ * </ul>
+ *
+ * The reason for using the options is that they allow the {@code jar} tool to perform additional verifications.

Review Comment:
   Modified the sentence for naming explicitly the options.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3923552549


##########
src/main/java/org/apache/maven/plugins/jar/PomDerivation.java:
##########
@@ -0,0 +1,529 @@
+/*
+ * 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.jar;
+
+import javax.xml.stream.XMLStreamException;
+
+import java.io.BufferedInputStream;
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.UncheckedIOException;
+import java.lang.module.ModuleDescriptor;
+import java.lang.module.ModuleFinder;
+import java.lang.module.ModuleReference;
+import java.net.URI;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.DependencyCoordinates;
+import org.apache.maven.api.JavaPathType;
+import org.apache.maven.api.Session;
+import org.apache.maven.api.Type;
+import org.apache.maven.api.model.Dependency;
+import org.apache.maven.api.model.Model;
+import org.apache.maven.api.model.Parent;
+import org.apache.maven.api.plugin.MojoException;
+import org.apache.maven.api.services.DependencyCoordinatesFactory;
+import org.apache.maven.api.services.DependencyCoordinatesFactoryRequest;
+import org.apache.maven.api.services.DependencyResolver;
+import org.apache.maven.api.services.DependencyResolverRequest;
+import org.apache.maven.api.services.DependencyResolverResult;
+import org.apache.maven.api.services.ModelBuilderException;
+import org.apache.maven.model.v4.MavenStaxWriter;
+
+/**
+ * A mapper from Maven model dependencies to Java module names.
+ * A single instance of this class is created for a Maven project,
+ * then shared by all {@link ForModule} instances (one per module to archive).
+ */
+final class PomDerivation {
+    /**
+     * Whether to expand the list of transitive dependencies in the generated <abbr>POM</abbr>.
+     */
+    private static final boolean EXPAND_TRANSITIVE = false;
+
+    /**
+     * Copy of {@link AbstractJarMojo#session}.
+     */
+    private final Session session;
+
+    /**
+     * The project model, which includes dependencies of all modules.
+     */
+    private final Model projectModel;
+
+    /**
+     * The factory to use for creating temporary {@link DependencyCoordinates} instances.
+     */
+    private final DependencyCoordinatesFactory coordinateFactory;
+
+    /**
+     * Provide module descriptors from module names.
+     * May be {@code null} if no {@code module-info} was found.
+     */
+    private final ModuleFinder moduleFinder;
+
+    /**
+     * Module references from paths to the <abbr>JAR</abbr> file or root directory.
+     */
+    private final Map<URI, ModuleReference> fromURI;
+
+    /**
+     * Module names associated with Maven dependencies.
+     * This map contains {@link DependencyCoordinates#getId()} as keys and module references as values.
+     * This is used to detect which dependencies are really used according to {@code module-info.class}.
+     *
+     * @todo The keys should be instances of {@link DependencyCoordinates}. Unfortunately, as of Maven 4.0.0-rc-5
+     *       that interface does not define the {@code equals} and {@code hashCode} contracts.
+     */
+    private final Map<String, ModuleReference> fromDependency;
+
+    /**
+     * Modules that are built by the project. Keys are module names.
+     */
+    private final Map<String, Dependency> builtModules;
+
+    /**
+     * Creates a new mapper from Maven dependency to module name.
+     *
+     * @param mojo the enclosing <abbr>MOJO</abbr>
+     * @param moduleRoots paths to root directories of each module to archive in a module hierarchy
+     * @throws IOException if an I/O error occurred while fetching dependencies
+     * @throws MavenException if an error occurred while fetching dependencies for a reason other than I/O.
+     */
+    PomDerivation(final AbstractJarMojo mojo, final List<Path> moduleRoots) throws IOException {
+        this.session = mojo.session;
+        projectModel = mojo.project.getModel();
+        coordinateFactory = session.getService(DependencyCoordinatesFactory.class);
+        DependencyResolver resolver = session.getService(DependencyResolver.class);
+        DependencyResolverResult result = resolver.resolve(DependencyResolverRequest.builder()
+                .session(session)
+                .project(mojo.project)
+                .requestType(DependencyResolverRequest.RequestType.RESOLVE)
+                .pathScope(mojo.getDependencyScope())
+                .pathTypeFilter(Set.of(JavaPathType.MODULES, JavaPathType.CLASSES))
+                .build());
+
+        rethrow(result);
+        final Map<org.apache.maven.api.Dependency, Path> dependencies = result.getDependencies();
+        final Path[] allModulePaths = toRealPaths(moduleRoots, dependencies.values());
+        fromURI = new HashMap<>(allModulePaths.length); // TODO: use newHashMap with JDK19.
+        moduleFinder = ModuleFinder.of(allModulePaths);
+        if (moduleFinder != null) {
+            for (ModuleReference reference : moduleFinder.findAll()) {
+                reference.location().ifPresent((location) -> fromURI.put(location, reference));
+            }
+        }
+        fromDependency = new HashMap<>(dependencies.size()); // TODO: use newHashMap with JDK19.
+        for (Map.Entry<org.apache.maven.api.Dependency, Path> entry : dependencies.entrySet()) {
+            Path modulePath = entry.getValue().toRealPath();
+            ModuleReference reference = fromURI.get(modulePath.toUri());
+            if (reference != null) {
+                DependencyCoordinates coordinates = entry.getKey().toCoordinates();
+                String id = coordinates.getId();
+                ModuleReference old = fromDependency.putIfAbsent(id, reference);
+                if (old == null) {
+                    coordinates = withoutVersion(coordinates);
+                    id = coordinates.getId();
+                    old = fromDependency.putIfAbsent(id, reference);
+                }
+                if (old != null && !old.equals(reference)) {
+                    mojo.log.warn("The \"" + id + "\" dependency is declared twice with different module names: \""
+                            + old.descriptor().name() + "\" and \""
+                            + reference.descriptor().name() + "\".");
+                }
+            }
+        }
+        builtModules = new HashMap<>(moduleRoots.size()); // TODO: use newHashMap with JDK19.

Review Comment:
   Done.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3923651959


##########
src/main/java/org/apache/maven/plugins/jar/TimestampCheck.java:
##########
@@ -0,0 +1,261 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.nio.file.attribute.FileTime;
+import java.util.Collection;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+
+import org.apache.maven.api.plugin.Log;
+
+/**
+ * Checks file timestamps in order to determine if anything changed compared to an existing <abbr>JAR</abbr> file.
+ * This class may scan directories, but only if they have not already been visited by {@link FileCollector}.
+ * The latter can only occur if {@link FileCollector} has no {@code PathMatcher}.
+ * Therefore, this class uses no {@code PathMatcher}.
+ *
+ * <h2>Ignore files</h2>
+ * The {@code META-INF/MANIFEST.MF} file and the {@code META-INF/maven/} directory are ignored.
+ * See {@link #isIgnored(Path)} for the rational.
+ */
+final class TimestampCheck extends SimpleFileVisitor<Path> {
+    /**
+     * The base directory of archived files.
+     */
+    private final Path classesDir;
+
+    /**
+     * Path to the existing <abbr>JAR</abbr> file.
+     */
+    private final Path jarFile;
+
+    /**
+     * The last modified time of the <abbr>JAR</abbr> file.
+     */
+    private final FileTime jarFileTime;
+
+    /**
+     * Where to send non-fatal error messages.
+     */
+    private final Log logger;
+
+    /**
+     * Entries of the <abbr>JAR</abbr> file. Note that getting elements from this enumeration can be costly.
+     * Therefore, we only fetch elements when needed.
+     */
+    private Enumeration<? extends ZipEntry> entries;
+
+    /**
+     * Files found in the <abbr>JAR</abbr> file but not yet traversed by the file visitor.
+     * Files are added lazily when needed, and removed as soon as they have been traversed.
+     * Path are absolute (resolved with {@link #classesDir}).

Review Comment:
   Done, thanks.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3949308368


##########
src/main/java/org/apache/maven/plugins/jar/TimestampCheck.java:
##########
@@ -0,0 +1,261 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.nio.file.attribute.FileTime;
+import java.util.Collection;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+
+import org.apache.maven.api.plugin.Log;
+
+/**
+ * Checks file timestamps in order to determine if anything changed compared to an existing <abbr>JAR</abbr> file.
+ * This class may scan directories, but only if they have not already been visited by {@link FileCollector}.
+ * The latter can only occur if {@link FileCollector} has no {@code PathMatcher}.
+ * Therefore, this class uses no {@code PathMatcher}.
+ *
+ * <h2>Ignore files</h2>

Review Comment:
   Done.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "ascheman (via GitHub)" <gi...@apache.org>.
ascheman commented on PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#issuecomment-5256876269

   Thanks for this migration, @desruisseaux — moving JAR creation to the `jar` `ToolProvider` with module-source-hierarchy + multi-release support (and the derived per-module POMs) is a big, elegant step.
   
   Reviewing it, I dug into the CI failures, and they share a root theme: the multi-release/module handling in `FileCollector`/`Archive` depends on the **unspecified `Files.walkFileTree` directory-iteration order** and on **jar-tool-vendor tolerances**. So it passes on macOS/Temurin and fails on Linux/Zulu — i.e. on CI. I found **six** distinct manifestations and prepared an atomic fix + tests for each.
   
   They're on `aschemaven:feat/from-archiver-to-jar-tool` (off your `5886fef`) — [compare](https://github.com/apache/maven-jar-plugin/compare/5886fef...aschemaven:feat/from-archiver-to-jar-tool). The full matrix (ubuntu/macos/windows × JDK 17/21 × rc-6) is **green** with all six, plus deterministic unit tests (`ArchiveTest`) and a `records-jar-validate` IT. Each is its own commit, so you can cherry-pick à la carte:
   
   1. **`jar --validate` crashes on records (JDK 17/18)** — `ToolExecutor` runs `--validate` after create; the JDK 17/18 jar tool throws `This feature requires ASM8` on any record ([JDK-8282446](https://bugs.openjdk.org/browse/JDK-8282446), fixed in 19). Guard: skip validate when `Runtime.version().feature() < 19`. — `27cce4a`
   2. **Base-release dir → NPE** — the base `FileSet` is seeded from whichever dir first creates the `Archive`; on some walk orders that's a `versions-modular/<n>/<module>` dir (no `module-info`), so `ModuleFinder` finds nothing and `PomDerivation` NPEs. Rebind the base to the version-less dir. — `c8a3f66`
   3. **Main-Class on the wrong module** — `setMainClass` removes `Main-Class` from a manifest shared across modules, so the first module processed consumes it. Per-module manifest copy. — `18581f7`
   4. **Absolute jar entry names** — `FileSet.add` relativizes only the first file; later files stay absolute and the jar tool records absolute `.class` entries ("names do not match"). Relativize all + repeat `-C` per file. — `63fe387`
   5. **Empty `-C ""` for version releases** — a `versions/<n>` dir is added to its own FileSet → `relativize(dir,dir)=""`; Zulu rejects `-C dir ""`, Temurin tolerates it. Emit `.`. — `e71b7ad`
   6. **Base files leak into a version FileSet** — a whole version dir is `SKIP_SUBTREE`'d, so `postVisitDirectory` (which resets to the base release) never runs; base files walked afterward land in the version FileSet as `../../../<pkg>`. Reset inline. — `0ee85a8`
   
   Because these are order/vendor-dependent they only surface on CI (Linux+Zulu); the `ArchiveTest` unit tests pin the behaviour deterministically so it can't silently regress on any walk order. Happy to open a PR against your branch if that's easier — just say the word. Thanks again, this is really nice work.
   


-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3777361164


##########
src/main/java/org/apache/maven/plugins/jar/AbstractJarMojo.java:
##########
@@ -207,167 +205,199 @@ protected final Log getLog() {
     protected abstract String getType();
 
     /**
-     * Returns the JAR file to generate, based on an optional classifier.
+     * {@return the scope of dependencies}
+     * It should be {@link PathScope#MAIN_COMPILE} or {@link PathScope#TEST_COMPILE}.
+     * Note that we use compile scope rather than runtime scope because dependencies
+     * cannot appear in {@code requires} statement if they didn't had compile scope.
+     */
+    protected abstract PathScope getDependencyScope();
+
+    /**
+     * {@return the JAR tool to use for archiving the code}
      *
-     * @param basedir the output directory
-     * @param resultFinalName the name of the JAR file
-     * @param classifier an optional classifier
-     * @return the file to generate
+     * @throws MojoException if no JAR tool was found
+     *
+     * @since 4.0.0-beta-2
      */
-    protected Path getJarFile(Path basedir, String resultFinalName, String classifier) {
-        Objects.requireNonNull(basedir, "basedir is not allowed to be null");
-        Objects.requireNonNull(resultFinalName, "finalName is not allowed to be null");
-        String fileName = resultFinalName + (hasClassifier(classifier) ? '-' + classifier : "") + ".jar";
-        return basedir.resolve(fileName);
+    protected ToolProvider getJarTool() throws MojoException {
+        return ToolProvider.findFirst(toolId).orElseThrow(() -> new MojoException("No such \"" + toolId + "\" tool."));
     }
 
     /**
-     * Generates the JAR.
+     * Returns whether the specified Java version is supported.
      *
-     * @return the path to the created archive file
-     * @throws MojoException in case of an error
+     * @param release name of an {@link SourceVersion} enumeration constant
+     * @return whether the current environment support that version
      */
-    public Path createArchive() throws MojoException {
-        Path basedir = outputDirectory != null
-                ? outputDirectory
-                : Path.of(project.getBuild().getDirectory());
-        String resultFinalName =
-                finalName != null ? finalName : project.getBuild().getFinalName();
-        Path jarFile = getJarFile(basedir, resultFinalName, getClassifier());
-
-        FileSetManager fileSetManager = new FileSetManager();
-        FileSet jarContentFileSet = new FileSet();
-        jarContentFileSet.setDirectory(getClassesDirectory().toAbsolutePath().toString());
-        jarContentFileSet.setIncludes(Arrays.asList(getIncludes()));
-        jarContentFileSet.setExcludes(Arrays.asList(getExcludes()));
-
-        String[] includedFiles = fileSetManager.getIncludedFiles(jarContentFileSet);
-
-        if (detectMultiReleaseJar
-                && Arrays.stream(includedFiles)
-                        .anyMatch(
-                                p -> p.startsWith("META-INF" + File.separatorChar + "versions" + File.separatorChar))) {
-            getLog().debug("Adding 'Multi-Release: true' manifest entry.");
-            archive.addManifestEntry(Attributes.Name.MULTI_RELEASE.toString(), "true");
+    private static boolean isSupported(String release) {

Review Comment:
   This is not addressed in this pull request. We will need an API from the tool provider API telling us what is the version of the tool. However, we do not need to address this limitation now. The possibility to use the tool provider is a new feature that we get as a side-effect of this pull request (in the previous JAR plugin version, no `jar` tool was used except in a corner case). A look at the beginning of this `AbstractMojo` file shows that the `toolId` field is annotated with `@since 4.0.0-beta-2`. Therefore, it is not a regression if the tool provider support is incomplete. We can work on that after.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "rmannibucau (via GitHub)" <gi...@apache.org>.
rmannibucau commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3777392170


##########
src/main/java/org/apache/maven/plugins/jar/AbstractJarMojo.java:
##########
@@ -207,167 +205,199 @@ protected final Log getLog() {
     protected abstract String getType();
 
     /**
-     * Returns the JAR file to generate, based on an optional classifier.
+     * {@return the scope of dependencies}
+     * It should be {@link PathScope#MAIN_COMPILE} or {@link PathScope#TEST_COMPILE}.
+     * Note that we use compile scope rather than runtime scope because dependencies
+     * cannot appear in {@code requires} statement if they didn't had compile scope.
+     */
+    protected abstract PathScope getDependencyScope();
+
+    /**
+     * {@return the JAR tool to use for archiving the code}
      *
-     * @param basedir the output directory
-     * @param resultFinalName the name of the JAR file
-     * @param classifier an optional classifier
-     * @return the file to generate
+     * @throws MojoException if no JAR tool was found
+     *
+     * @since 4.0.0-beta-2
      */
-    protected Path getJarFile(Path basedir, String resultFinalName, String classifier) {
-        Objects.requireNonNull(basedir, "basedir is not allowed to be null");
-        Objects.requireNonNull(resultFinalName, "finalName is not allowed to be null");
-        String fileName = resultFinalName + (hasClassifier(classifier) ? '-' + classifier : "") + ".jar";
-        return basedir.resolve(fileName);
+    protected ToolProvider getJarTool() throws MojoException {
+        return ToolProvider.findFirst(toolId).orElseThrow(() -> new MojoException("No such \"" + toolId + "\" tool."));
     }
 
     /**
-     * Generates the JAR.
+     * Returns whether the specified Java version is supported.
      *
-     * @return the path to the created archive file
-     * @throws MojoException in case of an error
+     * @param release name of an {@link SourceVersion} enumeration constant
+     * @return whether the current environment support that version
      */
-    public Path createArchive() throws MojoException {
-        Path basedir = outputDirectory != null
-                ? outputDirectory
-                : Path.of(project.getBuild().getDirectory());
-        String resultFinalName =
-                finalName != null ? finalName : project.getBuild().getFinalName();
-        Path jarFile = getJarFile(basedir, resultFinalName, getClassifier());
-
-        FileSetManager fileSetManager = new FileSetManager();
-        FileSet jarContentFileSet = new FileSet();
-        jarContentFileSet.setDirectory(getClassesDirectory().toAbsolutePath().toString());
-        jarContentFileSet.setIncludes(Arrays.asList(getIncludes()));
-        jarContentFileSet.setExcludes(Arrays.asList(getExcludes()));
-
-        String[] includedFiles = fileSetManager.getIncludedFiles(jarContentFileSet);
-
-        if (detectMultiReleaseJar
-                && Arrays.stream(includedFiles)
-                        .anyMatch(
-                                p -> p.startsWith("META-INF" + File.separatorChar + "versions" + File.separatorChar))) {
-            getLog().debug("Adding 'Multi-Release: true' manifest entry.");
-            archive.addManifestEntry(Attributes.Name.MULTI_RELEASE.toString(), "true");
+    private static boolean isSupported(String release) {

Review Comment:
   > We will need an API from the tool provider API telling us what is the version of the tool.
   
   I don't think it will happen since tool provider is generic enough to not have much compiler knowledge in its own signature, tool provider but the java compiler could maybe  (https://docs.oracle.com/javase/8/docs/api/javax/tools/Tool.html#getSourceVersions--).
   
   > Therefore, it is not a regression if the tool provider support is incomplete.
   
   Well, it is a bug compared to previous experience if you do use the new feature so even if we might not consider it blocking it is bothering to say we rewrote it in a way which doesn't work.
   
   One interesting excercise is to ensure the supported compilers are still supported (thinking to ECJ for ex which is known faster than javac).
   
   Agree forking can come later to avoid leaks in mvnd or alike.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "rmannibucau (via GitHub)" <gi...@apache.org>.
rmannibucau commented on PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#issuecomment-5345166596

   > a post-generation step where the JAR file is read and rewritten with directory entries added using java.util.zip
   
   if this true? if so let's drop toolprovider and get back maven archiver, this is cleaner than a workaround which can be insanelt slower (twice at least) on big jars and try to push upstream the needed features, there is no point to move to a new tool which is twice worse for only a validation most people will not need
   
   
   


-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3949078236


##########
src/main/java/org/apache/maven/plugins/jar/ExcludedFiles.java:
##########
@@ -0,0 +1,146 @@
+/*
+ * 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.jar;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardCopyOption;
+import java.util.List;
+
+/**
+ * A list of files to temporarily move outside the directory to package in a <abbr>JAR</abbr> archive.
+ * This class is needed when the {@link AbstractJarMojo} configuration has include or exclude filters.
+ * Excluded files are temporarily moved outside the directory to archive.
+ * We move these files for making possible to specify the whole directory to the {@code jar} tool.
+ * This approach is used instead of enumerating files in arguments given to the {@code jar} tool because
+ * such enumeration cannot contain directory entries (otherwise the whole directory would be included).
+ * Some software such as Spring applications component scan relies on the presence of directory entries.
+ */
+final class ExcludedFiles implements Closeable {
+    /**
+     * The paths of files or directories to temporarily move in another directory.
+     */
+    private final Path[] original;
+
+    /**
+     * The paths where files or directories were moved.
+     * For each index <var>i</var>, the original path of {@code moved[i]} was {@code original[i]}.
+     */
+    private final Path[] moved;
+
+    /**
+     * Temporary directory which will contain the {@code moved} files.
+     * It should be a parent directory of {@link #original} files for
+     * increasing the chances that it is on the same file system.
+     */
+    private final Path temporaryDirectory;
+
+    /**
+     * Index of the first path which is a directory instead of a file.
+     * All paths before this index in the {@link #original} and {@link #moved} arrays are files.
+     * All paths at this index and after this index are directories.
+     */
+    private final int indexOfFirstDirectory;
+
+    /**
+     * Creates a new list of files to move in a temporary directory.
+     *
+     * @param directory the directory which was scanned for files to include in the <abbr>JAR</abbr>
+     * @param excludedFiles paths of files to temporarily move in another directory
+     * @param excludedDirectories paths of directories to temporarily move in another directory

Review Comment:
   Done.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3949188723


##########
src/main/java/org/apache/maven/plugins/jar/FileCollector.java:
##########
@@ -0,0 +1,542 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.PathMatcher;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Deque;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.services.PathMatcherFactory;
+
+/**
+ * Dispatch the files from the output directory into the <abbr>JAR</abbr> files to create.
+ * Instead of just archiving as-is the content of the output directory, this class separates
+ * the following subdirectories to the options listed below:
+ *
+ * <ul>
+ *   <li>The {@code META-INF/MANIFEST.MF} file will be given to the {@code --manifest} option.</li>
+ *   <li>Files in the following directories will be given to the {@code --release} option:
+ *     <ul>
+ *       <li>{@code META-INF/versions/}</li>
+ *       <li>{@code META-INF/versions-modular/<module>/}</li>
+ *       <li>{@code <module>/META-INF/versions/}</li>
+ *     </ul>
+ *   </li>
+ * </ul>
+ *
+ * The reason for using the {@code --release} and {@code --manifest} options instead of adding explicitly
+ * the entries is because the options allow the {@code jar} tool to perform additional verifications.
+ * For example, when using the {@code --release} option, {@code jar} verifies the <abbr>API</abbr> compatibility.
+ */
+final class FileCollector extends SimpleFileVisitor<Path> {
+    /**
+     * The file to check for deciding whether the <abbr>JAR</abbr> is modular.
+     */
+    static final String MODULE_DESCRIPTOR_FILE_NAME = "module-info.class";
+
+    /**
+     * The {@value} directory.
+     * This is part of <abbr>JAR</abbr> file specification.
+     */
+    private static final String VERSIONS = "versions";
+
+    /**
+     * The {@value} directory.
+     * This is Maven-specific.
+     */
+    private static final String VERSIONS_MODULAR = "versions-modular";
+
+    /**
+     * Context (logger, configuration) in which the <abbr>JAR</abbr> file are created.
+     */
+    private final ToolExecutor context;
+
+    /**
+     * Whether to detect multi-release <abbr>JAR</abbr> files.
+     * The default value is {@code true}.
+     *
+     * @see AbstractJarMojo#detectMultiReleaseJar
+     */
+    private final boolean detectMultiReleaseJar;
+
+    /**
+     * The root directory to traverse. It will be used for temporarily moving excluded files.
+     */
+    private final Path rootDirectory;
+
+    /**
+     * Combination of includes and excludes path matcher applied on files.
+     */
+    @Nonnull
+    private final PathMatcher fileMatcher;
+
+    /**
+     * Combination of includes and excludes path matcher applied on directories.
+     */
+    @Nonnull
+    private final PathMatcher directoryMatcher;
+
+    /**
+     * Files to exclude. These files will be moved to a temporary location
+     * for allowing {@link ToolExecutor} to specify whole directories to the {@code jar} tool.
+     * Specifying whole directories is preferable to enumerating the files because otherwise,
+     * the generated <abbr>JAR</abbr> file contains only entries for the files and is missing
+     * entries for the directories.
+     *
+     * <p>This field is {@code null} if it is not possible to have any excluded file
+     * (because there is no include/exclude filters).</p>
+     */
+    @Nullable
+    private final List<Path> excludedFiles;
+
+    /**
+     * Directories to exclude. This field serves the same purpose as {@link #excludedFiles},
+     * but where the sources a directories instead of files.
+     */
+    @Nullable
+    private final List<Path> excludedDirectories;
+
+    /**
+     * Files found in the output directory when package hierarchy is used.
+     * At most one of {@code packageHierarchy} and {@link #moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Archive packageHierarchy;
+
+    /**
+     * Files found in the output directory when module hierarchy is used. Keys are module names.
+     * At most one of {@link #packageHierarchy} and {@code moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Map<String, Archive> moduleHierarchy;
+
+    /**
+     * The current module being archived. This field is updated every times that {@code FileCollector}
+     * visits a new module directory.
+     */
+    @Nonnull
+    private Archive currentModule;
+
+    /**
+     * The module and target Java release currently being scanned. This field is updated every times that

Review Comment:
   Done.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3949287067


##########
src/main/java/org/apache/maven/plugins/jar/FileCollector.java:
##########
@@ -0,0 +1,542 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.PathMatcher;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Deque;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.services.PathMatcherFactory;
+
+/**
+ * Dispatch the files from the output directory into the <abbr>JAR</abbr> files to create.
+ * Instead of just archiving as-is the content of the output directory, this class separates
+ * the following subdirectories to the options listed below:
+ *
+ * <ul>
+ *   <li>The {@code META-INF/MANIFEST.MF} file will be given to the {@code --manifest} option.</li>
+ *   <li>Files in the following directories will be given to the {@code --release} option:
+ *     <ul>
+ *       <li>{@code META-INF/versions/}</li>
+ *       <li>{@code META-INF/versions-modular/<module>/}</li>
+ *       <li>{@code <module>/META-INF/versions/}</li>
+ *     </ul>
+ *   </li>
+ * </ul>
+ *
+ * The reason for using the {@code --release} and {@code --manifest} options instead of adding explicitly
+ * the entries is because the options allow the {@code jar} tool to perform additional verifications.
+ * For example, when using the {@code --release} option, {@code jar} verifies the <abbr>API</abbr> compatibility.
+ */
+final class FileCollector extends SimpleFileVisitor<Path> {
+    /**
+     * The file to check for deciding whether the <abbr>JAR</abbr> is modular.
+     */
+    static final String MODULE_DESCRIPTOR_FILE_NAME = "module-info.class";
+
+    /**
+     * The {@value} directory.
+     * This is part of <abbr>JAR</abbr> file specification.
+     */
+    private static final String VERSIONS = "versions";
+
+    /**
+     * The {@value} directory.
+     * This is Maven-specific.
+     */
+    private static final String VERSIONS_MODULAR = "versions-modular";
+
+    /**
+     * Context (logger, configuration) in which the <abbr>JAR</abbr> file are created.
+     */
+    private final ToolExecutor context;
+
+    /**
+     * Whether to detect multi-release <abbr>JAR</abbr> files.
+     * The default value is {@code true}.
+     *
+     * @see AbstractJarMojo#detectMultiReleaseJar
+     */
+    private final boolean detectMultiReleaseJar;
+
+    /**
+     * The root directory to traverse. It will be used for temporarily moving excluded files.
+     */
+    private final Path rootDirectory;
+
+    /**
+     * Combination of includes and excludes path matcher applied on files.
+     */
+    @Nonnull
+    private final PathMatcher fileMatcher;
+
+    /**
+     * Combination of includes and excludes path matcher applied on directories.
+     */
+    @Nonnull
+    private final PathMatcher directoryMatcher;
+
+    /**
+     * Files to exclude. These files will be moved to a temporary location
+     * for allowing {@link ToolExecutor} to specify whole directories to the {@code jar} tool.
+     * Specifying whole directories is preferable to enumerating the files because otherwise,
+     * the generated <abbr>JAR</abbr> file contains only entries for the files and is missing
+     * entries for the directories.
+     *
+     * <p>This field is {@code null} if it is not possible to have any excluded file
+     * (because there is no include/exclude filters).</p>
+     */
+    @Nullable
+    private final List<Path> excludedFiles;
+
+    /**
+     * Directories to exclude. This field serves the same purpose as {@link #excludedFiles},
+     * but where the sources a directories instead of files.
+     */
+    @Nullable
+    private final List<Path> excludedDirectories;
+
+    /**
+     * Files found in the output directory when package hierarchy is used.
+     * At most one of {@code packageHierarchy} and {@link #moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Archive packageHierarchy;
+
+    /**
+     * Files found in the output directory when module hierarchy is used. Keys are module names.
+     * At most one of {@link #packageHierarchy} and {@code moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Map<String, Archive> moduleHierarchy;
+
+    /**
+     * The current module being archived. This field is updated every times that {@code FileCollector}
+     * visits a new module directory.
+     */
+    @Nonnull
+    private Archive currentModule;
+
+    /**
+     * The module and target Java release currently being scanned. This field is updated every times that
+     * {@code FileCollector} visits a new module directory or in a new target Java release for a given module.
+     */
+    @Nonnull
+    private Archive.FileSet currentFilesToArchive;
+
+    /**
+     * The current target Java release, or {@code null} if none.
+     */
+    @Nullable
+    private Runtime.Version currentTargetVersion;
+
+    /**
+     * Identification of the kinds of directories being traversed.
+     * The length of this list is the depth in the directory hierarchy.
+     * The last element identifies the type of the current directory.
+     */
+    private final Deque<DirectoryRole> directoryRoles;
+
+    /**
+     * Whether to check when a file is the {@code MANIFEST.MF} file.
+     * This is allowed only when scanning the content of a {@code META-INF} directory.
+     */
+    private boolean checkForManifest;
+
+    /**
+     * Creates a new file collector.
+     *
+     * @param mojo the <abbr>MOJO</abbr> from which to get the configuration
+     * @param context context (logger, configuration) in which the <abbr>JAR</abbr> file are created
+     * @param directory the base directory of the files to archive
+     */
+    FileCollector(AbstractJarMojo mojo, ToolExecutor context, Path directory, PathMatcherFactory matcherFactory) {
+        this.context = context;
+        rootDirectory = directory;
+        detectMultiReleaseJar = mojo.detectMultiReleaseJar;
+        directoryRoles = new ArrayDeque<>();
+        fileMatcher = matcherFactory.createPathMatcher(directory, mojo.getIncludes(), mojo.getExcludes(), false);
+        directoryMatcher = matcherFactory.deriveDirectoryMatcher(fileMatcher);
+        if (matcherFactory.isIncludesAll(fileMatcher) && matcherFactory.isIncludesAll(directoryMatcher)) {
+            excludedFiles = null;
+            excludedDirectories = null;
+        } else {
+            excludedFiles = new ArrayList<>();
+            excludedDirectories = new ArrayList<>();
+        }
+        packageHierarchy = context.newArchive(null, null, directory);
+        moduleHierarchy = new LinkedHashMap<>();
+        resetToPackageHierarchy();
+    }
+
+    /**
+     * Resets this {@code FileCollector} to the state where a package hierarchy is presumed.
+     */
+    private void resetToPackageHierarchy() {
+        currentModule = packageHierarchy;
+        currentFilesToArchive = currentModule.baseRelease();
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a module.
+     * For an output generated by {@code javac} from a module source hierarchy,
+     * the directory name is the module name.
+     *
+     * @param directory a {@code "<module>"} or {@code "META-INF/versions-modular/<module>"} directory
+     */
+    private void preVisitVersionDirectory(final Path directory) {
+        String moduleName = directory.getFileName().toString();
+        currentModule = moduleHierarchy.computeIfAbsent(
+                moduleName, (name) -> context.newArchive(name, currentTargetVersion, directory));
+        currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a target Java version.
+     * The {@code useDirectly} argument tells whether the content of this directory will be specified directly
+     * as the content to add in the <abbr>JAR</abbr> file. This argument should be {@code false} when there is
+     * another directory level (the module names) to process before to add content.
+     *
+     * @param directory a {@code "META-INF/versions/<n>"} or {@code "META-INF/versions-modular/<n>"} directory
+     * @param useDirectly whether the directory is {@code "META-INF/versions/<n>"}
+     * @return whether to skip the directory because of invalid version number
+     */
+    private boolean preVisitVersionDirectory(final Path directory, final boolean useDirectly) {
+        try {
+            currentTargetVersion = Runtime.Version.parse(directory.getFileName().toString());
+        } catch (IllegalArgumentException e) {
+            context.warnInvalidVersion(directory, e);
+            return true;
+        }
+        if (useDirectly) {
+            currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+        }
+        return false;
+    }
+
+    /**
+     * Determines if the given directory should be scanned for files to archive.
+     * This method may also update {@link #currentFilesToArchive} if it detects
+     * that we are visiting the content of a new module or a new target Java release.
+     *
+     * @param directory the directory which will be traversed
+     * @param attributes the directory's basic attributes
+     */
+    @Override
+    @SuppressWarnings("checkstyle:MissingSwitchDefault")
+    public FileVisitResult preVisitDirectory(final Path directory, final BasicFileAttributes attributes)
+            throws IOException {
+        DirectoryRole role;
+        if (directoryRoles.isEmpty()) {
+            role = DirectoryRole.ROOT;
+        } else {
+            if (!directoryMatcher.matches(directory)) {
+                excludedDirectories.add(directory); // Cannot be null if excluded directories may exist.
+                return FileVisitResult.SKIP_SUBTREE;
+            }
+            checkForManifest = false;
+            role = directoryRoles.getLast();
+            switch (role) {
+                case ROOT:
+                    /*
+                     * Visiting any subdirectory of `target/classes` (or other directory to archive).
+                     * We need to handle `META-INF` and modules in a special way, and archive the rest.
+                     */
+                    if (directory.endsWith(MetadataFiles.META_INF)) {
+                        role = DirectoryRole.META_INF;
+                        checkForManifest = true;
+                    } else if (Files.isRegularFile(directory.resolve(MODULE_DESCRIPTOR_FILE_NAME))) {
+                        role = DirectoryRole.NAMED_MODULE;
+                        preVisitVersionDirectory(directory);
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case META_INF:
+                    /*
+                     * Visiting a subdirectory of `META-INF` or `<module>/META-INF`. We will need to handle
+                     * `MANIFEST.MF`, `versions` and `versions-modular` in a special way, and archive the rest.
+                     */
+                    if (detectMultiReleaseJar && directory.endsWith(VERSIONS)) {
+                        role = DirectoryRole.VERSIONS;
+                    } else if (directory.endsWith(VERSIONS_MODULAR)) {
+                        if (!detectMultiReleaseJar) {
+                            // Used asked for no multi-release JAR.
+                            return FileVisitResult.SKIP_SUBTREE;
+                        }
+                        role = DirectoryRole.VERSIONS_MODULAR;
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case VERSIONS:
+                    /*
+                     * Visiting a `META-INF/versions/<n>/` directory for a specific target Java release.
+                     * Can also be a `<module>/META-INF/versions/<n>/` directory, even if the latter is not
+                     * the layout generated by Maven Compiler Plugin.
+                     */
+                    if (preVisitVersionDirectory(directory, true)) {
+                        // An error occurred while parsing the version number.
+                        return FileVisitResult.SKIP_SUBTREE;
+                    }
+                    role = DirectoryRole.RESOURCES;
+                    break;
+
+                case VERSIONS_MODULAR:
+                    /*
+                     * Visiting a `META-INF/versions-modular/<n>/` directory for a specific target Java release.
+                     * That directory contains all modules for the version.
+                     */
+                    resetToPackageHierarchy(); // No module in particular yet.
+                    if (preVisitVersionDirectory(directory, false)) {
+                        // An error occurred while parsing the version number.
+                        return FileVisitResult.SKIP_SUBTREE;
+                    }
+                    role = DirectoryRole.MODULES;
+                    break;
+
+                case MODULES:
+                    /*
+                     * Visiting a `META-INF/versions-modular/<n>/<module>` directory.
+                     */
+                    preVisitVersionDirectory(directory);
+                    role = DirectoryRole.NAMED_MODULE;
+                    break;
+
+                case NAMED_MODULE:
+                    /*
+                     * Visiting a `<module>` or `META-INF/versions-modular/<n>/<module>` subdirectory.
+                     * A module could have its own `META-INF` subdirectory, so we need to check again.
+                     */
+                    if (directory.endsWith(MetadataFiles.META_INF)) {
+                        role = DirectoryRole.META_INF;
+                        checkForManifest = true;
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+            }
+        }
+        /*
+         * Do not move this condition inside the `switch` block because `role` may have been modified.
+         * The `role` value is now the role of `directory`, not the role of parent directory.
+         */
+        if (role == DirectoryRole.RESOURCES) {
+            currentFilesToArchive.add(directory, attributes, true);
+            if (excludedFiles == null) {
+                /*
+                 * Since we are skipping the whole directory, `postVisitDirectory(…)` will not be invoked.
+                 * We must reset `currentFilesToArchive` and `currentTargetVersion` by an explicit call.
+                 * This is important mostly after we added a whole `META-INF/versions/<n>` directory.
+                 * Otherwise, since directory iteration order is unspecified, base files visited afterwards
+                 * would be added to this version's file set instead of the base release.
+                 */
+                resetToParentDirectoryState();
+                return FileVisitResult.SKIP_SUBTREE;
+            }
+        }
+        directoryRoles.addLast(role);
+        return FileVisitResult.CONTINUE;
+    }
+
+    /**
+     * Updates the {@code FileCollector} state after we finished scanning the contents of a directory.
+     * The fields to update depend on which directory has been visited (module, version, etc.).
+     *
+     * @param directory the directory which has been traversed
+     * @param error the error that occurred while traversing the directory, or {@code null} if none
+     */
+    @Override
+    public FileVisitResult postVisitDirectory(final Path directory, final IOException error) throws IOException {
+        if (error != null) {
+            throw error;
+        }
+        switch (directoryRoles.removeLast()) {
+            case ROOT:
+                break;
+
+            case NAMED_MODULE:
+                // Exited the directory of a single module.
+                resetToPackageHierarchy();
+                break;
+
+            default:
+                resetToParentDirectoryState();
+                break;
+        }
+        return FileVisitResult.CONTINUE;
+    }
+
+    /**
+     * Updates {@code FileCollector} to a state suitable for the parent of the directory that we finished to scan.
+     * Contrary to {@link #postVisitDirectory(Path, IOException)}, this method expects the last element of
+     * {@link #directoryRoles} to describe the parent directory, not the directory that we finished to visit.
+     */
+    @SuppressWarnings("checkstyle:MissingSwitchDefault")
+    private void resetToParentDirectoryState() {
+        switch (directoryRoles.getLast()) {
+            case VERSIONS:
+            case VERSIONS_MODULAR:
+                // Exited the directory for one target Java release.
+                currentFilesToArchive = currentModule.baseRelease();
+                currentTargetVersion = null;
+                break;
+
+            case META_INF:
+                checkForManifest = true;
+                break;
+        }
+    }
+
+    /**
+     * Archives a single file if accepted by the matcher.
+     *
+     * @param file the file
+     * @param attributes the file's basic attributes
+     */
+    @Override
+    public FileVisitResult visitFile(final Path file, final BasicFileAttributes attributes) {
+        if (fileMatcher.matches(file)) {
+            if (checkForManifest && file.endsWith(MetadataFiles.MANIFEST) && currentModule.setManifest(file, false)) {

Review Comment:
   Yes, but it would hurt performance (I don't know if it would be in a measurable way), because the analysis would need to be done for every files instead of only once for all when we enter in a directory.
   
   There are other directory-dependent information to track such as `currentModule`, `currentFilesToArchive` and `currentTargetVersion`. In the current design, all those information are updated by `preVisitDirectory`. If `checkForManifest` was treated differently, it would break this consistency.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3949349363


##########
src/test/java/org/apache/maven/plugins/jar/ArchiveTest.java:
##########
@@ -0,0 +1,257 @@
+/*
+ * 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.jar;
+
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Unit tests for {@link Archive}, focused on the two behaviours that are otherwise only
+ * exercised by integration tests whose outcome depends on the (unspecified) filesystem
+ * directory-iteration order, and therefore pass on some platforms while failing on others.
+ */
+class ArchiveTest {
+
+    /**
+     * Creates an {@code Archive} suitable for a unit test. {@code forceCreation = true} skips the
+     * existing-JAR timestamp check, so the (here {@code null}) logger is never dereferenced.
+     */
+    private static Archive archive(String moduleName, Runtime.Version version, Path directory) {
+        return new Archive(directory.resolve("out.jar"), moduleName, version, directory, true, null);
+    }
+
+    /**
+     * Creates a manifest with the main class attribute set to the given value.
+     *
+     * @param value value of the main class attribute
+     * @return a new manifest with the given attribute value
+     */
+    private static Manifest manifestWithMainClass(String value) {
+        Manifest m = new Manifest();

Review Comment:
   Done.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3777489825


##########
src/main/java/org/apache/maven/plugins/jar/AbstractJarMojo.java:
##########
@@ -207,167 +205,199 @@ protected final Log getLog() {
     protected abstract String getType();
 
     /**
-     * Returns the JAR file to generate, based on an optional classifier.
+     * {@return the scope of dependencies}
+     * It should be {@link PathScope#MAIN_COMPILE} or {@link PathScope#TEST_COMPILE}.
+     * Note that we use compile scope rather than runtime scope because dependencies
+     * cannot appear in {@code requires} statement if they didn't had compile scope.
+     */
+    protected abstract PathScope getDependencyScope();
+
+    /**
+     * {@return the JAR tool to use for archiving the code}
      *
-     * @param basedir the output directory
-     * @param resultFinalName the name of the JAR file
-     * @param classifier an optional classifier
-     * @return the file to generate
+     * @throws MojoException if no JAR tool was found
+     *
+     * @since 4.0.0-beta-2
      */
-    protected Path getJarFile(Path basedir, String resultFinalName, String classifier) {
-        Objects.requireNonNull(basedir, "basedir is not allowed to be null");
-        Objects.requireNonNull(resultFinalName, "finalName is not allowed to be null");
-        String fileName = resultFinalName + (hasClassifier(classifier) ? '-' + classifier : "") + ".jar";
-        return basedir.resolve(fileName);
+    protected ToolProvider getJarTool() throws MojoException {
+        return ToolProvider.findFirst(toolId).orElseThrow(() -> new MojoException("No such \"" + toolId + "\" tool."));
     }
 
     /**
-     * Generates the JAR.
+     * Returns whether the specified Java version is supported.
      *
-     * @return the path to the created archive file
-     * @throws MojoException in case of an error
+     * @param release name of an {@link SourceVersion} enumeration constant
+     * @return whether the current environment support that version
      */
-    public Path createArchive() throws MojoException {
-        Path basedir = outputDirectory != null
-                ? outputDirectory
-                : Path.of(project.getBuild().getDirectory());
-        String resultFinalName =
-                finalName != null ? finalName : project.getBuild().getFinalName();
-        Path jarFile = getJarFile(basedir, resultFinalName, getClassifier());
-
-        FileSetManager fileSetManager = new FileSetManager();
-        FileSet jarContentFileSet = new FileSet();
-        jarContentFileSet.setDirectory(getClassesDirectory().toAbsolutePath().toString());
-        jarContentFileSet.setIncludes(Arrays.asList(getIncludes()));
-        jarContentFileSet.setExcludes(Arrays.asList(getExcludes()));
-
-        String[] includedFiles = fileSetManager.getIncludedFiles(jarContentFileSet);
-
-        if (detectMultiReleaseJar
-                && Arrays.stream(includedFiles)
-                        .anyMatch(
-                                p -> p.startsWith("META-INF" + File.separatorChar + "versions" + File.separatorChar))) {
-            getLog().debug("Adding 'Multi-Release: true' manifest entry.");
-            archive.addManifestEntry(Attributes.Name.MULTI_RELEASE.toString(), "true");
+    private static boolean isSupported(String release) {

Review Comment:
   > Well, it is a bug compared to previous experience
   
   There is no previous experience since (if I remember correctly) 3.x had no tool provider support. If this is nevertheless considered as a bug, I can just remove this new `toolId` configuration option and problem solved.
   
   Alternatively, we can keep this new feature and just let users know that it is incomplete. User who really want to use this new tool provider support can avoid the issue by avoiding tools that are too old.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "elharo (via GitHub)" <gi...@apache.org>.
elharo commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3804250371


##########
src/main/java/org/apache/maven/plugins/jar/AbstractJarMojo.java:
##########
@@ -108,13 +105,22 @@ public abstract class AbstractJarMojo implements org.apache.maven.api.plugin.Moj
     @Parameter
     protected MavenArchiveConfiguration archive = new MavenArchiveConfiguration();
 
+    /**
+     * The service to use for attaching the artifacts produced by this plugin.

Review Comment:
   This is a service?



##########
src/main/java/org/apache/maven/plugins/jar/AbstractJarMojo.java:
##########
@@ -108,13 +105,22 @@ public abstract class AbstractJarMojo implements org.apache.maven.api.plugin.Moj
     @Parameter
     protected MavenArchiveConfiguration archive = new MavenArchiveConfiguration();
 
+    /**
+     * The service to use for attaching the artifacts produced by this plugin.
+     */
     @Inject
     protected ProjectManager projectManager;
 
     /**
-     * Require the jar plugin to build a new JAR even if none of the contents appear to have changed.
-     * By default, this plugin looks to see if the output JAR exists and inputs have not changed.
-     * If these conditions are true, the plugin skips creation of the JAR file.
+     * The service to use for creating include and exclude filters.

Review Comment:
   I don't think "service" is the right word here.



##########
src/main/java/org/apache/maven/plugins/jar/AbstractJarMojo.java:
##########
@@ -18,44 +18,44 @@
  */
 package org.apache.maven.plugins.jar;
 
-import java.io.File;
 import java.io.IOException;
 import java.nio.file.Files;
 import java.nio.file.Path;
+import java.time.Instant;
 import java.util.Arrays;
+import java.util.List;
 import java.util.Map;
-import java.util.Objects;
-import java.util.jar.Attributes;
-import java.util.stream.Stream;
+import java.util.spi.ToolProvider;
 
+import org.apache.maven.api.PathScope;
 import org.apache.maven.api.ProducedArtifact;
 import org.apache.maven.api.Project;
 import org.apache.maven.api.Session;
+import org.apache.maven.api.Type;
 import org.apache.maven.api.di.Inject;
 import org.apache.maven.api.plugin.Log;
 import org.apache.maven.api.plugin.MojoException;
 import org.apache.maven.api.plugin.annotations.Parameter;
+import org.apache.maven.api.services.PathMatcherFactory;
 import org.apache.maven.api.services.ProjectManager;
 import org.apache.maven.shared.archiver.MavenArchiveConfiguration;
 import org.apache.maven.shared.archiver.MavenArchiver;
-import org.apache.maven.shared.archiver.MavenArchiverException;
-import org.apache.maven.shared.model.fileset.FileSet;
-import org.apache.maven.shared.model.fileset.util.FileSetManager;
-import org.codehaus.plexus.archiver.Archiver;
-import org.codehaus.plexus.archiver.jar.JarArchiver;
 
 /**
  * Base class for creating a <abbr>JAR</abbr> file from project classes.
  *
  * @author <a href="evenisse@apache.org">Emmanuel Venisse</a>
+ * @author Martin Desruisseaux
  */
 public abstract class AbstractJarMojo implements org.apache.maven.api.plugin.Mojo {
-
-    private static final String[] DEFAULT_EXCLUDES = new String[] {"**/package.html"};
-
-    private static final String[] DEFAULT_INCLUDES = new String[] {"**/**"};
-
-    private static final String MODULE_DESCRIPTOR_FILE_NAME = "module-info.class";
+    /**
+     * Identifier of the tool to use. This identifier shall match the identifier of a tool

Review Comment:
   avoid "shall" as its confusing



##########
src/main/java/org/apache/maven/plugins/jar/AbstractJarMojo.java:
##########
@@ -207,167 +205,208 @@ protected final Log getLog() {
     protected abstract String getType();
 
     /**
-     * Returns the JAR file to generate, based on an optional classifier.
+     * {@return the scope of dependencies}
+     * It should be {@link PathScope#MAIN_COMPILE} or {@link PathScope#TEST_COMPILE}.
+     * Note that we use compile scope rather than runtime scope because dependencies
+     * cannot appear in {@code requires} statement if they didn't had compile scope.
+     */
+    protected abstract PathScope getDependencyScope();
+
+    /**
+     * {@return the JAR tool to use for archiving the code}
      *
-     * @param basedir the output directory
-     * @param resultFinalName the name of the JAR file
-     * @param classifier an optional classifier
-     * @return the file to generate
+     * @throws MojoException if no JAR tool was found
+     *
+     * @since 4.0.0-beta-2
      */
-    protected Path getJarFile(Path basedir, String resultFinalName, String classifier) {
-        Objects.requireNonNull(basedir, "basedir is not allowed to be null");
-        Objects.requireNonNull(resultFinalName, "finalName is not allowed to be null");
-        String fileName = resultFinalName + (hasClassifier(classifier) ? '-' + classifier : "") + ".jar";
-        return basedir.resolve(fileName);
+    protected ToolProvider getJarTool() throws MojoException {
+        return ToolProvider.findFirst(toolId).orElseThrow(() -> new MojoException("No such \"" + toolId + "\" tool."));
     }
 
     /**
-     * Generates the JAR.
+     * Returns the output time stamp or, as a fallback, the {@code SOURCE_DATE_EPOCH} environment variable.
+     * If the time stamp is expressed in seconds, it is converted to ISO 8601 format. Otherwise it is returned as-is.
      *
-     * @return the path to the created archive file
-     * @throws MojoException in case of an error
+     * @return the time stamp in presumed ISO 8601 format, or {@code null} if none
+     *
+     * @since 4.0.0-beta-2
      */
-    public Path createArchive() throws MojoException {
-        Path basedir = outputDirectory != null
-                ? outputDirectory
-                : Path.of(project.getBuild().getDirectory());
-        String resultFinalName =
-                finalName != null ? finalName : project.getBuild().getFinalName();
-        Path jarFile = getJarFile(basedir, resultFinalName, getClassifier());
-
-        FileSetManager fileSetManager = new FileSetManager();
-        FileSet jarContentFileSet = new FileSet();
-        jarContentFileSet.setDirectory(getClassesDirectory().toAbsolutePath().toString());
-        jarContentFileSet.setIncludes(Arrays.asList(getIncludes()));
-        jarContentFileSet.setExcludes(Arrays.asList(getExcludes()));
-
-        String[] includedFiles = fileSetManager.getIncludedFiles(jarContentFileSet);
-
-        if (detectMultiReleaseJar
-                && Arrays.stream(includedFiles)
-                        .anyMatch(
-                                p -> p.startsWith("META-INF" + File.separatorChar + "versions" + File.separatorChar))) {
-            getLog().debug("Adding 'Multi-Release: true' manifest entry.");
-            archive.addManifestEntry(Attributes.Name.MULTI_RELEASE.toString(), "true");
+    protected String getOutputTimestamp() {
+        String time = nullIfAbsent(outputTimestamp);
+        if (time == null) {
+            time = nullIfAbsent(System.getenv("SOURCE_DATE_EPOCH"));
+            if (time == null) {
+                return null;
+            }
         }
+        if (Runtime.version().feature() < ToolExecutor.JDK_SUPPORT_DATE) {

Review Comment:
   I think I agree this should be a hard fail



##########
src/main/java/org/apache/maven/plugins/jar/AbstractJarMojo.java:
##########
@@ -207,167 +205,208 @@ protected final Log getLog() {
     protected abstract String getType();
 
     /**
-     * Returns the JAR file to generate, based on an optional classifier.
+     * {@return the scope of dependencies}
+     * It should be {@link PathScope#MAIN_COMPILE} or {@link PathScope#TEST_COMPILE}.
+     * Note that we use compile scope rather than runtime scope because dependencies
+     * cannot appear in {@code requires} statement if they didn't had compile scope.

Review Comment:
   didn't had --> don't have



##########
src/main/java/org/apache/maven/plugins/jar/AbstractJarMojo.java:
##########
@@ -207,167 +205,208 @@ protected final Log getLog() {
     protected abstract String getType();
 
     /**
-     * Returns the JAR file to generate, based on an optional classifier.
+     * {@return the scope of dependencies}
+     * It should be {@link PathScope#MAIN_COMPILE} or {@link PathScope#TEST_COMPILE}.
+     * Note that we use compile scope rather than runtime scope because dependencies
+     * cannot appear in {@code requires} statement if they didn't had compile scope.
+     */
+    protected abstract PathScope getDependencyScope();
+
+    /**
+     * {@return the JAR tool to use for archiving the code}
      *
-     * @param basedir the output directory
-     * @param resultFinalName the name of the JAR file
-     * @param classifier an optional classifier
-     * @return the file to generate
+     * @throws MojoException if no JAR tool was found
+     *
+     * @since 4.0.0-beta-2
      */
-    protected Path getJarFile(Path basedir, String resultFinalName, String classifier) {
-        Objects.requireNonNull(basedir, "basedir is not allowed to be null");
-        Objects.requireNonNull(resultFinalName, "finalName is not allowed to be null");
-        String fileName = resultFinalName + (hasClassifier(classifier) ? '-' + classifier : "") + ".jar";
-        return basedir.resolve(fileName);
+    protected ToolProvider getJarTool() throws MojoException {
+        return ToolProvider.findFirst(toolId).orElseThrow(() -> new MojoException("No such \"" + toolId + "\" tool."));
     }
 
     /**
-     * Generates the JAR.
+     * Returns the output time stamp or, as a fallback, the {@code SOURCE_DATE_EPOCH} environment variable.
+     * If the time stamp is expressed in seconds, it is converted to ISO 8601 format. Otherwise it is returned as-is.
      *
-     * @return the path to the created archive file
-     * @throws MojoException in case of an error
+     * @return the time stamp in presumed ISO 8601 format, or {@code null} if none
+     *
+     * @since 4.0.0-beta-2
      */
-    public Path createArchive() throws MojoException {
-        Path basedir = outputDirectory != null
-                ? outputDirectory
-                : Path.of(project.getBuild().getDirectory());
-        String resultFinalName =
-                finalName != null ? finalName : project.getBuild().getFinalName();
-        Path jarFile = getJarFile(basedir, resultFinalName, getClassifier());
-
-        FileSetManager fileSetManager = new FileSetManager();
-        FileSet jarContentFileSet = new FileSet();
-        jarContentFileSet.setDirectory(getClassesDirectory().toAbsolutePath().toString());
-        jarContentFileSet.setIncludes(Arrays.asList(getIncludes()));
-        jarContentFileSet.setExcludes(Arrays.asList(getExcludes()));
-
-        String[] includedFiles = fileSetManager.getIncludedFiles(jarContentFileSet);
-
-        if (detectMultiReleaseJar
-                && Arrays.stream(includedFiles)
-                        .anyMatch(
-                                p -> p.startsWith("META-INF" + File.separatorChar + "versions" + File.separatorChar))) {
-            getLog().debug("Adding 'Multi-Release: true' manifest entry.");
-            archive.addManifestEntry(Attributes.Name.MULTI_RELEASE.toString(), "true");
+    protected String getOutputTimestamp() {
+        String time = nullIfAbsent(outputTimestamp);
+        if (time == null) {
+            time = nullIfAbsent(System.getenv("SOURCE_DATE_EPOCH"));
+            if (time == null) {
+                return null;
+            }
         }
+        if (Runtime.version().feature() < ToolExecutor.JDK_SUPPORT_DATE) {
+            log.warn("Reproducible build requires Java " + ToolExecutor.JDK_SUPPORT_DATE + " or later.");
+            return null;
+        }
+        for (int i = time.length(); --i >= 0; ) {
+            char c = time.charAt(i);
+            if ((c < '0' || c > '9') && (i != 0 || c != '-')) {
+                return time;
+            }
+        }
+        return Instant.ofEpochSecond(Long.parseLong(time)).toString();
+    }
 
-        // May give false positives if the files is named as module descriptor
-        // but is not in the root of the archive or in the versioned area
-        // (and hence not actually a module descriptor).
-        // That is fine since the modular Jar archiver will gracefully
-        // handle such case.
-        // And also such case is unlikely to happen as file ending
-        // with "module-info.class" is unlikely to be included in Jar file
-        // unless it is a module descriptor.
-        boolean containsModuleDescriptor =
-                Arrays.stream(includedFiles).anyMatch(p -> p.endsWith(MODULE_DESCRIPTOR_FILE_NAME));
-
-        String archiverName = containsModuleDescriptor ? "mjar" : "jar";
+    /**
+     * {@return the patterns of files to include, or an empty list if no include pattern was specified}
+     */
+    protected List<String> getIncludes() {

Review Comment:
   do these have to be protected? Maybe even could be private?



##########
src/main/java/org/apache/maven/plugins/jar/AbstractJarMojo.java:
##########
@@ -207,167 +205,208 @@ protected final Log getLog() {
     protected abstract String getType();
 
     /**
-     * Returns the JAR file to generate, based on an optional classifier.
+     * {@return the scope of dependencies}
+     * It should be {@link PathScope#MAIN_COMPILE} or {@link PathScope#TEST_COMPILE}.
+     * Note that we use compile scope rather than runtime scope because dependencies
+     * cannot appear in {@code requires} statement if they didn't had compile scope.
+     */
+    protected abstract PathScope getDependencyScope();

Review Comment:
   do these methods need to be protected? would package access suffice?



##########
src/main/java/org/apache/maven/plugins/jar/AbstractJarMojo.java:
##########
@@ -207,167 +205,208 @@ protected final Log getLog() {
     protected abstract String getType();
 
     /**
-     * Returns the JAR file to generate, based on an optional classifier.
+     * {@return the scope of dependencies}
+     * It should be {@link PathScope#MAIN_COMPILE} or {@link PathScope#TEST_COMPILE}.
+     * Note that we use compile scope rather than runtime scope because dependencies
+     * cannot appear in {@code requires} statement if they didn't had compile scope.
+     */
+    protected abstract PathScope getDependencyScope();
+
+    /**
+     * {@return the JAR tool to use for archiving the code}
      *
-     * @param basedir the output directory
-     * @param resultFinalName the name of the JAR file
-     * @param classifier an optional classifier
-     * @return the file to generate
+     * @throws MojoException if no JAR tool was found
+     *
+     * @since 4.0.0-beta-2
      */
-    protected Path getJarFile(Path basedir, String resultFinalName, String classifier) {
-        Objects.requireNonNull(basedir, "basedir is not allowed to be null");
-        Objects.requireNonNull(resultFinalName, "finalName is not allowed to be null");
-        String fileName = resultFinalName + (hasClassifier(classifier) ? '-' + classifier : "") + ".jar";
-        return basedir.resolve(fileName);
+    protected ToolProvider getJarTool() throws MojoException {
+        return ToolProvider.findFirst(toolId).orElseThrow(() -> new MojoException("No such \"" + toolId + "\" tool."));
     }
 
     /**
-     * Generates the JAR.
+     * Returns the output time stamp or, as a fallback, the {@code SOURCE_DATE_EPOCH} environment variable.
+     * If the time stamp is expressed in seconds, it is converted to ISO 8601 format. Otherwise it is returned as-is.
      *
-     * @return the path to the created archive file
-     * @throws MojoException in case of an error
+     * @return the time stamp in presumed ISO 8601 format, or {@code null} if none
+     *
+     * @since 4.0.0-beta-2
      */
-    public Path createArchive() throws MojoException {
-        Path basedir = outputDirectory != null
-                ? outputDirectory
-                : Path.of(project.getBuild().getDirectory());
-        String resultFinalName =
-                finalName != null ? finalName : project.getBuild().getFinalName();
-        Path jarFile = getJarFile(basedir, resultFinalName, getClassifier());
-
-        FileSetManager fileSetManager = new FileSetManager();
-        FileSet jarContentFileSet = new FileSet();
-        jarContentFileSet.setDirectory(getClassesDirectory().toAbsolutePath().toString());
-        jarContentFileSet.setIncludes(Arrays.asList(getIncludes()));
-        jarContentFileSet.setExcludes(Arrays.asList(getExcludes()));
-
-        String[] includedFiles = fileSetManager.getIncludedFiles(jarContentFileSet);
-
-        if (detectMultiReleaseJar
-                && Arrays.stream(includedFiles)
-                        .anyMatch(
-                                p -> p.startsWith("META-INF" + File.separatorChar + "versions" + File.separatorChar))) {
-            getLog().debug("Adding 'Multi-Release: true' manifest entry.");
-            archive.addManifestEntry(Attributes.Name.MULTI_RELEASE.toString(), "true");
+    protected String getOutputTimestamp() {
+        String time = nullIfAbsent(outputTimestamp);
+        if (time == null) {
+            time = nullIfAbsent(System.getenv("SOURCE_DATE_EPOCH"));
+            if (time == null) {
+                return null;
+            }
         }
+        if (Runtime.version().feature() < ToolExecutor.JDK_SUPPORT_DATE) {
+            log.warn("Reproducible build requires Java " + ToolExecutor.JDK_SUPPORT_DATE + " or later.");
+            return null;
+        }
+        for (int i = time.length(); --i >= 0; ) {
+            char c = time.charAt(i);
+            if ((c < '0' || c > '9') && (i != 0 || c != '-')) {
+                return time;
+            }
+        }
+        return Instant.ofEpochSecond(Long.parseLong(time)).toString();
+    }
 
-        // May give false positives if the files is named as module descriptor
-        // but is not in the root of the archive or in the versioned area
-        // (and hence not actually a module descriptor).
-        // That is fine since the modular Jar archiver will gracefully
-        // handle such case.
-        // And also such case is unlikely to happen as file ending
-        // with "module-info.class" is unlikely to be included in Jar file
-        // unless it is a module descriptor.
-        boolean containsModuleDescriptor =
-                Arrays.stream(includedFiles).anyMatch(p -> p.endsWith(MODULE_DESCRIPTOR_FILE_NAME));
-
-        String archiverName = containsModuleDescriptor ? "mjar" : "jar";
+    /**
+     * {@return the patterns of files to include, or an empty list if no include pattern was specified}
+     */
+    protected List<String> getIncludes() {
+        return asList(includes);
+    }
 
-        MavenArchiver archiver = new MavenArchiver();
-        archiver.setCreatedBy("Maven JAR Plugin", "org.apache.maven.plugins", "maven-jar-plugin");
-        archiver.setBuildJdkSpecDefaultEntry(archive.getManifest().isAddBuildEnvironmentEntries());
-        archiver.setArchiver((JarArchiver) archivers.get(archiverName));
-        archiver.setOutputFile(jarFile.toFile());
+    /**
+     * {@return the patterns of files to exclude, or an empty list if no exclude pattern was specified}
+     */
+    protected List<String> getExcludes() {
+        return asList(excludes);
+    }
 
-        // configure for Reproducible Builds based on outputTimestamp value
-        archiver.configureReproducibleBuild(outputTimestamp);
+    /**
+     * Returns the output directory and ensures that the directory exists.
+     * The returned directory will be either {@link #outputDirectory} if non-null,
+     * or {@link org.apache.maven.api.model.Build#getDirectory()} otherwise.
+     *
+     * <p>The directory is usually {@code target} and should always exist since it is usually the output
+     * of the compiler plugin. If nevertheless the directory does not exist, then this method creates it.
+     * However, this method does not try to create the parent directory, which should be the Maven sub-project.</p>
+     *
+     * @return the directory containing the generated <abbr>JAR</abbr> files.
+     * @throws IOException if the output directory did not existed and could not be created

Review Comment:
   did not exist



##########
src/main/java/org/apache/maven/plugins/jar/AbstractJarMojo.java:
##########
@@ -207,167 +205,208 @@ protected final Log getLog() {
     protected abstract String getType();
 
     /**
-     * Returns the JAR file to generate, based on an optional classifier.
+     * {@return the scope of dependencies}
+     * It should be {@link PathScope#MAIN_COMPILE} or {@link PathScope#TEST_COMPILE}.
+     * Note that we use compile scope rather than runtime scope because dependencies
+     * cannot appear in {@code requires} statement if they didn't had compile scope.
+     */
+    protected abstract PathScope getDependencyScope();
+
+    /**
+     * {@return the JAR tool to use for archiving the code}
      *
-     * @param basedir the output directory
-     * @param resultFinalName the name of the JAR file
-     * @param classifier an optional classifier
-     * @return the file to generate
+     * @throws MojoException if no JAR tool was found
+     *
+     * @since 4.0.0-beta-2
      */
-    protected Path getJarFile(Path basedir, String resultFinalName, String classifier) {
-        Objects.requireNonNull(basedir, "basedir is not allowed to be null");
-        Objects.requireNonNull(resultFinalName, "finalName is not allowed to be null");
-        String fileName = resultFinalName + (hasClassifier(classifier) ? '-' + classifier : "") + ".jar";
-        return basedir.resolve(fileName);
+    protected ToolProvider getJarTool() throws MojoException {
+        return ToolProvider.findFirst(toolId).orElseThrow(() -> new MojoException("No such \"" + toolId + "\" tool."));
     }
 
     /**
-     * Generates the JAR.
+     * Returns the output time stamp or, as a fallback, the {@code SOURCE_DATE_EPOCH} environment variable.
+     * If the time stamp is expressed in seconds, it is converted to ISO 8601 format. Otherwise it is returned as-is.
      *
-     * @return the path to the created archive file
-     * @throws MojoException in case of an error
+     * @return the time stamp in presumed ISO 8601 format, or {@code null} if none
+     *
+     * @since 4.0.0-beta-2
      */
-    public Path createArchive() throws MojoException {
-        Path basedir = outputDirectory != null
-                ? outputDirectory
-                : Path.of(project.getBuild().getDirectory());
-        String resultFinalName =
-                finalName != null ? finalName : project.getBuild().getFinalName();
-        Path jarFile = getJarFile(basedir, resultFinalName, getClassifier());
-
-        FileSetManager fileSetManager = new FileSetManager();
-        FileSet jarContentFileSet = new FileSet();
-        jarContentFileSet.setDirectory(getClassesDirectory().toAbsolutePath().toString());
-        jarContentFileSet.setIncludes(Arrays.asList(getIncludes()));
-        jarContentFileSet.setExcludes(Arrays.asList(getExcludes()));
-
-        String[] includedFiles = fileSetManager.getIncludedFiles(jarContentFileSet);
-
-        if (detectMultiReleaseJar
-                && Arrays.stream(includedFiles)
-                        .anyMatch(
-                                p -> p.startsWith("META-INF" + File.separatorChar + "versions" + File.separatorChar))) {
-            getLog().debug("Adding 'Multi-Release: true' manifest entry.");
-            archive.addManifestEntry(Attributes.Name.MULTI_RELEASE.toString(), "true");
+    protected String getOutputTimestamp() {
+        String time = nullIfAbsent(outputTimestamp);
+        if (time == null) {
+            time = nullIfAbsent(System.getenv("SOURCE_DATE_EPOCH"));
+            if (time == null) {
+                return null;
+            }
         }
+        if (Runtime.version().feature() < ToolExecutor.JDK_SUPPORT_DATE) {
+            log.warn("Reproducible build requires Java " + ToolExecutor.JDK_SUPPORT_DATE + " or later.");
+            return null;
+        }
+        for (int i = time.length(); --i >= 0; ) {
+            char c = time.charAt(i);
+            if ((c < '0' || c > '9') && (i != 0 || c != '-')) {
+                return time;
+            }
+        }
+        return Instant.ofEpochSecond(Long.parseLong(time)).toString();
+    }
 
-        // May give false positives if the files is named as module descriptor
-        // but is not in the root of the archive or in the versioned area
-        // (and hence not actually a module descriptor).
-        // That is fine since the modular Jar archiver will gracefully
-        // handle such case.
-        // And also such case is unlikely to happen as file ending
-        // with "module-info.class" is unlikely to be included in Jar file
-        // unless it is a module descriptor.
-        boolean containsModuleDescriptor =
-                Arrays.stream(includedFiles).anyMatch(p -> p.endsWith(MODULE_DESCRIPTOR_FILE_NAME));
-
-        String archiverName = containsModuleDescriptor ? "mjar" : "jar";
+    /**
+     * {@return the patterns of files to include, or an empty list if no include pattern was specified}
+     */
+    protected List<String> getIncludes() {
+        return asList(includes);
+    }
 
-        MavenArchiver archiver = new MavenArchiver();
-        archiver.setCreatedBy("Maven JAR Plugin", "org.apache.maven.plugins", "maven-jar-plugin");
-        archiver.setBuildJdkSpecDefaultEntry(archive.getManifest().isAddBuildEnvironmentEntries());
-        archiver.setArchiver((JarArchiver) archivers.get(archiverName));
-        archiver.setOutputFile(jarFile.toFile());
+    /**
+     * {@return the patterns of files to exclude, or an empty list if no exclude pattern was specified}
+     */
+    protected List<String> getExcludes() {
+        return asList(excludes);
+    }
 
-        // configure for Reproducible Builds based on outputTimestamp value
-        archiver.configureReproducibleBuild(outputTimestamp);
+    /**
+     * Returns the output directory and ensures that the directory exists.
+     * The returned directory will be either {@link #outputDirectory} if non-null,
+     * or {@link org.apache.maven.api.model.Build#getDirectory()} otherwise.
+     *
+     * <p>The directory is usually {@code target} and should always exist since it is usually the output
+     * of the compiler plugin. If nevertheless the directory does not exist, then this method creates it.
+     * However, this method does not try to create the parent directory, which should be the Maven sub-project.</p>
+     *
+     * @return the directory containing the generated <abbr>JAR</abbr> files.
+     * @throws IOException if the output directory did not existed and could not be created
+     */
+    protected Path getOutputDirectory() throws IOException {
+        Path dir = outputDirectory;
+        if (dir == null) {
+            dir = Path.of(project.getBuild().getDirectory());
+        }
+        if (Files.notExists(dir)) {
+            dir = Files.createDirectory(dir);
+        }
+        return dir;
+    }
 
-        archive.setForced(forceCreation);
+    /**
+     * Returns the given elements as a list if non-null.
+     *
+     * @param elements the elements, or {@code null}
+     * @return the elements as a list, or {@code null} if the given array was null
+     */
+    private static List<String> asList(String[] elements) {
+        return (elements == null) ? List.of() : Arrays.asList(elements);
+    }
 
-        try {
-            Path contentDirectory = getClassesDirectory();
-            if (!Files.exists(contentDirectory)) {
-                if (!forceCreation) {
-                    getLog().warn("JAR will be empty - no content was marked for inclusion!");
-                }
-            } else {
-                archiver.getArchiver().addDirectory(contentDirectory.toFile(), getIncludes(), getExcludes());
+    /**
+     * Generates the <abbr>JAR</abbr> files.
+     * Map keys are module names or {@code null} if the project does not use module hierarchy.
+     * Values are (<var>type</var>, <var>path</var>) pairs associated with each module where
+     * <var>type</var> is {@code "pom"}, {@code "jar"} or {@code "test-jar"} and <var>path</var>
+     * is the path to the <abbr>POM</abbr> or <abbr>JAR</abbr> file.
+     *
+     * <p>Note that a null key does not necessarily means that the <abbr>JAR</abbr> is not modular.
+     * It only means that the project was not compiled with module hierarchy,
+     * i.e. {@code target/classes/} subdirectories having module names.

Review Comment:
   avoid latin
   i.e. --> that is



##########
src/main/java/org/apache/maven/plugins/jar/Archive.java:
##########
@@ -0,0 +1,692 @@
+/*
+ * 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.jar;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.TreeMap;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.Type;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.MojoException;
+
+/**
+ * Files or root directories to archive for a single module.
+ * A single instance of {@code Archive} may contain many directories for different target Java releases.
+ * Many instances of {@code Archive} may exist when archiving a multi-modules project.
+ */
+final class Archive {
+    /**
+     * Whether to repeat the {@code -C} option before each file.
+     * Doing so makes the command-line very verbose while the documentation of
+     * <a href="https://docs.oracle.com/en/java/javase/25/docs/specs/man/jar.html">The jar Command</a>
+     * gives the impression that this option can be provided only once.
+     * However, our tests suggest that the first file after the directory specified by the {@code -C} option
+     * must be relative to that directory and all files after the first one must be prefixed by the directory
+     * which was specified in the {@code -C} option. This behavior is not documented, but we couldn't get the
+     * {@code jar} tool to work otherwise (except by repeating {@code -C} before each file).
+     * Furthermore, it seems that the relativized file needs to be the shortest one,
+     * otherwise the {@code jar} tool rejects files after the first one with "names do not match".
+     * Which file is first depends on the unspecified directory-iteration order.
+     *
+     * <p>If this flag is {@code true}, the plugin repeats {@code -C} before each file.
+     * This flag should be set to {@code false} if a future version of the {@code jar}
+     * tool allows to specify {@code -C} only once.</p>
+     *
+     * <p><b>Historical note:</b> we also tried to relativize only the first file after {@code -C}
+     * and keep all subsequent files as absolute. It works, but because we have to repeat the directory
+     * in the file name, it saves only 3 or 4 characters per file compared to repeating {@code -C}.</p>
+     */
+    private static final boolean REPEAT_C = true;
+
+    /**
+     * Path to the <abbr>POM</abbr> file generated for this archive, or {@code null} if none.
+     * This is non-null only if module source hierarchy is used, in which case the dependencies
+     * declared in this file are the intersection of the project dependencies and the content of
+     * the {@code module-info.class} file.
+     */
+    @Nullable
+    Path pomFile;
+
+    /**
+     * The <var>JAR</var> file to create. May be an existing file,
+     * in which case the file creation may be skipped if the file is still up-to-date.
+     */
+    @Nonnull
+    final Path jarFile;
+
+    /**
+     * A helper class for checking whether an existing <abbr>JAR</abbr> file is still up-to-date.
+     * This is null if there is no existing JAR file, or if we determined that the file is outdated.
+     */
+    private TimestampCheck existingJAR;
+
+    /**
+     * Name of the module being archived when the project is using module hierarchy.
+     * This is {@code null} if the project is using package hierarchy, either because it is a classical
+     * class-path project or because it is a single module compiled without using the module hierarchy.
+     * When using module source hierarchy, {@code javac} guarantees that the module name in the output
+     * directory is the name of the parent directory of {@code module-info.class}.
+     */
+    @Nullable
+    final String moduleName;
+
+    /**
+     * Path to {@code META-INF/MANIFEST.MF}, or {@code null} if none.
+     * If non-null, this value will be given to the {@code --manifest} option.
+     * The use of this option is preferable to adding {@code MANIFEST.MF} as an ordinary file.
+     *
+     * @see #setManifest(Path, boolean)
+     * @see #mergeManifest(Path, Manifest)
+     */
+    @Nullable
+    private Path manifest;
+
+    /**
+     * The Maven generated {@code pom.xml} and {@code pom.properties} files, or {@code null} if none.
+     * This first item shall be the base directory where the files are located.
+     */
+    @Nullable
+    List<Path> mavenFiles;
+
+    /**
+     * Fully-qualified name of the main class, or {@code null} if none.
+     * This is the value to provide to the {@code --main-class} option.
+     */
+    private String mainClass;
+
+    /**
+     * Files or root directories to store in the <abbr>JAR</abbr> file for each target Java release
+     * other than the base release. Keys are the target Java release with {@code null} for the base
+     * release.
+     */
+    @Nonnull
+    private final NavigableMap<Runtime.Version, FileSet> filesetForRelease;
+
+    /**
+     * Files or root directories to archive for a single target Java release of a single module.
+     * The {@link Archive} enclosing shall contain at least one instance of {@code FileSet} for
+     * the base release, and an arbitrary amount of other instances for other target releases.
+     */
+    final class FileSet {
+        /**
+         * A comparator for sorting paths in a reproducible order.
+         * This comparator assumes that all paths are relative to the same base directory (this is not verified).
+         * Note: we do not use {@link Path#compareTo(Path)} because the Javadoc said that it is platform dependent.
+         */
+        private static final Comparator<Path> REPRODUCIBLE_ORDER = (p1, p2) -> {
+            final int c1 = p1.getNameCount();
+            final int c2 = p2.getNameCount();
+            final int c = Math.min(c1, c2);
+            for (int i = 0; i < c; i++) {
+                String n1 = p1.getName(i).toString();
+                String n2 = p2.getName(i).toString();
+                int r = n1.compareTo(n2); // Case-sensitive comparison on all platforms.
+                if (r != 0) {
+                    return r;
+                }
+            }
+            return c1 - c2;
+        };
+
+        /**
+         * The root directory of all files or directories to archive.
+         * This is the value to pass to the {@code -C} tool option.
+         */
+        @Nonnull
+        final Path directory;
+
+        /**
+         * The files or directories to include in the <var>JAR</var> file.
+         * May be absolute paths or paths relative to {@link #directory}.
+         */
+        @Nonnull
+        final List<Path> files;
+
+        /**
+         * Creates an initially empty set of files or directories for a specific target Java release.
+         *
+         * @param directory the base directory of the files or directories to archive
+         */
+        private FileSet(Path directory) {
+            this.directory = directory;
+            this.files = new ArrayList<>();
+        }
+
+        /**
+         * 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.
+         * The caller should use that common directory for logging a warning message.
+         *
+         * @param base base directory found by previous invocations of this method, or {@code null} if none
+         * @return common directory of discarded files
+         */
+        private Path discardAllFiles(Path base) {
+            for (Path file : files) {
+                file = directory.resolve(file);
+                if (base == null) {
+                    base = file.getParent();
+                } else {
+                    while (!file.startsWith(base)) {
+                        base = base.getParent();
+                        if (base == null) {
+                            break;
+                        }
+                    }
+                }
+            }
+            files.clear();
+            return base;
+        }
+
+        /**
+         * Adds the given path to the list of files or directories to archive.
+         * This method may store a relative path instead of the absolute path.
+         *
+         * @param item a file or directory to archive
+         * @param attributes the file's basic attributes
+         * @param isDirectory whether the file is a directory
+         * @throws IllegalArgumentException if the given path cannot be made relative to the base directory
+         */
+        void add(Path item, BasicFileAttributes attributes, boolean isDirectory) {
+            TimestampCheck tc = existingJAR;
+            if (tc != null && tc.isUpdated(item, attributes, isDirectory)) {
+                existingJAR = null; // Signal that the existing file is outdated.
+            }
+            item = directory.relativize(item);
+            if (item.getNameCount() <= 1 && item.toString().isEmpty()) {
+                /*
+                 * The item is the `-C` directory itself (e.g. a `META-INF/versions/<n>` directory
+                 * added as a whole). An empty file argument is invalid for the `jar` tool
+                 * (some implementations reject it, others silently misbehave),
+                 * so archive the whole directory content with ".".
+                 */
+                item = Path.of(".");
+            }
+            files.add(item);
+        }
+
+        /**
+         * Adds to the given list the arguments to provide to the "jar" tool for this version.
+         * Elements added to the list shall be instances of {@link String} or {@link Path}.
+         *
+         * @param addTo the list where to add the arguments as {@link String} or {@link Path} instances
+         * @param version the target Java release, or {@code null} for the base version of the <abbr>JAR</abbr> file
+         */
+        private void arguments(List<Object> addTo, Runtime.Version version) {
+            if (!files.isEmpty()) {
+                if (version != null) {
+                    addTo.add("--release");
+                    addTo.add(version);
+                }
+                if (isReproducible) {
+                    files.sort(REPRODUCIBLE_ORDER);
+                }
+                if (REPEAT_C) {
+                    for (Path file : files) {
+                        addTo.add("-C");
+                        addTo.add(directory);
+                        addTo.add(file);
+                    }
+                } else {
+                    addTo.add("-C");
+                    addTo.add(directory);
+                    addTo.addAll(files);
+                }
+            }
+        }
+
+        /**
+         * {@return a string representation for debugging purposes}
+         */
+        @Override
+        public String toString() {
+            return getClass().getSimpleName() + '[' + directory.getFileName() + ": " + files.size() + " files]";
+        }
+    }
+
+    /**
+     * Whether reproducible build was requested.
+     */
+    private final boolean isReproducible;
+
+    /**
+     * Creates an initially empty set of files or directories.
+     *
+     * @param jarFile path to the <abbr>JAR</abbr> file to create
+     * @param moduleName the module name if using module hierarchy, or {@code null} if using package hierarchy
+     * @param version the target Java release, or {@code null} for the base version
+     * @param directory the directory of the classes targeting the base Java release
+     * @param forceCreation whether to force a new <abbr>JAR</abbr> file even if the content seems unchanged
+     * @param isReproducible whether reproducible build was requested
+     * @param logger where to send a warning if an error occurred while checking an existing <abbr>JAR</abbr> file
+     */
+    @SuppressWarnings("checkstyle:NeedBraces")
+    Archive(
+            final Path jarFile,
+            final String moduleName,
+            final Runtime.Version version,
+            final Path directory,
+            final boolean forceCreation,
+            final boolean isReproducible,
+            final Log logger) {
+        this.jarFile = jarFile;
+        this.moduleName = moduleName;
+        this.isReproducible = isReproducible;
+        filesetForRelease = new TreeMap<>((v1, v2) -> {
+            if (v1 == v2) return 0;
+            if (v1 == null) return -1;
+            if (v2 == null) return +1;
+            return v1.compareTo(v2);
+        });
+        filesetForRelease.put(version, new FileSet(directory));
+        if (!forceCreation && Files.isRegularFile(jarFile)) {
+            try {
+                existingJAR = new TimestampCheck(jarFile, directory, logger);
+            } catch (IOException e) {
+                // Ignore, we will regenerate the JAR file.
+                logger.warn(e);
+            }
+        }
+    }
+
+    /**
+     * {@return the files or directories to store in the <abbr>JAR</abbr> file for targeting the base Java release}
+     *
+     * @throws NoSuchElementException should not happen unless {@link #prune(boolean)} has been invoked
+     */
+    FileSet baseRelease() {
+        Map.Entry<Runtime.Version, FileSet> entry = filesetForRelease.firstEntry();
+        String message = null;
+        if (entry != null) {
+            Runtime.Version version = entry.getKey();
+            if (version == null) {
+                return entry.getValue();
+            }
+            message = "Expected base version but found version " + version;
+        }
+        throw new NoSuchElementException(message);
+    }
+
+    /**
+     * Returns the {@code module-info.class} files. Conceptually, there is at most once such file per module.
+     * However, more than one file may exist if additional files are provided for additional Java releases.
+     * This method returns only the files that exist.
+     *
+     * @return all {@code module-info.class} files found for all target Java releases
+     */
+    public List<Path> moduleInfoFiles() {
+        var files = new ArrayList<Path>();
+        filesetForRelease.values().forEach((release) -> {
+            Path file = release.directory.resolve(FileCollector.MODULE_DESCRIPTOR_FILE_NAME);
+            if (Files.isRegularFile(file)) {
+                files.add(file);
+            }
+        });
+        return files;
+    }
+
+    /**
+     * Discards all files in this archive, normally because those files are not in any module.
+     * This method returns a common parent directory for all the files that were discarded.
+     * The caller should use that common directory for logging a warning message.
+     *
+     * @return common directory of discarded files, or {@code null} if none
+     */
+    Path discardAllFiles() {
+        Path base = null;
+        for (FileSet release : filesetForRelease.values()) {
+            base = release.discardAllFiles(base);
+        }
+        filesetForRelease.clear();
+        return base;
+    }
+
+    /**
+     * Removes all empty file sets 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}, then this method ensures that at least one file set
+     * remains even if that file set is empty.
+     *
+     * @param skipIfEmpty value of {@link AbstractJarMojo#skipIfEmpty}
+     */
+    public void prune(final boolean skipIfEmpty) {
+        FileSet keep = (skipIfEmpty || isEmpty())
+                ? null
+                : filesetForRelease.firstEntry().getValue();
+        filesetForRelease.values().removeIf((fs) -> fs.files.isEmpty());
+        Iterator<Map.Entry<Runtime.Version, FileSet>> it =
+                filesetForRelease.entrySet().iterator();
+        if (it.hasNext()) {
+            Map.Entry<Runtime.Version, FileSet> first = it.next();
+            if (first.getKey() == null) {
+                return; // Already contains an entry for the base version, nothing to do.
+            }
+            keep = first.getValue();
+            it.remove();
+        }
+        if (keep != null) {
+            filesetForRelease.put(null, keep);
+        }
+    }
+
+    /**
+     * {@return whether this archive has nothing to archive}
+     * Note that this method may return {@code false} even when there is zero file to archive.
+     * It may happen if {@link AbstractJarMojo#skipIfEmpty} is {@code false}. In such case, the
+     * "empty" <abbr>JAR</abbr> file will still contain at {@code META-INF/MANIFEST.MF} file.
+     *
+     * <h4>Prerequisites</h4>
+     * The {@link #prune(boolean)} method should be invoked before this method for accurate result.
+     */
+    public boolean isEmpty() {
+        return filesetForRelease.isEmpty();
+    }
+
+    /**
+     * Checks whether the <abbr>JAR</abbr> file already exists and can be reused.
+     * This method verifies that the <abbr>JAR</abbr> file contains all the files to archive,
+     * contains no extra file, and no file to archive is newer than the <abbr>JAR</abbr> file.
+     *
+     * <p>This method can be invoked only once.
+     * If invoked more often, it returns {@code false} on all subsequent invocations.</p>
+     *
+     * @return whether the <abbr>JAR</abbr> file already exists and can be reused
+     */
+    public boolean isUpToDateJAR() {
+        final TimestampCheck tc = existingJAR;
+        if (tc == null) {
+            return false;
+        }
+        existingJAR = null; // Let GC do its job.
+        return tc.isUpToDateJAR(filesetForRelease.values());
+    }
+
+    /**
+     * Returns an initially empty set of files or directories for the specified target Java release.
+     *
+     * @param directory the base directory of the files to archive
+     * @param version the target Java release, or {@code null} for the base version
+     * @return container where to declare files and directories to archive
+     */
+    FileSet newTargetRelease(Path directory, Runtime.Version version) {
+        return filesetForRelease.computeIfAbsent(version, (key) -> new FileSet(directory));
+    }
+
+    /**
+     * Sets the {@code --main-class} option to the value of the {@code Main-Class} entry of the given manifest.
+     * As an extension, this method accepts the {@code module/classname} syntax (a syntax already used in some
+     * Java tools). If a module is specified, the main class is kept only if the module match. The intent is to
+     * allow users to specify on which module the main class applies when they use plugin configuration.
+     *
+     * <p>This method may modify the {@code content} manifest. Caller shall ensure that the given manifest
+     * is not a shared instance. This method returns whether a change has actually been done.</p>
+     *
+     * @param content combination of existing {@code MANIFEST.MF} and manifest inferred from configuration, or null
+     * @return whether the given manifest has been modified by this method
+     */
+    boolean setMainClass(Manifest content) {
+        if (content == null || mainClass != null) {
+            return false;
+        }
+        // We need to remove the attribute, otherwise it will conflict with `--main-class`.
+        mainClass = (String) content.getMainAttributes().remove(Attributes.Name.MAIN_CLASS);
+        if (mainClass != null) {
+            int s = mainClass.indexOf('/');
+            if (s >= 0) {
+                if (mainClass.substring(0, s).strip().equals(moduleName)) {
+                    mainClass = mainClass.substring(s + 1).strip();
+                } else {
+                    mainClass = null; // Main class is defined for another module.
+                }
+            }
+        }
+        return mainClass != null;
+    }
+
+    /**
+     * Sets the {@code --manifest} option to the given value if that option was not already set.
+     *
+     * @param file path to the manifest file
+     * @param force whether to set the manifest even if already set
+     * @return whether the manifest has been set
+     */
+    boolean setManifest(Path file, boolean force) {
+        if (manifest == null || force) {
+            manifest = file;
+            return true;
+        }
+        return false;
+    }
+
+    /**
+     * Merges the manifest of this module with the manifest specified in plugin configuration.
+     * If both {@code file} and {@code content} are non-null, then {@code content} must be the
+     * result of reading {@code file}.
+     *
+     * <p>This method never modifies the given {@code content} object. If manifest are merged,
+     * a new {@link Manifest} instance is created. Therefore, caller can check whether this
+     * method returned a new instance as a way to recognize that a merge occurred.</p>
+     *
+     * <p>If a merge occurs, the content specified to {@link #setManifest(Path)} has precedence.
+     * It should be the {@code target/classes/META-INF/MANIFEST.MF} file (or modular equivalent).</p>
+     *
+     * @param  file     an additional manifest file, or {@code null}
+     * @param  content  the content of {@code file}, or a standalone manifest produced at runtime
+     * @return the merged manifest as a new instance if some changes were necessary
+     * @throws IOException if an error occurred while reading a manifest file
+     */
+    Manifest mergeManifest(Path file, Manifest content) throws IOException {
+        if (manifest == null) {
+            manifest = file;
+        } else if (file != null && Files.isSameFile(file, manifest)) {
+            // Nothing to merge because of the constraint that `content` must be the content of `file`.
+        } else {
+            try (InputStream in = Files.newInputStream(manifest)) {
+                // No need to wrap in `BufferedInputStream`.
+                if (content != null) {
+                    content = new Manifest(content);
+                    content.read(in);
+                } else {
+                    content = new Manifest(in);
+                }
+            }
+        }
+        return content;
+    }
+
+    /**
+     * Adds to the given list the arguments to provide to the "jar" tool for each version.
+     * Elements added to the list shall be instances of {@link String} or {@link Path}.
+     * Callers should have added the following options (if applicable) before to invoke this method:
+     *
+     * <ul>
+     *   <li>{@code --create}</li>
+     *   <li>{@code --no-compress}</li>
+     *   <li>{@code --date} followed by the output time stamp</li>
+     *   <li>{@code --module-version} followed by module version</li>
+     *   <li>{@code --hash-modules} followed by patters of module names</li>
+     *   <li>{@code --module-path} followed by module path</li>
+     * </ul>
+     *
+     * This method adds the following options:
+     *
+     * <ul>
+     *   <li>{@code --file} followed by the path to the <abbr>JAR</abbr> file</li>
+     *   <li>{@code --manifest} followed by path to the manifest file</li>
+     *   <li>{@code --main-class} followed by fully qualified name class</li>
+     *   <li>{@code --release} followed by Java target release</li>
+     *   <li>{@code -C} followed by directory</li>
+     *   <li>files or directories to archive</li>
+     * </ul>
+     *
+     * @param addTo the list where to add the arguments as {@link String} or {@link Path} instances

Review Comment:
   the list to add the arguments as {@link String} or {@link Path} instances to



##########
src/main/java/org/apache/maven/plugins/jar/Archive.java:
##########
@@ -0,0 +1,692 @@
+/*
+ * 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.jar;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.TreeMap;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.Type;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.MojoException;
+
+/**
+ * Files or root directories to archive for a single module.
+ * A single instance of {@code Archive} may contain many directories for different target Java releases.
+ * Many instances of {@code Archive} may exist when archiving a multi-modules project.
+ */
+final class Archive {
+    /**
+     * Whether to repeat the {@code -C} option before each file.
+     * Doing so makes the command-line very verbose while the documentation of
+     * <a href="https://docs.oracle.com/en/java/javase/25/docs/specs/man/jar.html">The jar Command</a>
+     * gives the impression that this option can be provided only once.
+     * However, our tests suggest that the first file after the directory specified by the {@code -C} option
+     * must be relative to that directory and all files after the first one must be prefixed by the directory
+     * which was specified in the {@code -C} option. This behavior is not documented, but we couldn't get the
+     * {@code jar} tool to work otherwise (except by repeating {@code -C} before each file).
+     * Furthermore, it seems that the relativized file needs to be the shortest one,
+     * otherwise the {@code jar} tool rejects files after the first one with "names do not match".
+     * Which file is first depends on the unspecified directory-iteration order.
+     *
+     * <p>If this flag is {@code true}, the plugin repeats {@code -C} before each file.
+     * This flag should be set to {@code false} if a future version of the {@code jar}
+     * tool allows to specify {@code -C} only once.</p>
+     *
+     * <p><b>Historical note:</b> we also tried to relativize only the first file after {@code -C}
+     * and keep all subsequent files as absolute. It works, but because we have to repeat the directory
+     * in the file name, it saves only 3 or 4 characters per file compared to repeating {@code -C}.</p>
+     */
+    private static final boolean REPEAT_C = true;
+
+    /**
+     * Path to the <abbr>POM</abbr> file generated for this archive, or {@code null} if none.
+     * This is non-null only if module source hierarchy is used, in which case the dependencies
+     * declared in this file are the intersection of the project dependencies and the content of
+     * the {@code module-info.class} file.
+     */
+    @Nullable
+    Path pomFile;
+
+    /**
+     * The <var>JAR</var> file to create. May be an existing file,
+     * in which case the file creation may be skipped if the file is still up-to-date.
+     */
+    @Nonnull
+    final Path jarFile;
+
+    /**
+     * A helper class for checking whether an existing <abbr>JAR</abbr> file is still up-to-date.
+     * This is null if there is no existing JAR file, or if we determined that the file is outdated.
+     */
+    private TimestampCheck existingJAR;
+
+    /**
+     * Name of the module being archived when the project is using module hierarchy.
+     * This is {@code null} if the project is using package hierarchy, either because it is a classical
+     * class-path project or because it is a single module compiled without using the module hierarchy.
+     * When using module source hierarchy, {@code javac} guarantees that the module name in the output
+     * directory is the name of the parent directory of {@code module-info.class}.
+     */
+    @Nullable
+    final String moduleName;
+
+    /**
+     * Path to {@code META-INF/MANIFEST.MF}, or {@code null} if none.
+     * If non-null, this value will be given to the {@code --manifest} option.
+     * The use of this option is preferable to adding {@code MANIFEST.MF} as an ordinary file.
+     *
+     * @see #setManifest(Path, boolean)
+     * @see #mergeManifest(Path, Manifest)
+     */
+    @Nullable
+    private Path manifest;
+
+    /**
+     * The Maven generated {@code pom.xml} and {@code pom.properties} files, or {@code null} if none.
+     * This first item shall be the base directory where the files are located.
+     */
+    @Nullable
+    List<Path> mavenFiles;
+
+    /**
+     * Fully-qualified name of the main class, or {@code null} if none.
+     * This is the value to provide to the {@code --main-class} option.
+     */
+    private String mainClass;
+
+    /**
+     * Files or root directories to store in the <abbr>JAR</abbr> file for each target Java release
+     * other than the base release. Keys are the target Java release with {@code null} for the base
+     * release.
+     */
+    @Nonnull
+    private final NavigableMap<Runtime.Version, FileSet> filesetForRelease;
+
+    /**
+     * Files or root directories to archive for a single target Java release of a single module.
+     * The {@link Archive} enclosing shall contain at least one instance of {@code FileSet} for
+     * the base release, and an arbitrary amount of other instances for other target releases.
+     */
+    final class FileSet {
+        /**
+         * A comparator for sorting paths in a reproducible order.
+         * This comparator assumes that all paths are relative to the same base directory (this is not verified).
+         * Note: we do not use {@link Path#compareTo(Path)} because the Javadoc said that it is platform dependent.
+         */
+        private static final Comparator<Path> REPRODUCIBLE_ORDER = (p1, p2) -> {
+            final int c1 = p1.getNameCount();
+            final int c2 = p2.getNameCount();
+            final int c = Math.min(c1, c2);
+            for (int i = 0; i < c; i++) {
+                String n1 = p1.getName(i).toString();
+                String n2 = p2.getName(i).toString();
+                int r = n1.compareTo(n2); // Case-sensitive comparison on all platforms.
+                if (r != 0) {
+                    return r;
+                }
+            }
+            return c1 - c2;
+        };
+
+        /**
+         * The root directory of all files or directories to archive.
+         * This is the value to pass to the {@code -C} tool option.
+         */
+        @Nonnull
+        final Path directory;
+
+        /**
+         * The files or directories to include in the <var>JAR</var> file.
+         * May be absolute paths or paths relative to {@link #directory}.
+         */
+        @Nonnull
+        final List<Path> files;
+
+        /**
+         * Creates an initially empty set of files or directories for a specific target Java release.
+         *
+         * @param directory the base directory of the files or directories to archive
+         */
+        private FileSet(Path directory) {
+            this.directory = directory;
+            this.files = new ArrayList<>();
+        }
+
+        /**
+         * 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.
+         * The caller should use that common directory for logging a warning message.
+         *
+         * @param base base directory found by previous invocations of this method, or {@code null} if none
+         * @return common directory of discarded files
+         */
+        private Path discardAllFiles(Path base) {
+            for (Path file : files) {
+                file = directory.resolve(file);
+                if (base == null) {
+                    base = file.getParent();
+                } else {
+                    while (!file.startsWith(base)) {
+                        base = base.getParent();
+                        if (base == null) {
+                            break;
+                        }
+                    }
+                }
+            }
+            files.clear();
+            return base;
+        }
+
+        /**
+         * Adds the given path to the list of files or directories to archive.
+         * This method may store a relative path instead of the absolute path.
+         *
+         * @param item a file or directory to archive
+         * @param attributes the file's basic attributes
+         * @param isDirectory whether the file is a directory
+         * @throws IllegalArgumentException if the given path cannot be made relative to the base directory
+         */
+        void add(Path item, BasicFileAttributes attributes, boolean isDirectory) {
+            TimestampCheck tc = existingJAR;
+            if (tc != null && tc.isUpdated(item, attributes, isDirectory)) {
+                existingJAR = null; // Signal that the existing file is outdated.
+            }
+            item = directory.relativize(item);
+            if (item.getNameCount() <= 1 && item.toString().isEmpty()) {
+                /*
+                 * The item is the `-C` directory itself (e.g. a `META-INF/versions/<n>` directory
+                 * added as a whole). An empty file argument is invalid for the `jar` tool
+                 * (some implementations reject it, others silently misbehave),
+                 * so archive the whole directory content with ".".
+                 */
+                item = Path.of(".");
+            }
+            files.add(item);
+        }
+
+        /**
+         * Adds to the given list the arguments to provide to the "jar" tool for this version.
+         * Elements added to the list shall be instances of {@link String} or {@link Path}.
+         *
+         * @param addTo the list where to add the arguments as {@link String} or {@link Path} instances
+         * @param version the target Java release, or {@code null} for the base version of the <abbr>JAR</abbr> file
+         */
+        private void arguments(List<Object> addTo, Runtime.Version version) {
+            if (!files.isEmpty()) {
+                if (version != null) {
+                    addTo.add("--release");
+                    addTo.add(version);
+                }
+                if (isReproducible) {
+                    files.sort(REPRODUCIBLE_ORDER);
+                }
+                if (REPEAT_C) {
+                    for (Path file : files) {
+                        addTo.add("-C");
+                        addTo.add(directory);
+                        addTo.add(file);
+                    }
+                } else {
+                    addTo.add("-C");
+                    addTo.add(directory);
+                    addTo.addAll(files);
+                }
+            }
+        }
+
+        /**
+         * {@return a string representation for debugging purposes}
+         */
+        @Override
+        public String toString() {
+            return getClass().getSimpleName() + '[' + directory.getFileName() + ": " + files.size() + " files]";
+        }
+    }
+
+    /**
+     * Whether reproducible build was requested.
+     */
+    private final boolean isReproducible;
+
+    /**
+     * Creates an initially empty set of files or directories.
+     *
+     * @param jarFile path to the <abbr>JAR</abbr> file to create
+     * @param moduleName the module name if using module hierarchy, or {@code null} if using package hierarchy
+     * @param version the target Java release, or {@code null} for the base version
+     * @param directory the directory of the classes targeting the base Java release
+     * @param forceCreation whether to force a new <abbr>JAR</abbr> file even if the content seems unchanged
+     * @param isReproducible whether reproducible build was requested
+     * @param logger where to send a warning if an error occurred while checking an existing <abbr>JAR</abbr> file
+     */
+    @SuppressWarnings("checkstyle:NeedBraces")

Review Comment:
   add braces and remove the ignore



##########
src/main/java/org/apache/maven/plugins/jar/Archive.java:
##########
@@ -0,0 +1,692 @@
+/*
+ * 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.jar;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.TreeMap;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.Type;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.MojoException;
+
+/**
+ * Files or root directories to archive for a single module.
+ * A single instance of {@code Archive} may contain many directories for different target Java releases.
+ * Many instances of {@code Archive} may exist when archiving a multi-modules project.
+ */
+final class Archive {
+    /**
+     * Whether to repeat the {@code -C} option before each file.
+     * Doing so makes the command-line very verbose while the documentation of
+     * <a href="https://docs.oracle.com/en/java/javase/25/docs/specs/man/jar.html">The jar Command</a>
+     * gives the impression that this option can be provided only once.
+     * However, our tests suggest that the first file after the directory specified by the {@code -C} option
+     * must be relative to that directory and all files after the first one must be prefixed by the directory
+     * which was specified in the {@code -C} option. This behavior is not documented, but we couldn't get the
+     * {@code jar} tool to work otherwise (except by repeating {@code -C} before each file).
+     * Furthermore, it seems that the relativized file needs to be the shortest one,
+     * otherwise the {@code jar} tool rejects files after the first one with "names do not match".
+     * Which file is first depends on the unspecified directory-iteration order.
+     *
+     * <p>If this flag is {@code true}, the plugin repeats {@code -C} before each file.
+     * This flag should be set to {@code false} if a future version of the {@code jar}
+     * tool allows to specify {@code -C} only once.</p>
+     *
+     * <p><b>Historical note:</b> we also tried to relativize only the first file after {@code -C}
+     * and keep all subsequent files as absolute. It works, but because we have to repeat the directory
+     * in the file name, it saves only 3 or 4 characters per file compared to repeating {@code -C}.</p>
+     */
+    private static final boolean REPEAT_C = true;
+
+    /**
+     * Path to the <abbr>POM</abbr> file generated for this archive, or {@code null} if none.
+     * This is non-null only if module source hierarchy is used, in which case the dependencies
+     * declared in this file are the intersection of the project dependencies and the content of
+     * the {@code module-info.class} file.
+     */
+    @Nullable
+    Path pomFile;
+
+    /**
+     * The <var>JAR</var> file to create. May be an existing file,
+     * in which case the file creation may be skipped if the file is still up-to-date.
+     */
+    @Nonnull
+    final Path jarFile;
+
+    /**
+     * A helper class for checking whether an existing <abbr>JAR</abbr> file is still up-to-date.
+     * This is null if there is no existing JAR file, or if we determined that the file is outdated.
+     */
+    private TimestampCheck existingJAR;
+
+    /**
+     * Name of the module being archived when the project is using module hierarchy.
+     * This is {@code null} if the project is using package hierarchy, either because it is a classical
+     * class-path project or because it is a single module compiled without using the module hierarchy.
+     * When using module source hierarchy, {@code javac} guarantees that the module name in the output
+     * directory is the name of the parent directory of {@code module-info.class}.
+     */
+    @Nullable
+    final String moduleName;
+
+    /**
+     * Path to {@code META-INF/MANIFEST.MF}, or {@code null} if none.
+     * If non-null, this value will be given to the {@code --manifest} option.
+     * The use of this option is preferable to adding {@code MANIFEST.MF} as an ordinary file.
+     *
+     * @see #setManifest(Path, boolean)
+     * @see #mergeManifest(Path, Manifest)
+     */
+    @Nullable
+    private Path manifest;
+
+    /**
+     * The Maven generated {@code pom.xml} and {@code pom.properties} files, or {@code null} if none.
+     * This first item shall be the base directory where the files are located.
+     */
+    @Nullable
+    List<Path> mavenFiles;
+
+    /**
+     * Fully-qualified name of the main class, or {@code null} if none.
+     * This is the value to provide to the {@code --main-class} option.
+     */
+    private String mainClass;
+
+    /**
+     * Files or root directories to store in the <abbr>JAR</abbr> file for each target Java release
+     * other than the base release. Keys are the target Java release with {@code null} for the base
+     * release.
+     */
+    @Nonnull
+    private final NavigableMap<Runtime.Version, FileSet> filesetForRelease;
+
+    /**
+     * Files or root directories to archive for a single target Java release of a single module.
+     * The {@link Archive} enclosing shall contain at least one instance of {@code FileSet} for
+     * the base release, and an arbitrary amount of other instances for other target releases.
+     */
+    final class FileSet {
+        /**
+         * A comparator for sorting paths in a reproducible order.
+         * This comparator assumes that all paths are relative to the same base directory (this is not verified).
+         * Note: we do not use {@link Path#compareTo(Path)} because the Javadoc said that it is platform dependent.
+         */
+        private static final Comparator<Path> REPRODUCIBLE_ORDER = (p1, p2) -> {
+            final int c1 = p1.getNameCount();
+            final int c2 = p2.getNameCount();
+            final int c = Math.min(c1, c2);
+            for (int i = 0; i < c; i++) {
+                String n1 = p1.getName(i).toString();
+                String n2 = p2.getName(i).toString();
+                int r = n1.compareTo(n2); // Case-sensitive comparison on all platforms.
+                if (r != 0) {
+                    return r;
+                }
+            }
+            return c1 - c2;
+        };
+
+        /**
+         * The root directory of all files or directories to archive.
+         * This is the value to pass to the {@code -C} tool option.
+         */
+        @Nonnull
+        final Path directory;
+
+        /**
+         * The files or directories to include in the <var>JAR</var> file.
+         * May be absolute paths or paths relative to {@link #directory}.
+         */
+        @Nonnull
+        final List<Path> files;
+
+        /**
+         * Creates an initially empty set of files or directories for a specific target Java release.
+         *
+         * @param directory the base directory of the files or directories to archive
+         */
+        private FileSet(Path directory) {
+            this.directory = directory;
+            this.files = new ArrayList<>();
+        }
+
+        /**
+         * 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.
+         * The caller should use that common directory for logging a warning message.
+         *
+         * @param base base directory found by previous invocations of this method, or {@code null} if none
+         * @return common directory of discarded files
+         */
+        private Path discardAllFiles(Path base) {
+            for (Path file : files) {
+                file = directory.resolve(file);
+                if (base == null) {
+                    base = file.getParent();
+                } else {
+                    while (!file.startsWith(base)) {
+                        base = base.getParent();
+                        if (base == null) {
+                            break;
+                        }
+                    }
+                }
+            }
+            files.clear();
+            return base;
+        }
+
+        /**
+         * Adds the given path to the list of files or directories to archive.
+         * This method may store a relative path instead of the absolute path.
+         *
+         * @param item a file or directory to archive
+         * @param attributes the file's basic attributes
+         * @param isDirectory whether the file is a directory
+         * @throws IllegalArgumentException if the given path cannot be made relative to the base directory
+         */
+        void add(Path item, BasicFileAttributes attributes, boolean isDirectory) {
+            TimestampCheck tc = existingJAR;
+            if (tc != null && tc.isUpdated(item, attributes, isDirectory)) {
+                existingJAR = null; // Signal that the existing file is outdated.
+            }
+            item = directory.relativize(item);
+            if (item.getNameCount() <= 1 && item.toString().isEmpty()) {
+                /*
+                 * The item is the `-C` directory itself (e.g. a `META-INF/versions/<n>` directory
+                 * added as a whole). An empty file argument is invalid for the `jar` tool
+                 * (some implementations reject it, others silently misbehave),
+                 * so archive the whole directory content with ".".
+                 */
+                item = Path.of(".");
+            }
+            files.add(item);
+        }
+
+        /**
+         * Adds to the given list the arguments to provide to the "jar" tool for this version.
+         * Elements added to the list shall be instances of {@link String} or {@link Path}.
+         *
+         * @param addTo the list where to add the arguments as {@link String} or {@link Path} instances
+         * @param version the target Java release, or {@code null} for the base version of the <abbr>JAR</abbr> file
+         */
+        private void arguments(List<Object> addTo, Runtime.Version version) {
+            if (!files.isEmpty()) {
+                if (version != null) {
+                    addTo.add("--release");
+                    addTo.add(version);
+                }
+                if (isReproducible) {
+                    files.sort(REPRODUCIBLE_ORDER);
+                }
+                if (REPEAT_C) {
+                    for (Path file : files) {
+                        addTo.add("-C");
+                        addTo.add(directory);
+                        addTo.add(file);
+                    }
+                } else {
+                    addTo.add("-C");
+                    addTo.add(directory);
+                    addTo.addAll(files);
+                }
+            }
+        }
+
+        /**
+         * {@return a string representation for debugging purposes}
+         */
+        @Override
+        public String toString() {
+            return getClass().getSimpleName() + '[' + directory.getFileName() + ": " + files.size() + " files]";
+        }
+    }
+
+    /**
+     * Whether reproducible build was requested.
+     */
+    private final boolean isReproducible;
+
+    /**
+     * Creates an initially empty set of files or directories.
+     *
+     * @param jarFile path to the <abbr>JAR</abbr> file to create
+     * @param moduleName the module name if using module hierarchy, or {@code null} if using package hierarchy
+     * @param version the target Java release, or {@code null} for the base version
+     * @param directory the directory of the classes targeting the base Java release
+     * @param forceCreation whether to force a new <abbr>JAR</abbr> file even if the content seems unchanged
+     * @param isReproducible whether reproducible build was requested
+     * @param logger where to send a warning if an error occurred while checking an existing <abbr>JAR</abbr> file
+     */
+    @SuppressWarnings("checkstyle:NeedBraces")
+    Archive(
+            final Path jarFile,
+            final String moduleName,
+            final Runtime.Version version,
+            final Path directory,
+            final boolean forceCreation,
+            final boolean isReproducible,
+            final Log logger) {
+        this.jarFile = jarFile;
+        this.moduleName = moduleName;
+        this.isReproducible = isReproducible;
+        filesetForRelease = new TreeMap<>((v1, v2) -> {
+            if (v1 == v2) return 0;
+            if (v1 == null) return -1;
+            if (v2 == null) return +1;
+            return v1.compareTo(v2);
+        });
+        filesetForRelease.put(version, new FileSet(directory));
+        if (!forceCreation && Files.isRegularFile(jarFile)) {
+            try {
+                existingJAR = new TimestampCheck(jarFile, directory, logger);
+            } catch (IOException e) {
+                // Ignore, we will regenerate the JAR file.
+                logger.warn(e);
+            }
+        }
+    }
+
+    /**
+     * {@return the files or directories to store in the <abbr>JAR</abbr> file for targeting the base Java release}
+     *
+     * @throws NoSuchElementException should not happen unless {@link #prune(boolean)} has been invoked
+     */
+    FileSet baseRelease() {
+        Map.Entry<Runtime.Version, FileSet> entry = filesetForRelease.firstEntry();
+        String message = null;
+        if (entry != null) {
+            Runtime.Version version = entry.getKey();
+            if (version == null) {
+                return entry.getValue();
+            }
+            message = "Expected base version but found version " + version;
+        }
+        throw new NoSuchElementException(message);
+    }
+
+    /**
+     * Returns the {@code module-info.class} files. Conceptually, there is at most once such file per module.
+     * However, more than one file may exist if additional files are provided for additional Java releases.
+     * This method returns only the files that exist.
+     *
+     * @return all {@code module-info.class} files found for all target Java releases
+     */
+    public List<Path> moduleInfoFiles() {
+        var files = new ArrayList<Path>();
+        filesetForRelease.values().forEach((release) -> {
+            Path file = release.directory.resolve(FileCollector.MODULE_DESCRIPTOR_FILE_NAME);
+            if (Files.isRegularFile(file)) {
+                files.add(file);
+            }
+        });
+        return files;
+    }
+
+    /**
+     * Discards all files in this archive, normally because those files are not in any module.
+     * This method returns a common parent directory for all the files that were discarded.
+     * The caller should use that common directory for logging a warning message.
+     *
+     * @return common directory of discarded files, or {@code null} if none
+     */
+    Path discardAllFiles() {
+        Path base = null;
+        for (FileSet release : filesetForRelease.values()) {
+            base = release.discardAllFiles(base);
+        }
+        filesetForRelease.clear();
+        return base;
+    }
+
+    /**
+     * Removes all empty file sets 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}, then this method ensures that at least one file set
+     * remains even if that file set is empty.
+     *
+     * @param skipIfEmpty value of {@link AbstractJarMojo#skipIfEmpty}
+     */
+    public void prune(final boolean skipIfEmpty) {
+        FileSet keep = (skipIfEmpty || isEmpty())
+                ? null
+                : filesetForRelease.firstEntry().getValue();
+        filesetForRelease.values().removeIf((fs) -> fs.files.isEmpty());
+        Iterator<Map.Entry<Runtime.Version, FileSet>> it =
+                filesetForRelease.entrySet().iterator();
+        if (it.hasNext()) {
+            Map.Entry<Runtime.Version, FileSet> first = it.next();
+            if (first.getKey() == null) {
+                return; // Already contains an entry for the base version, nothing to do.
+            }
+            keep = first.getValue();
+            it.remove();
+        }
+        if (keep != null) {
+            filesetForRelease.put(null, keep);
+        }
+    }
+
+    /**
+     * {@return whether this archive has nothing to archive}
+     * Note that this method may return {@code false} even when there is zero file to archive.
+     * It may happen if {@link AbstractJarMojo#skipIfEmpty} is {@code false}. In such case, the
+     * "empty" <abbr>JAR</abbr> file will still contain at {@code META-INF/MANIFEST.MF} file.
+     *
+     * <h4>Prerequisites</h4>
+     * The {@link #prune(boolean)} method should be invoked before this method for accurate result.
+     */
+    public boolean isEmpty() {
+        return filesetForRelease.isEmpty();
+    }
+
+    /**
+     * Checks whether the <abbr>JAR</abbr> file already exists and can be reused.
+     * This method verifies that the <abbr>JAR</abbr> file contains all the files to archive,
+     * contains no extra file, and no file to archive is newer than the <abbr>JAR</abbr> file.
+     *
+     * <p>This method can be invoked only once.
+     * If invoked more often, it returns {@code false} on all subsequent invocations.</p>
+     *
+     * @return whether the <abbr>JAR</abbr> file already exists and can be reused
+     */
+    public boolean isUpToDateJAR() {
+        final TimestampCheck tc = existingJAR;
+        if (tc == null) {
+            return false;
+        }
+        existingJAR = null; // Let GC do its job.
+        return tc.isUpToDateJAR(filesetForRelease.values());
+    }
+
+    /**
+     * Returns an initially empty set of files or directories for the specified target Java release.
+     *
+     * @param directory the base directory of the files to archive
+     * @param version the target Java release, or {@code null} for the base version
+     * @return container where to declare files and directories to archive
+     */
+    FileSet newTargetRelease(Path directory, Runtime.Version version) {
+        return filesetForRelease.computeIfAbsent(version, (key) -> new FileSet(directory));
+    }
+
+    /**
+     * Sets the {@code --main-class} option to the value of the {@code Main-Class} entry of the given manifest.
+     * As an extension, this method accepts the {@code module/classname} syntax (a syntax already used in some
+     * Java tools). If a module is specified, the main class is kept only if the module match. The intent is to
+     * allow users to specify on which module the main class applies when they use plugin configuration.
+     *
+     * <p>This method may modify the {@code content} manifest. Caller shall ensure that the given manifest
+     * is not a shared instance. This method returns whether a change has actually been done.</p>
+     *
+     * @param content combination of existing {@code MANIFEST.MF} and manifest inferred from configuration, or null
+     * @return whether the given manifest has been modified by this method
+     */
+    boolean setMainClass(Manifest content) {
+        if (content == null || mainClass != null) {
+            return false;
+        }
+        // We need to remove the attribute, otherwise it will conflict with `--main-class`.
+        mainClass = (String) content.getMainAttributes().remove(Attributes.Name.MAIN_CLASS);
+        if (mainClass != null) {
+            int s = mainClass.indexOf('/');
+            if (s >= 0) {
+                if (mainClass.substring(0, s).strip().equals(moduleName)) {
+                    mainClass = mainClass.substring(s + 1).strip();
+                } else {
+                    mainClass = null; // Main class is defined for another module.
+                }
+            }
+        }
+        return mainClass != null;
+    }
+
+    /**
+     * Sets the {@code --manifest} option to the given value if that option was not already set.
+     *
+     * @param file path to the manifest file
+     * @param force whether to set the manifest even if already set
+     * @return whether the manifest has been set
+     */
+    boolean setManifest(Path file, boolean force) {
+        if (manifest == null || force) {
+            manifest = file;
+            return true;
+        }
+        return false;
+    }
+
+    /**
+     * Merges the manifest of this module with the manifest specified in plugin configuration.
+     * If both {@code file} and {@code content} are non-null, then {@code content} must be the
+     * result of reading {@code file}.
+     *
+     * <p>This method never modifies the given {@code content} object. If manifest are merged,
+     * a new {@link Manifest} instance is created. Therefore, caller can check whether this
+     * method returned a new instance as a way to recognize that a merge occurred.</p>
+     *
+     * <p>If a merge occurs, the content specified to {@link #setManifest(Path)} has precedence.
+     * It should be the {@code target/classes/META-INF/MANIFEST.MF} file (or modular equivalent).</p>
+     *
+     * @param  file     an additional manifest file, or {@code null}
+     * @param  content  the content of {@code file}, or a standalone manifest produced at runtime
+     * @return the merged manifest as a new instance if some changes were necessary
+     * @throws IOException if an error occurred while reading a manifest file
+     */
+    Manifest mergeManifest(Path file, Manifest content) throws IOException {
+        if (manifest == null) {
+            manifest = file;
+        } else if (file != null && Files.isSameFile(file, manifest)) {
+            // Nothing to merge because of the constraint that `content` must be the content of `file`.
+        } else {
+            try (InputStream in = Files.newInputStream(manifest)) {
+                // No need to wrap in `BufferedInputStream`.
+                if (content != null) {
+                    content = new Manifest(content);
+                    content.read(in);
+                } else {
+                    content = new Manifest(in);
+                }
+            }
+        }
+        return content;
+    }
+
+    /**
+     * Adds to the given list the arguments to provide to the "jar" tool for each version.
+     * Elements added to the list shall be instances of {@link String} or {@link Path}.

Review Comment:
   shall --> should



##########
src/main/java/org/apache/maven/plugins/jar/DirectoryRole.java:
##########
@@ -0,0 +1,73 @@
+/*
+ * 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.jar;
+
+/**
+ * Directories that the archiver needs to handle in a special way.
+ */
+enum DirectoryRole {
+    /**
+     * The root directory. This is usually {@code "target/classes"}.
+     * The next locations can be {@link #META_INF}, {@link #NAMED_MODULE} or {@link #RESOURCES}.
+     */
+    ROOT,
+
+    /**
+     * The {@code "META-INF"} or {@code "<module>/META-INF"} directory.
+     * This is part of the <abbr>JAR</abbr> specification.
+     * The next locations can be {@link #VERSIONS} or {@link #VERSIONS_MODULAR}.
+     */
+    META_INF,
+
+    /**
+     * The {@code "META-INF/versions"} or {@code "<module>/META-INF/versions"} directory.
+     * This is part of the <abbr>JAR</abbr> specification, except the {@code <module>} prefix.
+     * The sub-directories are named according Java releases such as "21".

Review Comment:
   according to



##########
src/main/java/org/apache/maven/plugins/jar/Archive.java:
##########
@@ -0,0 +1,692 @@
+/*
+ * 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.jar;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.TreeMap;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.Type;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.MojoException;
+
+/**
+ * Files or root directories to archive for a single module.
+ * A single instance of {@code Archive} may contain many directories for different target Java releases.
+ * Many instances of {@code Archive} may exist when archiving a multi-modules project.
+ */
+final class Archive {
+    /**
+     * Whether to repeat the {@code -C} option before each file.
+     * Doing so makes the command-line very verbose while the documentation of
+     * <a href="https://docs.oracle.com/en/java/javase/25/docs/specs/man/jar.html">The jar Command</a>
+     * gives the impression that this option can be provided only once.
+     * However, our tests suggest that the first file after the directory specified by the {@code -C} option
+     * must be relative to that directory and all files after the first one must be prefixed by the directory
+     * which was specified in the {@code -C} option. This behavior is not documented, but we couldn't get the
+     * {@code jar} tool to work otherwise (except by repeating {@code -C} before each file).
+     * Furthermore, it seems that the relativized file needs to be the shortest one,
+     * otherwise the {@code jar} tool rejects files after the first one with "names do not match".
+     * Which file is first depends on the unspecified directory-iteration order.
+     *
+     * <p>If this flag is {@code true}, the plugin repeats {@code -C} before each file.
+     * This flag should be set to {@code false} if a future version of the {@code jar}
+     * tool allows to specify {@code -C} only once.</p>
+     *
+     * <p><b>Historical note:</b> we also tried to relativize only the first file after {@code -C}
+     * and keep all subsequent files as absolute. It works, but because we have to repeat the directory
+     * in the file name, it saves only 3 or 4 characters per file compared to repeating {@code -C}.</p>
+     */
+    private static final boolean REPEAT_C = true;
+
+    /**
+     * Path to the <abbr>POM</abbr> file generated for this archive, or {@code null} if none.
+     * This is non-null only if module source hierarchy is used, in which case the dependencies
+     * declared in this file are the intersection of the project dependencies and the content of
+     * the {@code module-info.class} file.
+     */
+    @Nullable
+    Path pomFile;
+
+    /**
+     * The <var>JAR</var> file to create. May be an existing file,
+     * in which case the file creation may be skipped if the file is still up-to-date.
+     */
+    @Nonnull
+    final Path jarFile;
+
+    /**
+     * A helper class for checking whether an existing <abbr>JAR</abbr> file is still up-to-date.
+     * This is null if there is no existing JAR file, or if we determined that the file is outdated.
+     */
+    private TimestampCheck existingJAR;
+
+    /**
+     * Name of the module being archived when the project is using module hierarchy.
+     * This is {@code null} if the project is using package hierarchy, either because it is a classical
+     * class-path project or because it is a single module compiled without using the module hierarchy.
+     * When using module source hierarchy, {@code javac} guarantees that the module name in the output
+     * directory is the name of the parent directory of {@code module-info.class}.
+     */
+    @Nullable
+    final String moduleName;
+
+    /**
+     * Path to {@code META-INF/MANIFEST.MF}, or {@code null} if none.
+     * If non-null, this value will be given to the {@code --manifest} option.
+     * The use of this option is preferable to adding {@code MANIFEST.MF} as an ordinary file.
+     *
+     * @see #setManifest(Path, boolean)
+     * @see #mergeManifest(Path, Manifest)
+     */
+    @Nullable
+    private Path manifest;
+
+    /**
+     * The Maven generated {@code pom.xml} and {@code pom.properties} files, or {@code null} if none.
+     * This first item shall be the base directory where the files are located.
+     */
+    @Nullable
+    List<Path> mavenFiles;
+
+    /**
+     * Fully-qualified name of the main class, or {@code null} if none.
+     * This is the value to provide to the {@code --main-class} option.
+     */
+    private String mainClass;
+
+    /**
+     * Files or root directories to store in the <abbr>JAR</abbr> file for each target Java release
+     * other than the base release. Keys are the target Java release with {@code null} for the base
+     * release.
+     */
+    @Nonnull
+    private final NavigableMap<Runtime.Version, FileSet> filesetForRelease;
+
+    /**
+     * Files or root directories to archive for a single target Java release of a single module.
+     * The {@link Archive} enclosing shall contain at least one instance of {@code FileSet} for
+     * the base release, and an arbitrary amount of other instances for other target releases.
+     */
+    final class FileSet {
+        /**
+         * A comparator for sorting paths in a reproducible order.
+         * This comparator assumes that all paths are relative to the same base directory (this is not verified).
+         * Note: we do not use {@link Path#compareTo(Path)} because the Javadoc said that it is platform dependent.
+         */
+        private static final Comparator<Path> REPRODUCIBLE_ORDER = (p1, p2) -> {
+            final int c1 = p1.getNameCount();
+            final int c2 = p2.getNameCount();
+            final int c = Math.min(c1, c2);
+            for (int i = 0; i < c; i++) {
+                String n1 = p1.getName(i).toString();
+                String n2 = p2.getName(i).toString();
+                int r = n1.compareTo(n2); // Case-sensitive comparison on all platforms.
+                if (r != 0) {
+                    return r;
+                }
+            }
+            return c1 - c2;
+        };
+
+        /**
+         * The root directory of all files or directories to archive.
+         * This is the value to pass to the {@code -C} tool option.
+         */
+        @Nonnull
+        final Path directory;
+
+        /**
+         * The files or directories to include in the <var>JAR</var> file.
+         * May be absolute paths or paths relative to {@link #directory}.
+         */
+        @Nonnull
+        final List<Path> files;
+
+        /**
+         * Creates an initially empty set of files or directories for a specific target Java release.
+         *
+         * @param directory the base directory of the files or directories to archive
+         */
+        private FileSet(Path directory) {
+            this.directory = directory;
+            this.files = new ArrayList<>();
+        }
+
+        /**
+         * 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.
+         * The caller should use that common directory for logging a warning message.
+         *
+         * @param base base directory found by previous invocations of this method, or {@code null} if none
+         * @return common directory of discarded files
+         */
+        private Path discardAllFiles(Path base) {
+            for (Path file : files) {
+                file = directory.resolve(file);
+                if (base == null) {
+                    base = file.getParent();
+                } else {
+                    while (!file.startsWith(base)) {
+                        base = base.getParent();
+                        if (base == null) {
+                            break;
+                        }
+                    }
+                }
+            }
+            files.clear();
+            return base;
+        }
+
+        /**
+         * Adds the given path to the list of files or directories to archive.
+         * This method may store a relative path instead of the absolute path.
+         *
+         * @param item a file or directory to archive
+         * @param attributes the file's basic attributes
+         * @param isDirectory whether the file is a directory
+         * @throws IllegalArgumentException if the given path cannot be made relative to the base directory
+         */
+        void add(Path item, BasicFileAttributes attributes, boolean isDirectory) {
+            TimestampCheck tc = existingJAR;
+            if (tc != null && tc.isUpdated(item, attributes, isDirectory)) {
+                existingJAR = null; // Signal that the existing file is outdated.
+            }
+            item = directory.relativize(item);
+            if (item.getNameCount() <= 1 && item.toString().isEmpty()) {
+                /*
+                 * The item is the `-C` directory itself (e.g. a `META-INF/versions/<n>` directory
+                 * added as a whole). An empty file argument is invalid for the `jar` tool
+                 * (some implementations reject it, others silently misbehave),
+                 * so archive the whole directory content with ".".
+                 */
+                item = Path.of(".");
+            }
+            files.add(item);
+        }
+
+        /**
+         * Adds to the given list the arguments to provide to the "jar" tool for this version.
+         * Elements added to the list shall be instances of {@link String} or {@link Path}.
+         *
+         * @param addTo the list where to add the arguments as {@link String} or {@link Path} instances
+         * @param version the target Java release, or {@code null} for the base version of the <abbr>JAR</abbr> file
+         */
+        private void arguments(List<Object> addTo, Runtime.Version version) {
+            if (!files.isEmpty()) {
+                if (version != null) {
+                    addTo.add("--release");
+                    addTo.add(version);
+                }
+                if (isReproducible) {
+                    files.sort(REPRODUCIBLE_ORDER);
+                }
+                if (REPEAT_C) {
+                    for (Path file : files) {
+                        addTo.add("-C");
+                        addTo.add(directory);
+                        addTo.add(file);
+                    }
+                } else {
+                    addTo.add("-C");
+                    addTo.add(directory);
+                    addTo.addAll(files);
+                }
+            }
+        }
+
+        /**
+         * {@return a string representation for debugging purposes}
+         */
+        @Override
+        public String toString() {
+            return getClass().getSimpleName() + '[' + directory.getFileName() + ": " + files.size() + " files]";
+        }
+    }
+
+    /**
+     * Whether reproducible build was requested.
+     */
+    private final boolean isReproducible;
+
+    /**
+     * Creates an initially empty set of files or directories.
+     *
+     * @param jarFile path to the <abbr>JAR</abbr> file to create
+     * @param moduleName the module name if using module hierarchy, or {@code null} if using package hierarchy
+     * @param version the target Java release, or {@code null} for the base version
+     * @param directory the directory of the classes targeting the base Java release
+     * @param forceCreation whether to force a new <abbr>JAR</abbr> file even if the content seems unchanged
+     * @param isReproducible whether reproducible build was requested
+     * @param logger where to send a warning if an error occurred while checking an existing <abbr>JAR</abbr> file
+     */
+    @SuppressWarnings("checkstyle:NeedBraces")
+    Archive(
+            final Path jarFile,
+            final String moduleName,
+            final Runtime.Version version,
+            final Path directory,
+            final boolean forceCreation,
+            final boolean isReproducible,
+            final Log logger) {
+        this.jarFile = jarFile;
+        this.moduleName = moduleName;
+        this.isReproducible = isReproducible;
+        filesetForRelease = new TreeMap<>((v1, v2) -> {
+            if (v1 == v2) return 0;
+            if (v1 == null) return -1;
+            if (v2 == null) return +1;
+            return v1.compareTo(v2);
+        });
+        filesetForRelease.put(version, new FileSet(directory));
+        if (!forceCreation && Files.isRegularFile(jarFile)) {
+            try {
+                existingJAR = new TimestampCheck(jarFile, directory, logger);
+            } catch (IOException e) {
+                // Ignore, we will regenerate the JAR file.
+                logger.warn(e);
+            }
+        }
+    }
+
+    /**
+     * {@return the files or directories to store in the <abbr>JAR</abbr> file for targeting the base Java release}
+     *
+     * @throws NoSuchElementException should not happen unless {@link #prune(boolean)} has been invoked
+     */
+    FileSet baseRelease() {
+        Map.Entry<Runtime.Version, FileSet> entry = filesetForRelease.firstEntry();
+        String message = null;
+        if (entry != null) {
+            Runtime.Version version = entry.getKey();
+            if (version == null) {
+                return entry.getValue();
+            }
+            message = "Expected base version but found version " + version;
+        }
+        throw new NoSuchElementException(message);
+    }
+
+    /**
+     * Returns the {@code module-info.class} files. Conceptually, there is at most once such file per module.
+     * However, more than one file may exist if additional files are provided for additional Java releases.
+     * This method returns only the files that exist.
+     *
+     * @return all {@code module-info.class} files found for all target Java releases
+     */
+    public List<Path> moduleInfoFiles() {
+        var files = new ArrayList<Path>();
+        filesetForRelease.values().forEach((release) -> {
+            Path file = release.directory.resolve(FileCollector.MODULE_DESCRIPTOR_FILE_NAME);
+            if (Files.isRegularFile(file)) {
+                files.add(file);
+            }
+        });
+        return files;
+    }
+
+    /**
+     * Discards all files in this archive, normally because those files are not in any module.
+     * This method returns a common parent directory for all the files that were discarded.
+     * The caller should use that common directory for logging a warning message.
+     *
+     * @return common directory of discarded files, or {@code null} if none
+     */
+    Path discardAllFiles() {
+        Path base = null;
+        for (FileSet release : filesetForRelease.values()) {
+            base = release.discardAllFiles(base);
+        }
+        filesetForRelease.clear();
+        return base;
+    }
+
+    /**
+     * Removes all empty file sets 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}, then this method ensures that at least one file set
+     * remains even if that file set is empty.
+     *
+     * @param skipIfEmpty value of {@link AbstractJarMojo#skipIfEmpty}
+     */
+    public void prune(final boolean skipIfEmpty) {
+        FileSet keep = (skipIfEmpty || isEmpty())
+                ? null
+                : filesetForRelease.firstEntry().getValue();
+        filesetForRelease.values().removeIf((fs) -> fs.files.isEmpty());
+        Iterator<Map.Entry<Runtime.Version, FileSet>> it =
+                filesetForRelease.entrySet().iterator();
+        if (it.hasNext()) {
+            Map.Entry<Runtime.Version, FileSet> first = it.next();
+            if (first.getKey() == null) {
+                return; // Already contains an entry for the base version, nothing to do.
+            }
+            keep = first.getValue();
+            it.remove();
+        }
+        if (keep != null) {
+            filesetForRelease.put(null, keep);
+        }
+    }
+
+    /**
+     * {@return whether this archive has nothing to archive}
+     * Note that this method may return {@code false} even when there is zero file to archive.
+     * It may happen if {@link AbstractJarMojo#skipIfEmpty} is {@code false}. In such case, the
+     * "empty" <abbr>JAR</abbr> file will still contain at {@code META-INF/MANIFEST.MF} file.
+     *
+     * <h4>Prerequisites</h4>
+     * The {@link #prune(boolean)} method should be invoked before this method for accurate result.
+     */
+    public boolean isEmpty() {
+        return filesetForRelease.isEmpty();
+    }
+
+    /**
+     * Checks whether the <abbr>JAR</abbr> file already exists and can be reused.
+     * This method verifies that the <abbr>JAR</abbr> file contains all the files to archive,
+     * contains no extra file, and no file to archive is newer than the <abbr>JAR</abbr> file.
+     *
+     * <p>This method can be invoked only once.
+     * If invoked more often, it returns {@code false} on all subsequent invocations.</p>
+     *
+     * @return whether the <abbr>JAR</abbr> file already exists and can be reused
+     */
+    public boolean isUpToDateJAR() {
+        final TimestampCheck tc = existingJAR;
+        if (tc == null) {
+            return false;
+        }
+        existingJAR = null; // Let GC do its job.
+        return tc.isUpToDateJAR(filesetForRelease.values());
+    }
+
+    /**
+     * Returns an initially empty set of files or directories for the specified target Java release.
+     *
+     * @param directory the base directory of the files to archive
+     * @param version the target Java release, or {@code null} for the base version
+     * @return container where to declare files and directories to archive
+     */
+    FileSet newTargetRelease(Path directory, Runtime.Version version) {
+        return filesetForRelease.computeIfAbsent(version, (key) -> new FileSet(directory));
+    }
+
+    /**
+     * Sets the {@code --main-class} option to the value of the {@code Main-Class} entry of the given manifest.
+     * As an extension, this method accepts the {@code module/classname} syntax (a syntax already used in some
+     * Java tools). If a module is specified, the main class is kept only if the module match. The intent is to
+     * allow users to specify on which module the main class applies when they use plugin configuration.
+     *
+     * <p>This method may modify the {@code content} manifest. Caller shall ensure that the given manifest
+     * is not a shared instance. This method returns whether a change has actually been done.</p>
+     *
+     * @param content combination of existing {@code MANIFEST.MF} and manifest inferred from configuration, or null
+     * @return whether the given manifest has been modified by this method
+     */
+    boolean setMainClass(Manifest content) {
+        if (content == null || mainClass != null) {
+            return false;
+        }
+        // We need to remove the attribute, otherwise it will conflict with `--main-class`.
+        mainClass = (String) content.getMainAttributes().remove(Attributes.Name.MAIN_CLASS);
+        if (mainClass != null) {
+            int s = mainClass.indexOf('/');
+            if (s >= 0) {
+                if (mainClass.substring(0, s).strip().equals(moduleName)) {
+                    mainClass = mainClass.substring(s + 1).strip();
+                } else {
+                    mainClass = null; // Main class is defined for another module.
+                }
+            }
+        }
+        return mainClass != null;
+    }
+
+    /**
+     * Sets the {@code --manifest} option to the given value if that option was not already set.
+     *
+     * @param file path to the manifest file
+     * @param force whether to set the manifest even if already set
+     * @return whether the manifest has been set
+     */
+    boolean setManifest(Path file, boolean force) {
+        if (manifest == null || force) {
+            manifest = file;
+            return true;
+        }
+        return false;
+    }
+
+    /**
+     * Merges the manifest of this module with the manifest specified in plugin configuration.
+     * If both {@code file} and {@code content} are non-null, then {@code content} must be the
+     * result of reading {@code file}.
+     *
+     * <p>This method never modifies the given {@code content} object. If manifest are merged,
+     * a new {@link Manifest} instance is created. Therefore, caller can check whether this
+     * method returned a new instance as a way to recognize that a merge occurred.</p>
+     *
+     * <p>If a merge occurs, the content specified to {@link #setManifest(Path)} has precedence.
+     * It should be the {@code target/classes/META-INF/MANIFEST.MF} file (or modular equivalent).</p>
+     *
+     * @param  file     an additional manifest file, or {@code null}
+     * @param  content  the content of {@code file}, or a standalone manifest produced at runtime
+     * @return the merged manifest as a new instance if some changes were necessary
+     * @throws IOException if an error occurred while reading a manifest file
+     */
+    Manifest mergeManifest(Path file, Manifest content) throws IOException {
+        if (manifest == null) {
+            manifest = file;
+        } else if (file != null && Files.isSameFile(file, manifest)) {
+            // Nothing to merge because of the constraint that `content` must be the content of `file`.
+        } else {
+            try (InputStream in = Files.newInputStream(manifest)) {
+                // No need to wrap in `BufferedInputStream`.
+                if (content != null) {
+                    content = new Manifest(content);
+                    content.read(in);
+                } else {
+                    content = new Manifest(in);
+                }
+            }
+        }
+        return content;
+    }
+
+    /**
+     * Adds to the given list the arguments to provide to the "jar" tool for each version.
+     * Elements added to the list shall be instances of {@link String} or {@link Path}.
+     * Callers should have added the following options (if applicable) before to invoke this method:
+     *
+     * <ul>
+     *   <li>{@code --create}</li>
+     *   <li>{@code --no-compress}</li>
+     *   <li>{@code --date} followed by the output time stamp</li>
+     *   <li>{@code --module-version} followed by module version</li>
+     *   <li>{@code --hash-modules} followed by patters of module names</li>
+     *   <li>{@code --module-path} followed by module path</li>
+     * </ul>
+     *
+     * This method adds the following options:
+     *
+     * <ul>
+     *   <li>{@code --file} followed by the path to the <abbr>JAR</abbr> file</li>
+     *   <li>{@code --manifest} followed by path to the manifest file</li>
+     *   <li>{@code --main-class} followed by fully qualified name class</li>
+     *   <li>{@code --release} followed by Java target release</li>
+     *   <li>{@code -C} followed by directory</li>
+     *   <li>files or directories to archive</li>
+     * </ul>
+     *
+     * @param addTo the list where to add the arguments as {@link String} or {@link Path} instances
+     */
+    void arguments(final List<Object> addTo) {
+        addTo.add("--file");
+        addTo.add(jarFile);
+        if (manifest != null) {
+            addTo.add("--manifest");
+            addTo.add(manifest);
+        }
+        if (mainClass != null) {
+            addTo.add("--main-class");
+            addTo.add(mainClass);
+        }
+        if (mavenFiles != null) {
+            addTo.add("-C");
+            addTo.addAll(mavenFiles);
+        }
+        for (Map.Entry<Runtime.Version, FileSet> entry : filesetForRelease.entrySet()) {
+            entry.getValue().arguments(addTo, entry.getKey());
+        }
+    }
+
+    /**
+     * Adds to the given list the arguments to provide to the "jar" tool for validating the <abbr>JAR</abbr> file.
+     * The file is validated only if the validation was not done implicitly at <abbr>JAR</abbr> creation time.
+     * This is the case if no {@code --release} option was used.
+     * This method adds the following options:
+     *
+     * <ul>
+     *   <li>{@code --validate} operation mode</li>
+     *   <li>{@code --file} followed by the path to the <abbr>JAR</abbr> file</li>
+     * </ul>
+     *
+     * @param  addTo the list where to add the arguments as {@link String} or {@link Path} instances
+     * @return whether a validation should be run
+     */
+    boolean validate(final List<Object> addTo) {
+        if (filesetForRelease.values().stream().allMatch(Objects::isNull)) {
+            // At least one --release option was used. Validation was implicit.
+            return false;
+        }
+        addTo.add("--validate");
+        addTo.add("--file");
+        addTo.add(jarFile);
+        return true;
+    }
+
+    /**
+     * Dumps the tool options together with the list of files into a debug file.
+     * This is invoked in case of compilation failure, or if debug is enabled.
+     * The arguments can be separated by spaces or by new line characters.
+     * File name should be between double quotation marks.
+     *
+     * @param baseDir project base directory for relativizing the arguments
+     * @param debugDirectory the directory where to write the debug file
+     * @param classifier the classifier (e.g. "tests"), or {@code null} if none
+     * @param arguments the arguments formatted by {@link #arguments(List)}
+     * @return the debug file where arguments have been written
+     * @throws IOException if an error occurred while writing the debug file
+     */
+    Path writeDebugFile(Path baseDir, Path debugDirectory, String classifier, List<Object> arguments)
+            throws IOException {
+        var filename = new StringBuilder("jar");
+        if (moduleName != null) {
+            filename.append('-').append(moduleName);
+        }
+        if (classifier != null) {
+            filename.append('-').append(classifier);
+        }
+        Path debugFile = debugDirectory.resolve(filename.append(".args").toString());
+        try (BufferedWriter out = Files.newBufferedWriter(debugFile)) {
+            boolean isNewLine = true;
+            for (Object argument : arguments) {
+                if (argument instanceof Path file) {
+                    try {
+                        file = baseDir.relativize(file);
+                    } catch (IllegalArgumentException e) {
+                        // Ignore, keep the absolute path.
+                    }
+                    if (!isNewLine) {
+                        out.write(' ');
+                    }
+                    out.write('"');
+                    out.write(file.toString());
+                    out.write('"');
+                    out.newLine();
+                    isNewLine = true;
+                } else {
+                    String option = argument.toString();
+                    if (!isNewLine) {
+                        if (option.startsWith("--") || option.equals("-C")) {
+                            out.newLine();
+                        } else {
+                            out.write(' ');
+                        }
+                    }
+                    out.write(option);
+                    isNewLine = false;
+                }
+            }
+        }
+        return debugFile;
+    }
+
+    /**
+     * Stores in the given map the paths to the artifacts produced for this archive.

Review Comment:
   Stores the paths to the artifacts produced for this archive in the given map .



##########
src/main/java/org/apache/maven/plugins/jar/Archive.java:
##########
@@ -0,0 +1,692 @@
+/*
+ * 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.jar;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.TreeMap;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.Type;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.MojoException;
+
+/**
+ * Files or root directories to archive for a single module.
+ * A single instance of {@code Archive} may contain many directories for different target Java releases.
+ * Many instances of {@code Archive} may exist when archiving a multi-modules project.
+ */
+final class Archive {
+    /**
+     * Whether to repeat the {@code -C} option before each file.
+     * Doing so makes the command-line very verbose while the documentation of
+     * <a href="https://docs.oracle.com/en/java/javase/25/docs/specs/man/jar.html">The jar Command</a>
+     * gives the impression that this option can be provided only once.
+     * However, our tests suggest that the first file after the directory specified by the {@code -C} option
+     * must be relative to that directory and all files after the first one must be prefixed by the directory
+     * which was specified in the {@code -C} option. This behavior is not documented, but we couldn't get the
+     * {@code jar} tool to work otherwise (except by repeating {@code -C} before each file).
+     * Furthermore, it seems that the relativized file needs to be the shortest one,
+     * otherwise the {@code jar} tool rejects files after the first one with "names do not match".
+     * Which file is first depends on the unspecified directory-iteration order.
+     *
+     * <p>If this flag is {@code true}, the plugin repeats {@code -C} before each file.
+     * This flag should be set to {@code false} if a future version of the {@code jar}
+     * tool allows to specify {@code -C} only once.</p>
+     *
+     * <p><b>Historical note:</b> we also tried to relativize only the first file after {@code -C}
+     * and keep all subsequent files as absolute. It works, but because we have to repeat the directory
+     * in the file name, it saves only 3 or 4 characters per file compared to repeating {@code -C}.</p>
+     */
+    private static final boolean REPEAT_C = true;
+
+    /**
+     * Path to the <abbr>POM</abbr> file generated for this archive, or {@code null} if none.
+     * This is non-null only if module source hierarchy is used, in which case the dependencies
+     * declared in this file are the intersection of the project dependencies and the content of
+     * the {@code module-info.class} file.
+     */
+    @Nullable
+    Path pomFile;
+
+    /**
+     * The <var>JAR</var> file to create. May be an existing file,
+     * in which case the file creation may be skipped if the file is still up-to-date.
+     */
+    @Nonnull
+    final Path jarFile;
+
+    /**
+     * A helper class for checking whether an existing <abbr>JAR</abbr> file is still up-to-date.
+     * This is null if there is no existing JAR file, or if we determined that the file is outdated.
+     */
+    private TimestampCheck existingJAR;
+
+    /**
+     * Name of the module being archived when the project is using module hierarchy.
+     * This is {@code null} if the project is using package hierarchy, either because it is a classical
+     * class-path project or because it is a single module compiled without using the module hierarchy.
+     * When using module source hierarchy, {@code javac} guarantees that the module name in the output
+     * directory is the name of the parent directory of {@code module-info.class}.
+     */
+    @Nullable
+    final String moduleName;
+
+    /**
+     * Path to {@code META-INF/MANIFEST.MF}, or {@code null} if none.
+     * If non-null, this value will be given to the {@code --manifest} option.
+     * The use of this option is preferable to adding {@code MANIFEST.MF} as an ordinary file.
+     *
+     * @see #setManifest(Path, boolean)
+     * @see #mergeManifest(Path, Manifest)
+     */
+    @Nullable
+    private Path manifest;
+
+    /**
+     * The Maven generated {@code pom.xml} and {@code pom.properties} files, or {@code null} if none.
+     * This first item shall be the base directory where the files are located.
+     */
+    @Nullable
+    List<Path> mavenFiles;
+
+    /**
+     * Fully-qualified name of the main class, or {@code null} if none.
+     * This is the value to provide to the {@code --main-class} option.
+     */
+    private String mainClass;
+
+    /**
+     * Files or root directories to store in the <abbr>JAR</abbr> file for each target Java release
+     * other than the base release. Keys are the target Java release with {@code null} for the base
+     * release.
+     */
+    @Nonnull
+    private final NavigableMap<Runtime.Version, FileSet> filesetForRelease;
+
+    /**
+     * Files or root directories to archive for a single target Java release of a single module.
+     * The {@link Archive} enclosing shall contain at least one instance of {@code FileSet} for
+     * the base release, and an arbitrary amount of other instances for other target releases.
+     */
+    final class FileSet {
+        /**
+         * A comparator for sorting paths in a reproducible order.
+         * This comparator assumes that all paths are relative to the same base directory (this is not verified).
+         * Note: we do not use {@link Path#compareTo(Path)} because the Javadoc said that it is platform dependent.
+         */
+        private static final Comparator<Path> REPRODUCIBLE_ORDER = (p1, p2) -> {
+            final int c1 = p1.getNameCount();
+            final int c2 = p2.getNameCount();
+            final int c = Math.min(c1, c2);
+            for (int i = 0; i < c; i++) {
+                String n1 = p1.getName(i).toString();
+                String n2 = p2.getName(i).toString();
+                int r = n1.compareTo(n2); // Case-sensitive comparison on all platforms.
+                if (r != 0) {
+                    return r;
+                }
+            }
+            return c1 - c2;
+        };
+
+        /**
+         * The root directory of all files or directories to archive.
+         * This is the value to pass to the {@code -C} tool option.
+         */
+        @Nonnull
+        final Path directory;
+
+        /**
+         * The files or directories to include in the <var>JAR</var> file.
+         * May be absolute paths or paths relative to {@link #directory}.
+         */
+        @Nonnull
+        final List<Path> files;
+
+        /**
+         * Creates an initially empty set of files or directories for a specific target Java release.
+         *
+         * @param directory the base directory of the files or directories to archive
+         */
+        private FileSet(Path directory) {
+            this.directory = directory;
+            this.files = new ArrayList<>();
+        }
+
+        /**
+         * 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.
+         * The caller should use that common directory for logging a warning message.
+         *
+         * @param base base directory found by previous invocations of this method, or {@code null} if none
+         * @return common directory of discarded files
+         */
+        private Path discardAllFiles(Path base) {
+            for (Path file : files) {
+                file = directory.resolve(file);
+                if (base == null) {
+                    base = file.getParent();
+                } else {
+                    while (!file.startsWith(base)) {
+                        base = base.getParent();
+                        if (base == null) {
+                            break;
+                        }
+                    }
+                }
+            }
+            files.clear();
+            return base;
+        }
+
+        /**
+         * Adds the given path to the list of files or directories to archive.
+         * This method may store a relative path instead of the absolute path.
+         *
+         * @param item a file or directory to archive
+         * @param attributes the file's basic attributes
+         * @param isDirectory whether the file is a directory
+         * @throws IllegalArgumentException if the given path cannot be made relative to the base directory
+         */
+        void add(Path item, BasicFileAttributes attributes, boolean isDirectory) {
+            TimestampCheck tc = existingJAR;
+            if (tc != null && tc.isUpdated(item, attributes, isDirectory)) {
+                existingJAR = null; // Signal that the existing file is outdated.
+            }
+            item = directory.relativize(item);
+            if (item.getNameCount() <= 1 && item.toString().isEmpty()) {
+                /*
+                 * The item is the `-C` directory itself (e.g. a `META-INF/versions/<n>` directory
+                 * added as a whole). An empty file argument is invalid for the `jar` tool
+                 * (some implementations reject it, others silently misbehave),
+                 * so archive the whole directory content with ".".
+                 */
+                item = Path.of(".");
+            }
+            files.add(item);
+        }
+
+        /**
+         * Adds to the given list the arguments to provide to the "jar" tool for this version.
+         * Elements added to the list shall be instances of {@link String} or {@link Path}.
+         *
+         * @param addTo the list where to add the arguments as {@link String} or {@link Path} instances
+         * @param version the target Java release, or {@code null} for the base version of the <abbr>JAR</abbr> file
+         */
+        private void arguments(List<Object> addTo, Runtime.Version version) {
+            if (!files.isEmpty()) {
+                if (version != null) {
+                    addTo.add("--release");
+                    addTo.add(version);
+                }
+                if (isReproducible) {
+                    files.sort(REPRODUCIBLE_ORDER);
+                }
+                if (REPEAT_C) {
+                    for (Path file : files) {
+                        addTo.add("-C");
+                        addTo.add(directory);
+                        addTo.add(file);
+                    }
+                } else {
+                    addTo.add("-C");
+                    addTo.add(directory);
+                    addTo.addAll(files);
+                }
+            }
+        }
+
+        /**
+         * {@return a string representation for debugging purposes}
+         */
+        @Override
+        public String toString() {
+            return getClass().getSimpleName() + '[' + directory.getFileName() + ": " + files.size() + " files]";
+        }
+    }
+
+    /**
+     * Whether reproducible build was requested.
+     */
+    private final boolean isReproducible;
+
+    /**
+     * Creates an initially empty set of files or directories.
+     *
+     * @param jarFile path to the <abbr>JAR</abbr> file to create
+     * @param moduleName the module name if using module hierarchy, or {@code null} if using package hierarchy
+     * @param version the target Java release, or {@code null} for the base version
+     * @param directory the directory of the classes targeting the base Java release
+     * @param forceCreation whether to force a new <abbr>JAR</abbr> file even if the content seems unchanged
+     * @param isReproducible whether reproducible build was requested
+     * @param logger where to send a warning if an error occurred while checking an existing <abbr>JAR</abbr> file
+     */
+    @SuppressWarnings("checkstyle:NeedBraces")
+    Archive(
+            final Path jarFile,
+            final String moduleName,
+            final Runtime.Version version,
+            final Path directory,
+            final boolean forceCreation,
+            final boolean isReproducible,
+            final Log logger) {
+        this.jarFile = jarFile;
+        this.moduleName = moduleName;
+        this.isReproducible = isReproducible;
+        filesetForRelease = new TreeMap<>((v1, v2) -> {
+            if (v1 == v2) return 0;
+            if (v1 == null) return -1;
+            if (v2 == null) return +1;
+            return v1.compareTo(v2);
+        });
+        filesetForRelease.put(version, new FileSet(directory));
+        if (!forceCreation && Files.isRegularFile(jarFile)) {
+            try {
+                existingJAR = new TimestampCheck(jarFile, directory, logger);
+            } catch (IOException e) {
+                // Ignore, we will regenerate the JAR file.
+                logger.warn(e);
+            }
+        }
+    }
+
+    /**
+     * {@return the files or directories to store in the <abbr>JAR</abbr> file for targeting the base Java release}
+     *
+     * @throws NoSuchElementException should not happen unless {@link #prune(boolean)} has been invoked
+     */
+    FileSet baseRelease() {
+        Map.Entry<Runtime.Version, FileSet> entry = filesetForRelease.firstEntry();
+        String message = null;
+        if (entry != null) {
+            Runtime.Version version = entry.getKey();
+            if (version == null) {
+                return entry.getValue();
+            }
+            message = "Expected base version but found version " + version;
+        }
+        throw new NoSuchElementException(message);
+    }
+
+    /**
+     * Returns the {@code module-info.class} files. Conceptually, there is at most once such file per module.
+     * However, more than one file may exist if additional files are provided for additional Java releases.
+     * This method returns only the files that exist.
+     *
+     * @return all {@code module-info.class} files found for all target Java releases
+     */
+    public List<Path> moduleInfoFiles() {
+        var files = new ArrayList<Path>();
+        filesetForRelease.values().forEach((release) -> {
+            Path file = release.directory.resolve(FileCollector.MODULE_DESCRIPTOR_FILE_NAME);
+            if (Files.isRegularFile(file)) {
+                files.add(file);
+            }
+        });
+        return files;
+    }
+
+    /**
+     * Discards all files in this archive, normally because those files are not in any module.
+     * This method returns a common parent directory for all the files that were discarded.
+     * The caller should use that common directory for logging a warning message.
+     *
+     * @return common directory of discarded files, or {@code null} if none
+     */
+    Path discardAllFiles() {
+        Path base = null;
+        for (FileSet release : filesetForRelease.values()) {
+            base = release.discardAllFiles(base);
+        }
+        filesetForRelease.clear();
+        return base;
+    }
+
+    /**
+     * Removes all empty file sets 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}, then this method ensures that at least one file set
+     * remains even if that file set is empty.
+     *
+     * @param skipIfEmpty value of {@link AbstractJarMojo#skipIfEmpty}
+     */
+    public void prune(final boolean skipIfEmpty) {
+        FileSet keep = (skipIfEmpty || isEmpty())
+                ? null
+                : filesetForRelease.firstEntry().getValue();
+        filesetForRelease.values().removeIf((fs) -> fs.files.isEmpty());
+        Iterator<Map.Entry<Runtime.Version, FileSet>> it =
+                filesetForRelease.entrySet().iterator();
+        if (it.hasNext()) {
+            Map.Entry<Runtime.Version, FileSet> first = it.next();
+            if (first.getKey() == null) {
+                return; // Already contains an entry for the base version, nothing to do.
+            }
+            keep = first.getValue();
+            it.remove();
+        }
+        if (keep != null) {
+            filesetForRelease.put(null, keep);
+        }
+    }
+
+    /**
+     * {@return whether this archive has nothing to archive}
+     * Note that this method may return {@code false} even when there is zero file to archive.
+     * It may happen if {@link AbstractJarMojo#skipIfEmpty} is {@code false}. In such case, the
+     * "empty" <abbr>JAR</abbr> file will still contain at {@code META-INF/MANIFEST.MF} file.
+     *
+     * <h4>Prerequisites</h4>
+     * The {@link #prune(boolean)} method should be invoked before this method for accurate result.
+     */
+    public boolean isEmpty() {
+        return filesetForRelease.isEmpty();
+    }
+
+    /**
+     * Checks whether the <abbr>JAR</abbr> file already exists and can be reused.
+     * This method verifies that the <abbr>JAR</abbr> file contains all the files to archive,
+     * contains no extra file, and no file to archive is newer than the <abbr>JAR</abbr> file.
+     *
+     * <p>This method can be invoked only once.
+     * If invoked more often, it returns {@code false} on all subsequent invocations.</p>
+     *
+     * @return whether the <abbr>JAR</abbr> file already exists and can be reused
+     */
+    public boolean isUpToDateJAR() {
+        final TimestampCheck tc = existingJAR;
+        if (tc == null) {
+            return false;
+        }
+        existingJAR = null; // Let GC do its job.
+        return tc.isUpToDateJAR(filesetForRelease.values());
+    }
+
+    /**
+     * Returns an initially empty set of files or directories for the specified target Java release.
+     *
+     * @param directory the base directory of the files to archive
+     * @param version the target Java release, or {@code null} for the base version
+     * @return container where to declare files and directories to archive
+     */
+    FileSet newTargetRelease(Path directory, Runtime.Version version) {
+        return filesetForRelease.computeIfAbsent(version, (key) -> new FileSet(directory));
+    }
+
+    /**
+     * Sets the {@code --main-class} option to the value of the {@code Main-Class} entry of the given manifest.
+     * As an extension, this method accepts the {@code module/classname} syntax (a syntax already used in some
+     * Java tools). If a module is specified, the main class is kept only if the module match. The intent is to
+     * allow users to specify on which module the main class applies when they use plugin configuration.
+     *
+     * <p>This method may modify the {@code content} manifest. Caller shall ensure that the given manifest
+     * is not a shared instance. This method returns whether a change has actually been done.</p>
+     *
+     * @param content combination of existing {@code MANIFEST.MF} and manifest inferred from configuration, or null
+     * @return whether the given manifest has been modified by this method
+     */
+    boolean setMainClass(Manifest content) {
+        if (content == null || mainClass != null) {
+            return false;
+        }
+        // We need to remove the attribute, otherwise it will conflict with `--main-class`.
+        mainClass = (String) content.getMainAttributes().remove(Attributes.Name.MAIN_CLASS);
+        if (mainClass != null) {
+            int s = mainClass.indexOf('/');
+            if (s >= 0) {
+                if (mainClass.substring(0, s).strip().equals(moduleName)) {
+                    mainClass = mainClass.substring(s + 1).strip();
+                } else {
+                    mainClass = null; // Main class is defined for another module.
+                }
+            }
+        }
+        return mainClass != null;
+    }
+
+    /**
+     * Sets the {@code --manifest} option to the given value if that option was not already set.
+     *
+     * @param file path to the manifest file
+     * @param force whether to set the manifest even if already set
+     * @return whether the manifest has been set
+     */
+    boolean setManifest(Path file, boolean force) {
+        if (manifest == null || force) {
+            manifest = file;
+            return true;
+        }
+        return false;
+    }
+
+    /**
+     * Merges the manifest of this module with the manifest specified in plugin configuration.
+     * If both {@code file} and {@code content} are non-null, then {@code content} must be the
+     * result of reading {@code file}.
+     *
+     * <p>This method never modifies the given {@code content} object. If manifest are merged,
+     * a new {@link Manifest} instance is created. Therefore, caller can check whether this
+     * method returned a new instance as a way to recognize that a merge occurred.</p>
+     *
+     * <p>If a merge occurs, the content specified to {@link #setManifest(Path)} has precedence.
+     * It should be the {@code target/classes/META-INF/MANIFEST.MF} file (or modular equivalent).</p>
+     *
+     * @param  file     an additional manifest file, or {@code null}
+     * @param  content  the content of {@code file}, or a standalone manifest produced at runtime
+     * @return the merged manifest as a new instance if some changes were necessary
+     * @throws IOException if an error occurred while reading a manifest file
+     */
+    Manifest mergeManifest(Path file, Manifest content) throws IOException {
+        if (manifest == null) {
+            manifest = file;
+        } else if (file != null && Files.isSameFile(file, manifest)) {
+            // Nothing to merge because of the constraint that `content` must be the content of `file`.
+        } else {
+            try (InputStream in = Files.newInputStream(manifest)) {
+                // No need to wrap in `BufferedInputStream`.
+                if (content != null) {
+                    content = new Manifest(content);
+                    content.read(in);
+                } else {
+                    content = new Manifest(in);
+                }
+            }
+        }
+        return content;
+    }
+
+    /**
+     * Adds to the given list the arguments to provide to the "jar" tool for each version.
+     * Elements added to the list shall be instances of {@link String} or {@link Path}.
+     * Callers should have added the following options (if applicable) before to invoke this method:
+     *
+     * <ul>
+     *   <li>{@code --create}</li>
+     *   <li>{@code --no-compress}</li>
+     *   <li>{@code --date} followed by the output time stamp</li>
+     *   <li>{@code --module-version} followed by module version</li>
+     *   <li>{@code --hash-modules} followed by patters of module names</li>
+     *   <li>{@code --module-path} followed by module path</li>
+     * </ul>
+     *
+     * This method adds the following options:
+     *
+     * <ul>
+     *   <li>{@code --file} followed by the path to the <abbr>JAR</abbr> file</li>
+     *   <li>{@code --manifest} followed by path to the manifest file</li>
+     *   <li>{@code --main-class} followed by fully qualified name class</li>
+     *   <li>{@code --release} followed by Java target release</li>
+     *   <li>{@code -C} followed by directory</li>
+     *   <li>files or directories to archive</li>
+     * </ul>
+     *
+     * @param addTo the list where to add the arguments as {@link String} or {@link Path} instances
+     */
+    void arguments(final List<Object> addTo) {
+        addTo.add("--file");
+        addTo.add(jarFile);
+        if (manifest != null) {
+            addTo.add("--manifest");
+            addTo.add(manifest);
+        }
+        if (mainClass != null) {
+            addTo.add("--main-class");
+            addTo.add(mainClass);
+        }
+        if (mavenFiles != null) {
+            addTo.add("-C");
+            addTo.addAll(mavenFiles);
+        }
+        for (Map.Entry<Runtime.Version, FileSet> entry : filesetForRelease.entrySet()) {
+            entry.getValue().arguments(addTo, entry.getKey());
+        }
+    }
+
+    /**
+     * Adds to the given list the arguments to provide to the "jar" tool for validating the <abbr>JAR</abbr> file.

Review Comment:
   Adds the arguments for the "jar" tool for validating the <abbr>JAR</abbr> file.



##########
src/main/java/org/apache/maven/plugins/jar/FileCollector.java:
##########
@@ -0,0 +1,496 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.PathMatcher;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayDeque;
+import java.util.Deque;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.services.PathMatcherFactory;
+
+/**
+ * Dispatch the files in the output directory into the <abbr>JAR</abbr> files to create.
+ * Instead of just archiving as-is the content of the output directory, this class separates
+ * the following subdirectories to the options listed below:
+ *
+ * <ul>
+ *   <li>The {@code META-INF/MANIFEST.MF} file will be given to the {@code --manifest} option.</li>
+ *   <li>Files in the following directories will be given to the {@code --release} option:
+ *     <ul>
+ *       <li>{@code META-INF/versions/}</li>
+ *       <li>{@code META-INF/versions-modular/<module>/}</li>
+ *       <li>{@code <module>/META-INF/versions/}</li>
+ *     </ul>
+ *   </li>
+ * </ul>
+ *
+ * The reason for using the options is that they allow the {@code jar} tool to perform additional verifications.
+ * For example, when using the {@code --release} option, {@code jar} verifies the <abbr>API</abbr> compatibility.
+ */
+final class FileCollector extends SimpleFileVisitor<Path> {
+    /**
+     * The file to check for deciding whether the <abbr>JAR</abbr> is modular.
+     */
+    static final String MODULE_DESCRIPTOR_FILE_NAME = "module-info.class";
+
+    /**
+     * The {@value} directory.
+     * This is part of <abbr>JAR</abbr> file specification.
+     */
+    private static final String VERSIONS = "versions";
+
+    /**
+     * The {@value} directory.
+     * This is Maven-specific.
+     */
+    private static final String VERSIONS_MODULAR = "versions-modular";
+
+    /**
+     * Context (logger, configuration) in which the <abbr>JAR</abbr> file are created.
+     */
+    private final ToolExecutor context;
+
+    /**
+     * Whether to detect multi-release <abbr>JAR</abbr> files.
+     * The default value is {@code true}.
+     *
+     * @see AbstractJarMojo#detectMultiReleaseJar
+     */
+    private final boolean detectMultiReleaseJar;
+
+    /**
+     * Combination of includes and excludes path matcher applied on files.
+     */
+    @Nonnull
+    private final PathMatcher fileMatcher;
+
+    /**
+     * Combination of includes and excludes path matcher applied on directories.
+     */
+    @Nonnull
+    private final PathMatcher directoryMatcher;
+
+    /**
+     * Whether the matchers accept all files and there is no need to sort the files.
+     * In such case, we can declare whole directories to the {@code jar} tool instead
+     * of scanning the directory tree ourselves.
+     */
+    private final boolean addDirectories;
+
+    /**
+     * Files found in the output directory when package hierarchy is used.
+     * At most one of {@code packageHierarchy} and {@link #moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Archive packageHierarchy;
+
+    /**
+     * Files found in the output directory when module hierarchy is used. Keys are module names.
+     * At most one of {@link #packageHierarchy} and {@code moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Map<String, Archive> moduleHierarchy;
+
+    /**
+     * The current module being archived. This field is updated every times that {@code FileCollector}
+     * enters in a new module directory.
+     */
+    @Nonnull
+    private Archive currentModule;
+
+    /**
+     * The module and target Java release currently being scanned. This field is updated every times that
+     * {@code FileCollector} enters in a new module directory or in a new target Java release for a given module.
+     */
+    @Nonnull
+    private Archive.FileSet currentFilesToArchive;
+
+    /**
+     * The current target Java release, or {@code null} if none.
+     */
+    @Nullable
+    private Runtime.Version currentTargetVersion;
+
+    /**
+     * Identification of the kinds of directories being traversed.
+     * The length of this list is the depth in the directory hierarchy.
+     * The last element identifies the type of the current directory.
+     */
+    private final Deque<DirectoryRole> directoryRoles;
+
+    /**
+     * Whether to check when a file is the {@code MANIFEST.MF} file.
+     * This is allowed only when scanning the content of a {@code META-INF} directory.
+     */
+    private boolean checkForManifest;
+
+    /**
+     * Creates a new file collector.
+     *
+     * @param mojo the <abbr>MOJO</abbr> from which to get the configuration
+     * @param context context (logger, configuration) in which the <abbr>JAR</abbr> file are created
+     * @param directory the base directory of the files to archive
+     */
+    FileCollector(AbstractJarMojo mojo, ToolExecutor context, Path directory, PathMatcherFactory matcherFactory) {
+        this.context = context;
+        detectMultiReleaseJar = mojo.detectMultiReleaseJar;
+        directoryRoles = new ArrayDeque<>();
+        fileMatcher = matcherFactory.createPathMatcher(directory, mojo.getIncludes(), mojo.getExcludes(), false);
+        directoryMatcher = matcherFactory.deriveDirectoryMatcher(fileMatcher);
+        addDirectories = !context.isReproducible()
+                && matcherFactory.isIncludesAll(fileMatcher)
+                && matcherFactory.isIncludesAll(directoryMatcher);
+        packageHierarchy = context.newArchive(null, null, directory);
+        moduleHierarchy = new LinkedHashMap<>();
+        resetToPackageHierarchy();
+    }
+
+    /**
+     * Resets this {@code FileCollector} to the state where a package hierarchy is presumed.
+     */
+    private void resetToPackageHierarchy() {
+        currentModule = packageHierarchy;
+        currentFilesToArchive = currentModule.baseRelease();
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a module.
+     * For an output generated by {@code javac} from a module source hierarchy,
+     * the directory name is guaranteed to be the module name.
+     *
+     * @param directory a {@code "<module>"} or {@code "META-INF/versions-modular/<module>"} directory
+     */
+    private void enterModuleDirectory(final Path directory) {
+        String moduleName = directory.getFileName().toString();
+        currentModule = moduleHierarchy.computeIfAbsent(
+                moduleName, (name) -> context.newArchive(name, currentTargetVersion, directory));
+        currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a target Java version.
+     * The {@code useDirectly} argument tells whether the content of this directory will be specified directly
+     * as the content to add in the <abbr>JAR</abbr> file. This argument should be {@code false} when there is
+     * another directory level (the module names) to process before to add content.
+     *
+     * @param directory a {@code "META-INF/versions/<n>"} or {@code "META-INF/versions-modular/<n>"} directory
+     * @param useDirectly whether the directory is {@code "META-INF/versions/<n>"}
+     * @return whether to skip the directory because of invalid version number
+     */
+    private boolean enterVersionDirectory(final Path directory, final boolean useDirectly) {
+        try {
+            currentTargetVersion = Runtime.Version.parse(directory.getFileName().toString());
+        } catch (IllegalArgumentException e) {
+            context.warnInvalidVersion(directory, e);
+            return true;
+        }
+        if (useDirectly) {
+            currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+        }
+        return false;
+    }
+
+    /**
+     * Determines if the given directory should be scanned for files to archive.
+     * This method may also update {@link #currentFilesToArchive} if it detects
+     * that we are entering in a new module or a new target Java release.
+     *
+     * @param directory the directory which will be traversed
+     * @param attributes the directory's basic attributes
+     */
+    @Override
+    @SuppressWarnings("checkstyle:MissingSwitchDefault")
+    public FileVisitResult preVisitDirectory(final Path directory, final BasicFileAttributes attributes)
+            throws IOException {
+        DirectoryRole role;
+        if (directoryRoles.isEmpty()) {
+            role = DirectoryRole.ROOT;
+        } else {
+            if (!directoryMatcher.matches(directory)) {
+                return FileVisitResult.SKIP_SUBTREE;
+            }
+            checkForManifest = false;
+            role = directoryRoles.getLast();
+            switch (role) {
+                case ROOT:
+                    /*
+                     * Entering in any subdirectory of `target/classes` (or other directory to archive).
+                     * We need to handle `META-INF` and modules in a special way, and archive the rest.
+                     */
+                    if (directory.endsWith(MetadataFiles.META_INF)) {
+                        role = DirectoryRole.META_INF;
+                        checkForManifest = true;
+                    } else if (Files.isRegularFile(directory.resolve(MODULE_DESCRIPTOR_FILE_NAME))) {
+                        role = DirectoryRole.NAMED_MODULE;
+                        enterModuleDirectory(directory);
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case META_INF:
+                    /*
+                     * Entering in a subdirectory of `META-INF` or `<module>/META-INF`. We will need to handle
+                     * `MANIFEST.MF`, `versions` and `versions-modular` in a special way, and archive the rest.
+                     */
+                    if (detectMultiReleaseJar && directory.endsWith(VERSIONS)) {
+                        role = DirectoryRole.VERSIONS;
+                    } else if (directory.endsWith(VERSIONS_MODULAR)) {
+                        if (!detectMultiReleaseJar) {
+                            // Used asked for no multi-release JAR.
+                            return FileVisitResult.SKIP_SUBTREE;
+                        }
+                        role = DirectoryRole.VERSIONS_MODULAR;
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case VERSIONS:
+                    /*
+                     * Entering in a `META-INF/versions/<n>/` directory for a specific target Java release.
+                     * May also be a `<module>/META-INF/versions/<n>/` directory, even if the latter is not
+                     * the layout generated by Maven Compiler Plugin.
+                     */
+                    if (enterVersionDirectory(directory, true)) {
+                        // An error occurred while parsing the version number.
+                        return FileVisitResult.SKIP_SUBTREE;
+                    }
+                    role = DirectoryRole.RESOURCES;
+                    break;
+
+                case VERSIONS_MODULAR:
+                    /*
+                     * Entering in a `META-INF/versions-modular/<n>/` directory for a specific target Java release.
+                     * That directory contains all modules for the version.
+                     */
+                    resetToPackageHierarchy(); // No module in particular yet.
+                    if (enterVersionDirectory(directory, false)) {
+                        // An error occurred while parsing the version number.
+                        return FileVisitResult.SKIP_SUBTREE;
+                    }
+                    role = DirectoryRole.MODULES;
+                    break;
+
+                case MODULES:
+                    /*
+                     * Entering in a `META-INF/versions-modular/<n>/<module>` directory.
+                     */
+                    enterModuleDirectory(directory);
+                    role = DirectoryRole.NAMED_MODULE;
+                    break;
+
+                case NAMED_MODULE:
+                    /*
+                     * Entering in a `<module>` or `META-INF/versions-modular/<n>/<module>` subdirectory.
+                     * A module could have its own `META-INF` subdirectory, so we need to check again.
+                     */
+                    if (directory.endsWith(MetadataFiles.META_INF)) {
+                        role = DirectoryRole.META_INF;
+                        checkForManifest = true;
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+            }
+        }
+        /*
+         * Do not move this condition inside the `switch` block because `role` may have been modified.
+         * The `role` value is now the role of `directory`, not anymore the role of parent directory.

Review Comment:
   delete anymore



##########
src/main/java/org/apache/maven/plugins/jar/AbstractJarMojo.java:
##########
@@ -72,23 +72,20 @@ public abstract class AbstractJarMojo implements org.apache.maven.api.plugin.Moj
     protected String[] excludes;
 
     /**
-     * Directory containing the generated JAR.
+     * Directory containing the generated <abbr>JAR</abbr> files.
      */
     @Parameter(defaultValue = "${project.build.directory}", required = true)
     protected Path outputDirectory;
 
     /**
-     * Name of the generated JAR.
+     * Name of the generated <abbr>JAR</abbr> file.

Review Comment:
   without the title attribute abbr isn't helpful. I'm not sure we need it here at all.



##########
src/main/java/org/apache/maven/plugins/jar/AbstractJarMojo.java:
##########
@@ -136,18 +142,26 @@ public abstract class AbstractJarMojo implements org.apache.maven.api.plugin.Moj
      * Timestamp for reproducible output archive entries.
      * This is either formatted as ISO 8601 extended offset date-time
      * (e.g. in UTC such as '2011-12-03T10:15:30Z' or with an offset '2019-10-05T20:37:42+06:00'),
-     * or as an integer representing seconds since the epoch
-     * (like <a href="https://reproducible-builds.org/docs/source-date-epoch/">SOURCE_DATE_EPOCH</a>).
+     * or as an integer representing seconds since the Java epoch (January 1st, 1970).
+     * If not configured or disabled,
+     * the <a href="https://reproducible-builds.org/docs/source-date-epoch/">SOURCE_DATE_EPOCH</a>
+     * environment variable is used as a fallback value,
+     * to ease forcing Reproducible Build externally when the build has not enabled it natively in <abbr>POM</abbr>.
+     *
+     * <p>This property is supported only with Java Development Kit (<abbr>JDK</abbr>) version 19 or later.</p>

Review Comment:
   only supported in
   
   Java Development Kit (<abbr>JDK</abbr>) version 19 --> Java 19



##########
src/main/java/org/apache/maven/plugins/jar/AbstractJarMojo.java:
##########
@@ -136,18 +142,26 @@ public abstract class AbstractJarMojo implements org.apache.maven.api.plugin.Moj
      * Timestamp for reproducible output archive entries.
      * This is either formatted as ISO 8601 extended offset date-time
      * (e.g. in UTC such as '2011-12-03T10:15:30Z' or with an offset '2019-10-05T20:37:42+06:00'),
-     * or as an integer representing seconds since the epoch
-     * (like <a href="https://reproducible-builds.org/docs/source-date-epoch/">SOURCE_DATE_EPOCH</a>).
+     * or as an integer representing seconds since the Java epoch (January 1st, 1970).
+     * If not configured or disabled,
+     * the <a href="https://reproducible-builds.org/docs/source-date-epoch/">SOURCE_DATE_EPOCH</a>
+     * environment variable is used as a fallback value,
+     * to ease forcing Reproducible Build externally when the build has not enabled it natively in <abbr>POM</abbr>.
+     *
+     * <p>This property is supported only with Java Development Kit (<abbr>JDK</abbr>) version 19 or later.</p>
      *
      * @since 3.2.0
      */
     @Parameter(defaultValue = "${project.build.outputTimestamp}")
     protected String outputTimestamp;
 
     /**
-     * Whether to detect multi-release JAR files.
-     * If the JAR contains the {@code META-INF/versions} directory it will be detected as a multi-release JAR file
-     * ("MRJAR"), adding the {@code Multi-Release: true} attribute to the main section of the JAR {@code MANIFEST.MF}.
+     * Whether to detect multi-release <abbr>JAR</abbr> files.
+     * If the JAR contains the {@code META-INF/versions} directory it will be detected as a multi-release JAR file,
+     * adding the {@code Multi-Release: true} attribute to the main section of the JAR {@code MANIFEST.MF} entry.

Review Comment:
   run-on sentence



##########
src/main/java/org/apache/maven/plugins/jar/FileCollector.java:
##########
@@ -0,0 +1,496 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.PathMatcher;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayDeque;
+import java.util.Deque;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.services.PathMatcherFactory;
+
+/**
+ * Dispatch the files in the output directory into the <abbr>JAR</abbr> files to create.
+ * Instead of just archiving as-is the content of the output directory, this class separates
+ * the following subdirectories to the options listed below:
+ *
+ * <ul>
+ *   <li>The {@code META-INF/MANIFEST.MF} file will be given to the {@code --manifest} option.</li>
+ *   <li>Files in the following directories will be given to the {@code --release} option:
+ *     <ul>
+ *       <li>{@code META-INF/versions/}</li>
+ *       <li>{@code META-INF/versions-modular/<module>/}</li>
+ *       <li>{@code <module>/META-INF/versions/}</li>
+ *     </ul>
+ *   </li>
+ * </ul>
+ *
+ * The reason for using the options is that they allow the {@code jar} tool to perform additional verifications.
+ * For example, when using the {@code --release} option, {@code jar} verifies the <abbr>API</abbr> compatibility.
+ */
+final class FileCollector extends SimpleFileVisitor<Path> {
+    /**
+     * The file to check for deciding whether the <abbr>JAR</abbr> is modular.
+     */
+    static final String MODULE_DESCRIPTOR_FILE_NAME = "module-info.class";
+
+    /**
+     * The {@value} directory.
+     * This is part of <abbr>JAR</abbr> file specification.
+     */
+    private static final String VERSIONS = "versions";
+
+    /**
+     * The {@value} directory.
+     * This is Maven-specific.
+     */
+    private static final String VERSIONS_MODULAR = "versions-modular";
+
+    /**
+     * Context (logger, configuration) in which the <abbr>JAR</abbr> file are created.
+     */
+    private final ToolExecutor context;
+
+    /**
+     * Whether to detect multi-release <abbr>JAR</abbr> files.
+     * The default value is {@code true}.
+     *
+     * @see AbstractJarMojo#detectMultiReleaseJar
+     */
+    private final boolean detectMultiReleaseJar;
+
+    /**
+     * Combination of includes and excludes path matcher applied on files.
+     */
+    @Nonnull
+    private final PathMatcher fileMatcher;
+
+    /**
+     * Combination of includes and excludes path matcher applied on directories.
+     */
+    @Nonnull
+    private final PathMatcher directoryMatcher;
+
+    /**
+     * Whether the matchers accept all files and there is no need to sort the files.
+     * In such case, we can declare whole directories to the {@code jar} tool instead
+     * of scanning the directory tree ourselves.
+     */
+    private final boolean addDirectories;
+
+    /**
+     * Files found in the output directory when package hierarchy is used.
+     * At most one of {@code packageHierarchy} and {@link #moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Archive packageHierarchy;
+
+    /**
+     * Files found in the output directory when module hierarchy is used. Keys are module names.
+     * At most one of {@link #packageHierarchy} and {@code moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Map<String, Archive> moduleHierarchy;
+
+    /**
+     * The current module being archived. This field is updated every times that {@code FileCollector}
+     * enters in a new module directory.
+     */
+    @Nonnull
+    private Archive currentModule;
+
+    /**
+     * The module and target Java release currently being scanned. This field is updated every times that
+     * {@code FileCollector} enters in a new module directory or in a new target Java release for a given module.
+     */
+    @Nonnull
+    private Archive.FileSet currentFilesToArchive;
+
+    /**
+     * The current target Java release, or {@code null} if none.
+     */
+    @Nullable
+    private Runtime.Version currentTargetVersion;
+
+    /**
+     * Identification of the kinds of directories being traversed.
+     * The length of this list is the depth in the directory hierarchy.
+     * The last element identifies the type of the current directory.
+     */
+    private final Deque<DirectoryRole> directoryRoles;
+
+    /**
+     * Whether to check when a file is the {@code MANIFEST.MF} file.
+     * This is allowed only when scanning the content of a {@code META-INF} directory.
+     */
+    private boolean checkForManifest;
+
+    /**
+     * Creates a new file collector.
+     *
+     * @param mojo the <abbr>MOJO</abbr> from which to get the configuration
+     * @param context context (logger, configuration) in which the <abbr>JAR</abbr> file are created
+     * @param directory the base directory of the files to archive
+     */
+    FileCollector(AbstractJarMojo mojo, ToolExecutor context, Path directory, PathMatcherFactory matcherFactory) {
+        this.context = context;
+        detectMultiReleaseJar = mojo.detectMultiReleaseJar;
+        directoryRoles = new ArrayDeque<>();
+        fileMatcher = matcherFactory.createPathMatcher(directory, mojo.getIncludes(), mojo.getExcludes(), false);
+        directoryMatcher = matcherFactory.deriveDirectoryMatcher(fileMatcher);
+        addDirectories = !context.isReproducible()
+                && matcherFactory.isIncludesAll(fileMatcher)
+                && matcherFactory.isIncludesAll(directoryMatcher);
+        packageHierarchy = context.newArchive(null, null, directory);
+        moduleHierarchy = new LinkedHashMap<>();
+        resetToPackageHierarchy();
+    }
+
+    /**
+     * Resets this {@code FileCollector} to the state where a package hierarchy is presumed.
+     */
+    private void resetToPackageHierarchy() {
+        currentModule = packageHierarchy;
+        currentFilesToArchive = currentModule.baseRelease();
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a module.
+     * For an output generated by {@code javac} from a module source hierarchy,
+     * the directory name is guaranteed to be the module name.
+     *
+     * @param directory a {@code "<module>"} or {@code "META-INF/versions-modular/<module>"} directory
+     */
+    private void enterModuleDirectory(final Path directory) {
+        String moduleName = directory.getFileName().toString();
+        currentModule = moduleHierarchy.computeIfAbsent(
+                moduleName, (name) -> context.newArchive(name, currentTargetVersion, directory));
+        currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a target Java version.
+     * The {@code useDirectly} argument tells whether the content of this directory will be specified directly
+     * as the content to add in the <abbr>JAR</abbr> file. This argument should be {@code false} when there is
+     * another directory level (the module names) to process before to add content.
+     *
+     * @param directory a {@code "META-INF/versions/<n>"} or {@code "META-INF/versions-modular/<n>"} directory
+     * @param useDirectly whether the directory is {@code "META-INF/versions/<n>"}
+     * @return whether to skip the directory because of invalid version number
+     */
+    private boolean enterVersionDirectory(final Path directory, final boolean useDirectly) {
+        try {
+            currentTargetVersion = Runtime.Version.parse(directory.getFileName().toString());
+        } catch (IllegalArgumentException e) {
+            context.warnInvalidVersion(directory, e);
+            return true;
+        }
+        if (useDirectly) {
+            currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+        }
+        return false;
+    }
+
+    /**
+     * Determines if the given directory should be scanned for files to archive.
+     * This method may also update {@link #currentFilesToArchive} if it detects
+     * that we are entering in a new module or a new target Java release.
+     *
+     * @param directory the directory which will be traversed
+     * @param attributes the directory's basic attributes
+     */
+    @Override
+    @SuppressWarnings("checkstyle:MissingSwitchDefault")
+    public FileVisitResult preVisitDirectory(final Path directory, final BasicFileAttributes attributes)
+            throws IOException {
+        DirectoryRole role;
+        if (directoryRoles.isEmpty()) {
+            role = DirectoryRole.ROOT;
+        } else {
+            if (!directoryMatcher.matches(directory)) {
+                return FileVisitResult.SKIP_SUBTREE;
+            }
+            checkForManifest = false;
+            role = directoryRoles.getLast();
+            switch (role) {
+                case ROOT:
+                    /*
+                     * Entering in any subdirectory of `target/classes` (or other directory to archive).
+                     * We need to handle `META-INF` and modules in a special way, and archive the rest.
+                     */
+                    if (directory.endsWith(MetadataFiles.META_INF)) {
+                        role = DirectoryRole.META_INF;
+                        checkForManifest = true;
+                    } else if (Files.isRegularFile(directory.resolve(MODULE_DESCRIPTOR_FILE_NAME))) {
+                        role = DirectoryRole.NAMED_MODULE;
+                        enterModuleDirectory(directory);
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case META_INF:
+                    /*
+                     * Entering in a subdirectory of `META-INF` or `<module>/META-INF`. We will need to handle
+                     * `MANIFEST.MF`, `versions` and `versions-modular` in a special way, and archive the rest.
+                     */
+                    if (detectMultiReleaseJar && directory.endsWith(VERSIONS)) {
+                        role = DirectoryRole.VERSIONS;
+                    } else if (directory.endsWith(VERSIONS_MODULAR)) {
+                        if (!detectMultiReleaseJar) {
+                            // Used asked for no multi-release JAR.
+                            return FileVisitResult.SKIP_SUBTREE;
+                        }
+                        role = DirectoryRole.VERSIONS_MODULAR;
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case VERSIONS:
+                    /*
+                     * Entering in a `META-INF/versions/<n>/` directory for a specific target Java release.
+                     * May also be a `<module>/META-INF/versions/<n>/` directory, even if the latter is not
+                     * the layout generated by Maven Compiler Plugin.
+                     */
+                    if (enterVersionDirectory(directory, true)) {
+                        // An error occurred while parsing the version number.
+                        return FileVisitResult.SKIP_SUBTREE;
+                    }
+                    role = DirectoryRole.RESOURCES;
+                    break;
+
+                case VERSIONS_MODULAR:
+                    /*
+                     * Entering in a `META-INF/versions-modular/<n>/` directory for a specific target Java release.
+                     * That directory contains all modules for the version.
+                     */
+                    resetToPackageHierarchy(); // No module in particular yet.
+                    if (enterVersionDirectory(directory, false)) {
+                        // An error occurred while parsing the version number.
+                        return FileVisitResult.SKIP_SUBTREE;
+                    }
+                    role = DirectoryRole.MODULES;
+                    break;
+
+                case MODULES:
+                    /*
+                     * Entering in a `META-INF/versions-modular/<n>/<module>` directory.
+                     */
+                    enterModuleDirectory(directory);
+                    role = DirectoryRole.NAMED_MODULE;
+                    break;
+
+                case NAMED_MODULE:
+                    /*
+                     * Entering in a `<module>` or `META-INF/versions-modular/<n>/<module>` subdirectory.
+                     * A module could have its own `META-INF` subdirectory, so we need to check again.
+                     */
+                    if (directory.endsWith(MetadataFiles.META_INF)) {
+                        role = DirectoryRole.META_INF;
+                        checkForManifest = true;
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+            }
+        }
+        /*
+         * Do not move this condition inside the `switch` block because `role` may have been modified.
+         * The `role` value is now the role of `directory`, not anymore the role of parent directory.
+         */
+        if (addDirectories && role == DirectoryRole.RESOURCES) {
+            currentFilesToArchive.add(directory, attributes, true);
+            /*
+             * Since we are skipping the whole directory, `postVisitDirectory(…)` will not be invoked.
+             * We must reset `currentFilesToArchive` and `currentTargetVersion` by an explicit call.
+             * This is important mostly after we added a whole `META-INF/versions/<n>` directory,
+             * otherwise base files visited afterwards (directory iteration order is unspecified)

Review Comment:
   run-on sentence



##########
src/main/java/org/apache/maven/plugins/jar/FileCollector.java:
##########
@@ -0,0 +1,496 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.PathMatcher;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayDeque;
+import java.util.Deque;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.services.PathMatcherFactory;
+
+/**
+ * Dispatch the files in the output directory into the <abbr>JAR</abbr> files to create.
+ * Instead of just archiving as-is the content of the output directory, this class separates
+ * the following subdirectories to the options listed below:
+ *
+ * <ul>
+ *   <li>The {@code META-INF/MANIFEST.MF} file will be given to the {@code --manifest} option.</li>
+ *   <li>Files in the following directories will be given to the {@code --release} option:
+ *     <ul>
+ *       <li>{@code META-INF/versions/}</li>
+ *       <li>{@code META-INF/versions-modular/<module>/}</li>
+ *       <li>{@code <module>/META-INF/versions/}</li>
+ *     </ul>
+ *   </li>
+ * </ul>
+ *
+ * The reason for using the options is that they allow the {@code jar} tool to perform additional verifications.
+ * For example, when using the {@code --release} option, {@code jar} verifies the <abbr>API</abbr> compatibility.
+ */
+final class FileCollector extends SimpleFileVisitor<Path> {
+    /**
+     * The file to check for deciding whether the <abbr>JAR</abbr> is modular.
+     */
+    static final String MODULE_DESCRIPTOR_FILE_NAME = "module-info.class";
+
+    /**
+     * The {@value} directory.
+     * This is part of <abbr>JAR</abbr> file specification.
+     */
+    private static final String VERSIONS = "versions";
+
+    /**
+     * The {@value} directory.
+     * This is Maven-specific.
+     */
+    private static final String VERSIONS_MODULAR = "versions-modular";
+
+    /**
+     * Context (logger, configuration) in which the <abbr>JAR</abbr> file are created.
+     */
+    private final ToolExecutor context;
+
+    /**
+     * Whether to detect multi-release <abbr>JAR</abbr> files.
+     * The default value is {@code true}.
+     *
+     * @see AbstractJarMojo#detectMultiReleaseJar
+     */
+    private final boolean detectMultiReleaseJar;
+
+    /**
+     * Combination of includes and excludes path matcher applied on files.
+     */
+    @Nonnull
+    private final PathMatcher fileMatcher;
+
+    /**
+     * Combination of includes and excludes path matcher applied on directories.
+     */
+    @Nonnull
+    private final PathMatcher directoryMatcher;
+
+    /**
+     * Whether the matchers accept all files and there is no need to sort the files.
+     * In such case, we can declare whole directories to the {@code jar} tool instead
+     * of scanning the directory tree ourselves.
+     */
+    private final boolean addDirectories;
+
+    /**
+     * Files found in the output directory when package hierarchy is used.
+     * At most one of {@code packageHierarchy} and {@link #moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Archive packageHierarchy;
+
+    /**
+     * Files found in the output directory when module hierarchy is used. Keys are module names.
+     * At most one of {@link #packageHierarchy} and {@code moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Map<String, Archive> moduleHierarchy;
+
+    /**
+     * The current module being archived. This field is updated every times that {@code FileCollector}
+     * enters in a new module directory.
+     */
+    @Nonnull
+    private Archive currentModule;
+
+    /**
+     * The module and target Java release currently being scanned. This field is updated every times that
+     * {@code FileCollector} enters in a new module directory or in a new target Java release for a given module.
+     */
+    @Nonnull
+    private Archive.FileSet currentFilesToArchive;
+
+    /**
+     * The current target Java release, or {@code null} if none.
+     */
+    @Nullable
+    private Runtime.Version currentTargetVersion;
+
+    /**
+     * Identification of the kinds of directories being traversed.
+     * The length of this list is the depth in the directory hierarchy.
+     * The last element identifies the type of the current directory.
+     */
+    private final Deque<DirectoryRole> directoryRoles;
+
+    /**
+     * Whether to check when a file is the {@code MANIFEST.MF} file.
+     * This is allowed only when scanning the content of a {@code META-INF} directory.
+     */
+    private boolean checkForManifest;
+
+    /**
+     * Creates a new file collector.
+     *
+     * @param mojo the <abbr>MOJO</abbr> from which to get the configuration
+     * @param context context (logger, configuration) in which the <abbr>JAR</abbr> file are created
+     * @param directory the base directory of the files to archive
+     */
+    FileCollector(AbstractJarMojo mojo, ToolExecutor context, Path directory, PathMatcherFactory matcherFactory) {
+        this.context = context;
+        detectMultiReleaseJar = mojo.detectMultiReleaseJar;
+        directoryRoles = new ArrayDeque<>();
+        fileMatcher = matcherFactory.createPathMatcher(directory, mojo.getIncludes(), mojo.getExcludes(), false);
+        directoryMatcher = matcherFactory.deriveDirectoryMatcher(fileMatcher);
+        addDirectories = !context.isReproducible()
+                && matcherFactory.isIncludesAll(fileMatcher)
+                && matcherFactory.isIncludesAll(directoryMatcher);
+        packageHierarchy = context.newArchive(null, null, directory);
+        moduleHierarchy = new LinkedHashMap<>();
+        resetToPackageHierarchy();
+    }
+
+    /**
+     * Resets this {@code FileCollector} to the state where a package hierarchy is presumed.
+     */
+    private void resetToPackageHierarchy() {
+        currentModule = packageHierarchy;
+        currentFilesToArchive = currentModule.baseRelease();
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a module.
+     * For an output generated by {@code javac} from a module source hierarchy,
+     * the directory name is guaranteed to be the module name.
+     *
+     * @param directory a {@code "<module>"} or {@code "META-INF/versions-modular/<module>"} directory
+     */
+    private void enterModuleDirectory(final Path directory) {
+        String moduleName = directory.getFileName().toString();
+        currentModule = moduleHierarchy.computeIfAbsent(
+                moduleName, (name) -> context.newArchive(name, currentTargetVersion, directory));
+        currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a target Java version.
+     * The {@code useDirectly} argument tells whether the content of this directory will be specified directly
+     * as the content to add in the <abbr>JAR</abbr> file. This argument should be {@code false} when there is
+     * another directory level (the module names) to process before to add content.
+     *
+     * @param directory a {@code "META-INF/versions/<n>"} or {@code "META-INF/versions-modular/<n>"} directory
+     * @param useDirectly whether the directory is {@code "META-INF/versions/<n>"}
+     * @return whether to skip the directory because of invalid version number
+     */
+    private boolean enterVersionDirectory(final Path directory, final boolean useDirectly) {
+        try {
+            currentTargetVersion = Runtime.Version.parse(directory.getFileName().toString());
+        } catch (IllegalArgumentException e) {
+            context.warnInvalidVersion(directory, e);
+            return true;
+        }
+        if (useDirectly) {
+            currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+        }
+        return false;
+    }
+
+    /**
+     * Determines if the given directory should be scanned for files to archive.
+     * This method may also update {@link #currentFilesToArchive} if it detects
+     * that we are entering in a new module or a new target Java release.
+     *
+     * @param directory the directory which will be traversed
+     * @param attributes the directory's basic attributes
+     */
+    @Override
+    @SuppressWarnings("checkstyle:MissingSwitchDefault")
+    public FileVisitResult preVisitDirectory(final Path directory, final BasicFileAttributes attributes)
+            throws IOException {
+        DirectoryRole role;
+        if (directoryRoles.isEmpty()) {
+            role = DirectoryRole.ROOT;
+        } else {
+            if (!directoryMatcher.matches(directory)) {
+                return FileVisitResult.SKIP_SUBTREE;
+            }
+            checkForManifest = false;
+            role = directoryRoles.getLast();
+            switch (role) {
+                case ROOT:
+                    /*
+                     * Entering in any subdirectory of `target/classes` (or other directory to archive).
+                     * We need to handle `META-INF` and modules in a special way, and archive the rest.
+                     */
+                    if (directory.endsWith(MetadataFiles.META_INF)) {
+                        role = DirectoryRole.META_INF;
+                        checkForManifest = true;
+                    } else if (Files.isRegularFile(directory.resolve(MODULE_DESCRIPTOR_FILE_NAME))) {
+                        role = DirectoryRole.NAMED_MODULE;
+                        enterModuleDirectory(directory);
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case META_INF:
+                    /*
+                     * Entering in a subdirectory of `META-INF` or `<module>/META-INF`. We will need to handle
+                     * `MANIFEST.MF`, `versions` and `versions-modular` in a special way, and archive the rest.
+                     */
+                    if (detectMultiReleaseJar && directory.endsWith(VERSIONS)) {
+                        role = DirectoryRole.VERSIONS;
+                    } else if (directory.endsWith(VERSIONS_MODULAR)) {
+                        if (!detectMultiReleaseJar) {
+                            // Used asked for no multi-release JAR.
+                            return FileVisitResult.SKIP_SUBTREE;
+                        }
+                        role = DirectoryRole.VERSIONS_MODULAR;
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case VERSIONS:
+                    /*
+                     * Entering in a `META-INF/versions/<n>/` directory for a specific target Java release.
+                     * May also be a `<module>/META-INF/versions/<n>/` directory, even if the latter is not
+                     * the layout generated by Maven Compiler Plugin.
+                     */
+                    if (enterVersionDirectory(directory, true)) {
+                        // An error occurred while parsing the version number.
+                        return FileVisitResult.SKIP_SUBTREE;
+                    }
+                    role = DirectoryRole.RESOURCES;
+                    break;
+
+                case VERSIONS_MODULAR:
+                    /*
+                     * Entering in a `META-INF/versions-modular/<n>/` directory for a specific target Java release.
+                     * That directory contains all modules for the version.
+                     */
+                    resetToPackageHierarchy(); // No module in particular yet.
+                    if (enterVersionDirectory(directory, false)) {
+                        // An error occurred while parsing the version number.
+                        return FileVisitResult.SKIP_SUBTREE;
+                    }
+                    role = DirectoryRole.MODULES;
+                    break;
+
+                case MODULES:
+                    /*
+                     * Entering in a `META-INF/versions-modular/<n>/<module>` directory.
+                     */
+                    enterModuleDirectory(directory);
+                    role = DirectoryRole.NAMED_MODULE;
+                    break;
+
+                case NAMED_MODULE:
+                    /*
+                     * Entering in a `<module>` or `META-INF/versions-modular/<n>/<module>` subdirectory.
+                     * A module could have its own `META-INF` subdirectory, so we need to check again.
+                     */
+                    if (directory.endsWith(MetadataFiles.META_INF)) {
+                        role = DirectoryRole.META_INF;
+                        checkForManifest = true;
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+            }
+        }
+        /*
+         * Do not move this condition inside the `switch` block because `role` may have been modified.
+         * The `role` value is now the role of `directory`, not anymore the role of parent directory.
+         */
+        if (addDirectories && role == DirectoryRole.RESOURCES) {
+            currentFilesToArchive.add(directory, attributes, true);
+            /*
+             * Since we are skipping the whole directory, `postVisitDirectory(…)` will not be invoked.
+             * We must reset `currentFilesToArchive` and `currentTargetVersion` by an explicit call.
+             * This is important mostly after we added a whole `META-INF/versions/<n>` directory,
+             * otherwise base files visited afterwards (directory iteration order is unspecified)
+             * would be added to this version's file set instead of the base release.
+             */
+            resetToParentDirectoryState();
+            return FileVisitResult.SKIP_SUBTREE;
+        } else {
+            directoryRoles.addLast(role);
+            return FileVisitResult.CONTINUE;
+        }
+    }
+
+    /**
+     * Updates the {@code FileCollector} state after we finished to scan the content of a directory.
+     * The fields to update depend on which directory has been visited (module, version, <i>etc.</i>).
+     *
+     * @param directory the directory which has been traversed
+     * @param error the error that occurred while traversing the directory, or {@code null} if none
+     */
+    @Override
+    public FileVisitResult postVisitDirectory(final Path directory, final IOException error) throws IOException {
+        if (error != null) {
+            throw error;
+        }
+        switch (directoryRoles.removeLast()) {
+            case NAMED_MODULE:
+                // Exited the directory of a single module.
+                resetToPackageHierarchy();
+                break;
+
+            case ROOT:
+                break;
+
+            default:
+                resetToParentDirectoryState();
+        }
+        return FileVisitResult.CONTINUE;
+    }
+
+    /**
+     * Updates {@code FileCollector} to a state suitable to the parent of the directory that we finished to scan.
+     * Contrarily to {@link #postVisitDirectory(Path, IOException)}, this method expects the last element of

Review Comment:
   Contrary



##########
src/main/java/org/apache/maven/plugins/jar/AbstractJarMojo.java:
##########
@@ -207,167 +205,208 @@ protected final Log getLog() {
     protected abstract String getType();
 
     /**
-     * Returns the JAR file to generate, based on an optional classifier.
+     * {@return the scope of dependencies}
+     * It should be {@link PathScope#MAIN_COMPILE} or {@link PathScope#TEST_COMPILE}.
+     * Note that we use compile scope rather than runtime scope because dependencies
+     * cannot appear in {@code requires} statement if they didn't had compile scope.
+     */
+    protected abstract PathScope getDependencyScope();
+
+    /**
+     * {@return the JAR tool to use for archiving the code}
      *
-     * @param basedir the output directory
-     * @param resultFinalName the name of the JAR file
-     * @param classifier an optional classifier
-     * @return the file to generate
+     * @throws MojoException if no JAR tool was found
+     *
+     * @since 4.0.0-beta-2
      */
-    protected Path getJarFile(Path basedir, String resultFinalName, String classifier) {
-        Objects.requireNonNull(basedir, "basedir is not allowed to be null");
-        Objects.requireNonNull(resultFinalName, "finalName is not allowed to be null");
-        String fileName = resultFinalName + (hasClassifier(classifier) ? '-' + classifier : "") + ".jar";
-        return basedir.resolve(fileName);
+    protected ToolProvider getJarTool() throws MojoException {
+        return ToolProvider.findFirst(toolId).orElseThrow(() -> new MojoException("No such \"" + toolId + "\" tool."));
     }
 
     /**
-     * Generates the JAR.
+     * Returns the output time stamp or, as a fallback, the {@code SOURCE_DATE_EPOCH} environment variable.

Review Comment:
   timestamp



##########
src/main/java/org/apache/maven/plugins/jar/AbstractJarMojo.java:
##########
@@ -207,167 +205,208 @@ protected final Log getLog() {
     protected abstract String getType();
 
     /**
-     * Returns the JAR file to generate, based on an optional classifier.
+     * {@return the scope of dependencies}
+     * It should be {@link PathScope#MAIN_COMPILE} or {@link PathScope#TEST_COMPILE}.
+     * Note that we use compile scope rather than runtime scope because dependencies
+     * cannot appear in {@code requires} statement if they didn't had compile scope.
+     */
+    protected abstract PathScope getDependencyScope();
+
+    /**
+     * {@return the JAR tool to use for archiving the code}
      *
-     * @param basedir the output directory
-     * @param resultFinalName the name of the JAR file
-     * @param classifier an optional classifier
-     * @return the file to generate
+     * @throws MojoException if no JAR tool was found
+     *
+     * @since 4.0.0-beta-2
      */
-    protected Path getJarFile(Path basedir, String resultFinalName, String classifier) {
-        Objects.requireNonNull(basedir, "basedir is not allowed to be null");
-        Objects.requireNonNull(resultFinalName, "finalName is not allowed to be null");
-        String fileName = resultFinalName + (hasClassifier(classifier) ? '-' + classifier : "") + ".jar";
-        return basedir.resolve(fileName);
+    protected ToolProvider getJarTool() throws MojoException {

Review Comment:
   do these methods need to be protected? would package access suffice?



##########
src/main/java/org/apache/maven/plugins/jar/FileCollector.java:
##########
@@ -0,0 +1,496 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.PathMatcher;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayDeque;
+import java.util.Deque;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.services.PathMatcherFactory;
+
+/**
+ * Dispatch the files in the output directory into the <abbr>JAR</abbr> files to create.
+ * Instead of just archiving as-is the content of the output directory, this class separates
+ * the following subdirectories to the options listed below:
+ *
+ * <ul>
+ *   <li>The {@code META-INF/MANIFEST.MF} file will be given to the {@code --manifest} option.</li>
+ *   <li>Files in the following directories will be given to the {@code --release} option:
+ *     <ul>
+ *       <li>{@code META-INF/versions/}</li>
+ *       <li>{@code META-INF/versions-modular/<module>/}</li>
+ *       <li>{@code <module>/META-INF/versions/}</li>
+ *     </ul>
+ *   </li>
+ * </ul>
+ *
+ * The reason for using the options is that they allow the {@code jar} tool to perform additional verifications.
+ * For example, when using the {@code --release} option, {@code jar} verifies the <abbr>API</abbr> compatibility.
+ */
+final class FileCollector extends SimpleFileVisitor<Path> {
+    /**
+     * The file to check for deciding whether the <abbr>JAR</abbr> is modular.
+     */
+    static final String MODULE_DESCRIPTOR_FILE_NAME = "module-info.class";
+
+    /**
+     * The {@value} directory.
+     * This is part of <abbr>JAR</abbr> file specification.
+     */
+    private static final String VERSIONS = "versions";
+
+    /**
+     * The {@value} directory.
+     * This is Maven-specific.
+     */
+    private static final String VERSIONS_MODULAR = "versions-modular";
+
+    /**
+     * Context (logger, configuration) in which the <abbr>JAR</abbr> file are created.
+     */
+    private final ToolExecutor context;
+
+    /**
+     * Whether to detect multi-release <abbr>JAR</abbr> files.
+     * The default value is {@code true}.
+     *
+     * @see AbstractJarMojo#detectMultiReleaseJar
+     */
+    private final boolean detectMultiReleaseJar;
+
+    /**
+     * Combination of includes and excludes path matcher applied on files.
+     */
+    @Nonnull
+    private final PathMatcher fileMatcher;
+
+    /**
+     * Combination of includes and excludes path matcher applied on directories.
+     */
+    @Nonnull
+    private final PathMatcher directoryMatcher;
+
+    /**
+     * Whether the matchers accept all files and there is no need to sort the files.
+     * In such case, we can declare whole directories to the {@code jar} tool instead
+     * of scanning the directory tree ourselves.
+     */
+    private final boolean addDirectories;
+
+    /**
+     * Files found in the output directory when package hierarchy is used.
+     * At most one of {@code packageHierarchy} and {@link #moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Archive packageHierarchy;
+
+    /**
+     * Files found in the output directory when module hierarchy is used. Keys are module names.
+     * At most one of {@link #packageHierarchy} and {@code moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Map<String, Archive> moduleHierarchy;
+
+    /**
+     * The current module being archived. This field is updated every times that {@code FileCollector}
+     * enters in a new module directory.
+     */
+    @Nonnull
+    private Archive currentModule;
+
+    /**
+     * The module and target Java release currently being scanned. This field is updated every times that
+     * {@code FileCollector} enters in a new module directory or in a new target Java release for a given module.
+     */
+    @Nonnull
+    private Archive.FileSet currentFilesToArchive;
+
+    /**
+     * The current target Java release, or {@code null} if none.
+     */
+    @Nullable
+    private Runtime.Version currentTargetVersion;
+
+    /**
+     * Identification of the kinds of directories being traversed.
+     * The length of this list is the depth in the directory hierarchy.
+     * The last element identifies the type of the current directory.
+     */
+    private final Deque<DirectoryRole> directoryRoles;
+
+    /**
+     * Whether to check when a file is the {@code MANIFEST.MF} file.
+     * This is allowed only when scanning the content of a {@code META-INF} directory.
+     */
+    private boolean checkForManifest;
+
+    /**
+     * Creates a new file collector.
+     *
+     * @param mojo the <abbr>MOJO</abbr> from which to get the configuration
+     * @param context context (logger, configuration) in which the <abbr>JAR</abbr> file are created
+     * @param directory the base directory of the files to archive
+     */
+    FileCollector(AbstractJarMojo mojo, ToolExecutor context, Path directory, PathMatcherFactory matcherFactory) {
+        this.context = context;
+        detectMultiReleaseJar = mojo.detectMultiReleaseJar;
+        directoryRoles = new ArrayDeque<>();
+        fileMatcher = matcherFactory.createPathMatcher(directory, mojo.getIncludes(), mojo.getExcludes(), false);
+        directoryMatcher = matcherFactory.deriveDirectoryMatcher(fileMatcher);
+        addDirectories = !context.isReproducible()
+                && matcherFactory.isIncludesAll(fileMatcher)
+                && matcherFactory.isIncludesAll(directoryMatcher);
+        packageHierarchy = context.newArchive(null, null, directory);
+        moduleHierarchy = new LinkedHashMap<>();
+        resetToPackageHierarchy();
+    }
+
+    /**
+     * Resets this {@code FileCollector} to the state where a package hierarchy is presumed.
+     */
+    private void resetToPackageHierarchy() {
+        currentModule = packageHierarchy;
+        currentFilesToArchive = currentModule.baseRelease();
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a module.
+     * For an output generated by {@code javac} from a module source hierarchy,
+     * the directory name is guaranteed to be the module name.
+     *
+     * @param directory a {@code "<module>"} or {@code "META-INF/versions-modular/<module>"} directory
+     */
+    private void enterModuleDirectory(final Path directory) {
+        String moduleName = directory.getFileName().toString();
+        currentModule = moduleHierarchy.computeIfAbsent(
+                moduleName, (name) -> context.newArchive(name, currentTargetVersion, directory));
+        currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a target Java version.
+     * The {@code useDirectly} argument tells whether the content of this directory will be specified directly
+     * as the content to add in the <abbr>JAR</abbr> file. This argument should be {@code false} when there is
+     * another directory level (the module names) to process before to add content.
+     *
+     * @param directory a {@code "META-INF/versions/<n>"} or {@code "META-INF/versions-modular/<n>"} directory
+     * @param useDirectly whether the directory is {@code "META-INF/versions/<n>"}
+     * @return whether to skip the directory because of invalid version number
+     */
+    private boolean enterVersionDirectory(final Path directory, final boolean useDirectly) {
+        try {
+            currentTargetVersion = Runtime.Version.parse(directory.getFileName().toString());
+        } catch (IllegalArgumentException e) {
+            context.warnInvalidVersion(directory, e);
+            return true;
+        }
+        if (useDirectly) {
+            currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+        }
+        return false;
+    }
+
+    /**
+     * Determines if the given directory should be scanned for files to archive.
+     * This method may also update {@link #currentFilesToArchive} if it detects
+     * that we are entering in a new module or a new target Java release.
+     *
+     * @param directory the directory which will be traversed
+     * @param attributes the directory's basic attributes
+     */
+    @Override
+    @SuppressWarnings("checkstyle:MissingSwitchDefault")
+    public FileVisitResult preVisitDirectory(final Path directory, final BasicFileAttributes attributes)
+            throws IOException {
+        DirectoryRole role;
+        if (directoryRoles.isEmpty()) {
+            role = DirectoryRole.ROOT;
+        } else {
+            if (!directoryMatcher.matches(directory)) {
+                return FileVisitResult.SKIP_SUBTREE;
+            }
+            checkForManifest = false;
+            role = directoryRoles.getLast();
+            switch (role) {
+                case ROOT:
+                    /*
+                     * Entering in any subdirectory of `target/classes` (or other directory to archive).
+                     * We need to handle `META-INF` and modules in a special way, and archive the rest.
+                     */
+                    if (directory.endsWith(MetadataFiles.META_INF)) {
+                        role = DirectoryRole.META_INF;
+                        checkForManifest = true;
+                    } else if (Files.isRegularFile(directory.resolve(MODULE_DESCRIPTOR_FILE_NAME))) {
+                        role = DirectoryRole.NAMED_MODULE;
+                        enterModuleDirectory(directory);
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case META_INF:
+                    /*
+                     * Entering in a subdirectory of `META-INF` or `<module>/META-INF`. We will need to handle
+                     * `MANIFEST.MF`, `versions` and `versions-modular` in a special way, and archive the rest.
+                     */
+                    if (detectMultiReleaseJar && directory.endsWith(VERSIONS)) {
+                        role = DirectoryRole.VERSIONS;
+                    } else if (directory.endsWith(VERSIONS_MODULAR)) {
+                        if (!detectMultiReleaseJar) {
+                            // Used asked for no multi-release JAR.
+                            return FileVisitResult.SKIP_SUBTREE;
+                        }
+                        role = DirectoryRole.VERSIONS_MODULAR;
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case VERSIONS:
+                    /*
+                     * Entering in a `META-INF/versions/<n>/` directory for a specific target Java release.
+                     * May also be a `<module>/META-INF/versions/<n>/` directory, even if the latter is not
+                     * the layout generated by Maven Compiler Plugin.
+                     */
+                    if (enterVersionDirectory(directory, true)) {
+                        // An error occurred while parsing the version number.
+                        return FileVisitResult.SKIP_SUBTREE;
+                    }
+                    role = DirectoryRole.RESOURCES;
+                    break;
+
+                case VERSIONS_MODULAR:
+                    /*
+                     * Entering in a `META-INF/versions-modular/<n>/` directory for a specific target Java release.
+                     * That directory contains all modules for the version.
+                     */
+                    resetToPackageHierarchy(); // No module in particular yet.
+                    if (enterVersionDirectory(directory, false)) {
+                        // An error occurred while parsing the version number.
+                        return FileVisitResult.SKIP_SUBTREE;
+                    }
+                    role = DirectoryRole.MODULES;
+                    break;
+
+                case MODULES:
+                    /*
+                     * Entering in a `META-INF/versions-modular/<n>/<module>` directory.
+                     */
+                    enterModuleDirectory(directory);
+                    role = DirectoryRole.NAMED_MODULE;
+                    break;
+
+                case NAMED_MODULE:
+                    /*
+                     * Entering in a `<module>` or `META-INF/versions-modular/<n>/<module>` subdirectory.
+                     * A module could have its own `META-INF` subdirectory, so we need to check again.
+                     */
+                    if (directory.endsWith(MetadataFiles.META_INF)) {
+                        role = DirectoryRole.META_INF;
+                        checkForManifest = true;
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+            }
+        }
+        /*
+         * Do not move this condition inside the `switch` block because `role` may have been modified.
+         * The `role` value is now the role of `directory`, not anymore the role of parent directory.
+         */
+        if (addDirectories && role == DirectoryRole.RESOURCES) {
+            currentFilesToArchive.add(directory, attributes, true);
+            /*
+             * Since we are skipping the whole directory, `postVisitDirectory(…)` will not be invoked.
+             * We must reset `currentFilesToArchive` and `currentTargetVersion` by an explicit call.
+             * This is important mostly after we added a whole `META-INF/versions/<n>` directory,
+             * otherwise base files visited afterwards (directory iteration order is unspecified)
+             * would be added to this version's file set instead of the base release.
+             */
+            resetToParentDirectoryState();
+            return FileVisitResult.SKIP_SUBTREE;
+        } else {
+            directoryRoles.addLast(role);
+            return FileVisitResult.CONTINUE;
+        }
+    }
+
+    /**
+     * Updates the {@code FileCollector} state after we finished to scan the content of a directory.
+     * The fields to update depend on which directory has been visited (module, version, <i>etc.</i>).
+     *
+     * @param directory the directory which has been traversed
+     * @param error the error that occurred while traversing the directory, or {@code null} if none
+     */
+    @Override
+    public FileVisitResult postVisitDirectory(final Path directory, final IOException error) throws IOException {
+        if (error != null) {
+            throw error;
+        }
+        switch (directoryRoles.removeLast()) {
+            case NAMED_MODULE:
+                // Exited the directory of a single module.
+                resetToPackageHierarchy();
+                break;
+
+            case ROOT:
+                break;
+
+            default:
+                resetToParentDirectoryState();
+        }
+        return FileVisitResult.CONTINUE;
+    }
+
+    /**
+     * Updates {@code FileCollector} to a state suitable to the parent of the directory that we finished to scan.
+     * Contrarily to {@link #postVisitDirectory(Path, IOException)}, this method expects the last element of
+     * {@link #directoryRoles} to describe the parent directory, not the directory that we finished to visit.
+     */
+    @SuppressWarnings("checkstyle:MissingSwitchDefault")
+    private void resetToParentDirectoryState() {
+        switch (directoryRoles.getLast()) {
+            case VERSIONS:
+            case VERSIONS_MODULAR:
+                // Exited the directory for one target Java release.
+                currentFilesToArchive = currentModule.baseRelease();
+                currentTargetVersion = null;
+                break;
+
+            case META_INF:
+                checkForManifest = true;
+                break;
+        }
+    }
+
+    /**
+     * Archives a single file if accepted by the matcher.
+     *
+     * @param file the file
+     * @param attributes the file's basic attributes
+     */
+    @Override
+    public FileVisitResult visitFile(final Path file, final BasicFileAttributes attributes) {
+        if (fileMatcher.matches(file)) {
+            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.add(file, attributes, false);
+            }
+        }
+        return FileVisitResult.CONTINUE;
+    }
+
+    /**
+     * 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}, then this method ensures that at least one archive
+     * remains even if that archive is empty.
+     *
+     * @param skipIfEmpty value of {@link AbstractJarMojo#skipIfEmpty}
+     */
+    public void prune(boolean skipIfEmpty) {
+        boolean isModuleHierarchy = !moduleHierarchy.isEmpty();
+        moduleHierarchy.values().forEach((archive) -> archive.prune(skipIfEmpty));
+        moduleHierarchy.values().removeIf(Archive::isEmpty);
+        packageHierarchy.prune(isModuleHierarchy || skipIfEmpty);
+    }
+
+    /**
+     * Moves, copies or ignores orphan files.
+     * An orphan file is a file which is not in any module when module hierarchy is used.
+     * For example, some Maven plugins may create files such as {@code META-INF/LICENSE},
+     * {@code META-INF/NOTICE} or {@code META-INF/DEPENDENCIES}. These files are not in
+     * the correct directory (they should be in a {@code "<module>/META-INF"} directory)
+     * because the plugin may not be aware of module hierarchy.
+     *
+     * <p>A possible strategy could be to copy the {@code LICENSE} and {@code NOTICE} files
+     * in each module, and ignore the {@code DEPENDENCIES} file because its content is not
+     * correct for a module. For now, we just log a warning an ignore.</p>

Review Comment:
   warning an ignore?
   
   maybe warning and ignore?



##########
src/main/java/org/apache/maven/plugins/jar/MetadataFiles.java:
##########
@@ -0,0 +1,250 @@
+/*
+ * 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.jar;
+
+import java.io.BufferedWriter;
+import java.io.Closeable;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Properties;
+import java.util.jar.Manifest;
+import java.util.stream.Collectors;
+
+import org.apache.maven.api.ProducedArtifact;
+import org.apache.maven.api.Project;
+import org.apache.maven.shared.archiver.MavenArchiveConfiguration;
+
+/**
+ * Temporary metadata files generated by Maven before inclusion in the archive.
+ * Those files are created in a temporary {@code META-INF} directory when first needed.
+ * Those files are deleted after the build, unless the build failed or Maven was run in verbose mode.
+ */
+final class MetadataFiles implements Closeable {
+    /**
+     * The {@value} directory.
+     * This is part of <abbr>JAR</abbr> file specification.
+     */
+    static final String META_INF = "META-INF";
+
+    /**
+     * The {@value} file.
+     * This is part of <abbr>JAR</abbr> file specification.
+     */
+    static final String MANIFEST = "MANIFEST.MF";
+
+    /**
+     * The subdirectory where to add Maven-specific files.
+     */
+    static final String MAVEN_DIR = "maven";
+
+    /**
+     * The project for which to write metadata files.
+     */
+    private final Project project;
+
+    /**
+     * The output directory (usually {@code ${baseDir}/target/}).
+     */
+    private final Path buildDir;
+
+    /**
+     * All files and directories in the order that they were created.
+     * The first element of this list shall be the root temporary directory created by this class.
+     */
+    private final List<Path> filesToDelete;
+
+    /**
+     * The <abbr>POM</abbr> file to attach to the artifact. This is initially the project <abbr>POM</abbr>,
+     * but will be replaced by a new file generated by {@link ForModule} if module hierarchy is used.
+     * That file may be copied verbatim in the {@code META-INF/maven/} directory of the <abbr>JAR</abbr>.
+     */
+    private Path attachedPOM;
+
+    /**
+     * Creates an initially empty set of temporary metadata files.
+     *
+     * @param project the project for which to write metadata files
+     * @param buildDir the (usually) {@code ${baseDir}/target/} directory
+     */
+    MetadataFiles(Project project, Path buildDir) {
+        this.project = project;
+        this.buildDir = buildDir;
+        filesToDelete = new ArrayList<>();
+        attachedPOM = project.getPomPath();
+    }
+
+    /**
+     * Derives a <abbr>POM</abbr> as the intersection of the given {@code model} and {@code archive}.
+     *
+     * @param context the tool executor which is generating all archives
+     * @param archive the archive for which to generate a <abbr>POM</abbr>
+     * @param manifest manifest to use for deriving project name, or {@code null} if none
+     * @throws IOException if an error occurred while reading the {@code module-info.class} file
+     *         or while writing the <abbr>POM</abbr> file
+     */
+    void deriveModulePOM(ToolExecutor context, Archive archive, Manifest manifest) throws IOException {
+        var pom = context.pomDerivation.new ForModule(archive, manifest);
+        pom.writeModulePOM();
+        attachedPOM = pom.pomFile;
+        archive.pomFile = pom.pomFile;
+    }
+
+    /**
+     * Adds the given manifest in a temporary file.
+     * The file will be deleted when {@link #close()} is invoked.
+     *
+     * @param manifest the manifest to write
+     * @return the temporary manifest file
+     * @throws IOException if an error occurred while writing the file
+     */
+    public Path addManifest(final Manifest manifest) throws IOException {
+        Path file = baseDirectory().resolve(MANIFEST);
+        try (OutputStream out = Files.newOutputStream(file)) {
+            filesToDelete.add(file);
+            manifest.write(out);
+        }
+        return file;
+    }
+
+    /**
+     * {@return the root temporary directory for the files created by this class}
+     * The directory is created the first time that this method is invoked.
+     *
+     * @throws IOException if an error occurred while creating the temporary directory
+     */
+    private Path baseDirectory() throws IOException {
+        if (filesToDelete.isEmpty()) {
+            filesToDelete.add(Files.createTempDirectory(buildDir, "classes-"));
+        }
+        return filesToDelete.get(0);
+    }
+
+    /**
+     * Creates a new directory and adds it to the list of files to delete after the build.
+     *
+     * @param dir the existing directory where to create a sub-directory
+     * @param path path to the subdirectory to create
+     * @return the new directory
+     * @throws IOException if an error occurred while creating the subdirectory
+     */
+    private Path createDirectories(Path dir, String... path) throws IOException {
+        for (String subdir : path) {
+            dir = Files.createDirectory(dir.resolve(subdir));
+            filesToDelete.add(dir);
+        }
+        return dir;
+    }
+
+    /**
+     * Writes the {@code pom.xml} and {@code pom.properties} files.
+     * This method returns the base temporary directory followed by files that the "jar" tool will need to add
+     *
+     * @param archive archive configuration
+     * @param reproducible whether to enforce reproducible build
+     * @return arguments for the "jar" tool
+     * @throws IOException if an error occurred while writing the files
+     */
+    public List<Path> addPOM(final MavenArchiveConfiguration archive, final boolean reproducible) throws IOException {
+        final String groupId = project.getGroupId();
+        final String artifactId = project.getArtifactId();
+        final String version;
+        final ProducedArtifact pom = project.getPomArtifact();
+        if (pom.isSnapshot()) {
+            version = pom.getVersion().toString();
+        } else {
+            version = project.getVersion();
+        }
+        final Path baseDir = baseDirectory();
+        final Path mavenDir = createDirectories(baseDir, META_INF, MAVEN_DIR, groupId, artifactId);
+        final Path pomFile = linkOrCopy(attachedPOM, mavenDir.resolve("pom.xml"));
+        filesToDelete.add(pomFile); // Add soon for deleting this file even if an exception is thrown below.
+        /*
+         * Subset of above "pom.xml" file but written as a properties file.
+         * If reproducible build is enabled, we will need to reformat after
+         * writing for ensuring a deterministic order of entries.

Review Comment:
   for ensuring a --> to ensure



##########
src/main/java/org/apache/maven/plugins/jar/FileCollector.java:
##########
@@ -0,0 +1,496 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.PathMatcher;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayDeque;
+import java.util.Deque;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.services.PathMatcherFactory;
+
+/**
+ * Dispatch the files in the output directory into the <abbr>JAR</abbr> files to create.
+ * Instead of just archiving as-is the content of the output directory, this class separates
+ * the following subdirectories to the options listed below:
+ *
+ * <ul>
+ *   <li>The {@code META-INF/MANIFEST.MF} file will be given to the {@code --manifest} option.</li>
+ *   <li>Files in the following directories will be given to the {@code --release} option:
+ *     <ul>
+ *       <li>{@code META-INF/versions/}</li>
+ *       <li>{@code META-INF/versions-modular/<module>/}</li>
+ *       <li>{@code <module>/META-INF/versions/}</li>
+ *     </ul>
+ *   </li>
+ * </ul>
+ *
+ * The reason for using the options is that they allow the {@code jar} tool to perform additional verifications.
+ * For example, when using the {@code --release} option, {@code jar} verifies the <abbr>API</abbr> compatibility.
+ */
+final class FileCollector extends SimpleFileVisitor<Path> {
+    /**
+     * The file to check for deciding whether the <abbr>JAR</abbr> is modular.
+     */
+    static final String MODULE_DESCRIPTOR_FILE_NAME = "module-info.class";
+
+    /**
+     * The {@value} directory.
+     * This is part of <abbr>JAR</abbr> file specification.
+     */
+    private static final String VERSIONS = "versions";
+
+    /**
+     * The {@value} directory.
+     * This is Maven-specific.
+     */
+    private static final String VERSIONS_MODULAR = "versions-modular";
+
+    /**
+     * Context (logger, configuration) in which the <abbr>JAR</abbr> file are created.
+     */
+    private final ToolExecutor context;
+
+    /**
+     * Whether to detect multi-release <abbr>JAR</abbr> files.
+     * The default value is {@code true}.
+     *
+     * @see AbstractJarMojo#detectMultiReleaseJar
+     */
+    private final boolean detectMultiReleaseJar;
+
+    /**
+     * Combination of includes and excludes path matcher applied on files.
+     */
+    @Nonnull
+    private final PathMatcher fileMatcher;
+
+    /**
+     * Combination of includes and excludes path matcher applied on directories.
+     */
+    @Nonnull
+    private final PathMatcher directoryMatcher;
+
+    /**
+     * Whether the matchers accept all files and there is no need to sort the files.
+     * In such case, we can declare whole directories to the {@code jar} tool instead
+     * of scanning the directory tree ourselves.
+     */
+    private final boolean addDirectories;
+
+    /**
+     * Files found in the output directory when package hierarchy is used.
+     * At most one of {@code packageHierarchy} and {@link #moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Archive packageHierarchy;
+
+    /**
+     * Files found in the output directory when module hierarchy is used. Keys are module names.
+     * At most one of {@link #packageHierarchy} and {@code moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Map<String, Archive> moduleHierarchy;
+
+    /**
+     * The current module being archived. This field is updated every times that {@code FileCollector}
+     * enters in a new module directory.
+     */
+    @Nonnull
+    private Archive currentModule;
+
+    /**
+     * The module and target Java release currently being scanned. This field is updated every times that
+     * {@code FileCollector} enters in a new module directory or in a new target Java release for a given module.
+     */
+    @Nonnull
+    private Archive.FileSet currentFilesToArchive;
+
+    /**
+     * The current target Java release, or {@code null} if none.
+     */
+    @Nullable
+    private Runtime.Version currentTargetVersion;
+
+    /**
+     * Identification of the kinds of directories being traversed.
+     * The length of this list is the depth in the directory hierarchy.
+     * The last element identifies the type of the current directory.
+     */
+    private final Deque<DirectoryRole> directoryRoles;
+
+    /**
+     * Whether to check when a file is the {@code MANIFEST.MF} file.
+     * This is allowed only when scanning the content of a {@code META-INF} directory.
+     */
+    private boolean checkForManifest;
+
+    /**
+     * Creates a new file collector.
+     *
+     * @param mojo the <abbr>MOJO</abbr> from which to get the configuration
+     * @param context context (logger, configuration) in which the <abbr>JAR</abbr> file are created
+     * @param directory the base directory of the files to archive
+     */
+    FileCollector(AbstractJarMojo mojo, ToolExecutor context, Path directory, PathMatcherFactory matcherFactory) {
+        this.context = context;
+        detectMultiReleaseJar = mojo.detectMultiReleaseJar;
+        directoryRoles = new ArrayDeque<>();
+        fileMatcher = matcherFactory.createPathMatcher(directory, mojo.getIncludes(), mojo.getExcludes(), false);
+        directoryMatcher = matcherFactory.deriveDirectoryMatcher(fileMatcher);
+        addDirectories = !context.isReproducible()
+                && matcherFactory.isIncludesAll(fileMatcher)
+                && matcherFactory.isIncludesAll(directoryMatcher);
+        packageHierarchy = context.newArchive(null, null, directory);
+        moduleHierarchy = new LinkedHashMap<>();
+        resetToPackageHierarchy();
+    }
+
+    /**
+     * Resets this {@code FileCollector} to the state where a package hierarchy is presumed.
+     */
+    private void resetToPackageHierarchy() {
+        currentModule = packageHierarchy;
+        currentFilesToArchive = currentModule.baseRelease();
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a module.
+     * For an output generated by {@code javac} from a module source hierarchy,
+     * the directory name is guaranteed to be the module name.
+     *
+     * @param directory a {@code "<module>"} or {@code "META-INF/versions-modular/<module>"} directory
+     */
+    private void enterModuleDirectory(final Path directory) {
+        String moduleName = directory.getFileName().toString();
+        currentModule = moduleHierarchy.computeIfAbsent(
+                moduleName, (name) -> context.newArchive(name, currentTargetVersion, directory));
+        currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a target Java version.
+     * The {@code useDirectly} argument tells whether the content of this directory will be specified directly
+     * as the content to add in the <abbr>JAR</abbr> file. This argument should be {@code false} when there is
+     * another directory level (the module names) to process before to add content.
+     *
+     * @param directory a {@code "META-INF/versions/<n>"} or {@code "META-INF/versions-modular/<n>"} directory
+     * @param useDirectly whether the directory is {@code "META-INF/versions/<n>"}
+     * @return whether to skip the directory because of invalid version number
+     */
+    private boolean enterVersionDirectory(final Path directory, final boolean useDirectly) {
+        try {
+            currentTargetVersion = Runtime.Version.parse(directory.getFileName().toString());
+        } catch (IllegalArgumentException e) {
+            context.warnInvalidVersion(directory, e);
+            return true;
+        }
+        if (useDirectly) {
+            currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+        }
+        return false;
+    }
+
+    /**
+     * Determines if the given directory should be scanned for files to archive.
+     * This method may also update {@link #currentFilesToArchive} if it detects
+     * that we are entering in a new module or a new target Java release.
+     *
+     * @param directory the directory which will be traversed
+     * @param attributes the directory's basic attributes
+     */
+    @Override
+    @SuppressWarnings("checkstyle:MissingSwitchDefault")
+    public FileVisitResult preVisitDirectory(final Path directory, final BasicFileAttributes attributes)
+            throws IOException {
+        DirectoryRole role;
+        if (directoryRoles.isEmpty()) {
+            role = DirectoryRole.ROOT;
+        } else {
+            if (!directoryMatcher.matches(directory)) {
+                return FileVisitResult.SKIP_SUBTREE;
+            }
+            checkForManifest = false;
+            role = directoryRoles.getLast();
+            switch (role) {
+                case ROOT:
+                    /*
+                     * Entering in any subdirectory of `target/classes` (or other directory to archive).
+                     * We need to handle `META-INF` and modules in a special way, and archive the rest.
+                     */
+                    if (directory.endsWith(MetadataFiles.META_INF)) {
+                        role = DirectoryRole.META_INF;
+                        checkForManifest = true;
+                    } else if (Files.isRegularFile(directory.resolve(MODULE_DESCRIPTOR_FILE_NAME))) {
+                        role = DirectoryRole.NAMED_MODULE;
+                        enterModuleDirectory(directory);
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case META_INF:
+                    /*
+                     * Entering in a subdirectory of `META-INF` or `<module>/META-INF`. We will need to handle
+                     * `MANIFEST.MF`, `versions` and `versions-modular` in a special way, and archive the rest.
+                     */
+                    if (detectMultiReleaseJar && directory.endsWith(VERSIONS)) {
+                        role = DirectoryRole.VERSIONS;
+                    } else if (directory.endsWith(VERSIONS_MODULAR)) {
+                        if (!detectMultiReleaseJar) {
+                            // Used asked for no multi-release JAR.
+                            return FileVisitResult.SKIP_SUBTREE;
+                        }
+                        role = DirectoryRole.VERSIONS_MODULAR;
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case VERSIONS:
+                    /*
+                     * Entering in a `META-INF/versions/<n>/` directory for a specific target Java release.
+                     * May also be a `<module>/META-INF/versions/<n>/` directory, even if the latter is not
+                     * the layout generated by Maven Compiler Plugin.
+                     */
+                    if (enterVersionDirectory(directory, true)) {
+                        // An error occurred while parsing the version number.
+                        return FileVisitResult.SKIP_SUBTREE;
+                    }
+                    role = DirectoryRole.RESOURCES;
+                    break;
+
+                case VERSIONS_MODULAR:
+                    /*
+                     * Entering in a `META-INF/versions-modular/<n>/` directory for a specific target Java release.
+                     * That directory contains all modules for the version.
+                     */
+                    resetToPackageHierarchy(); // No module in particular yet.
+                    if (enterVersionDirectory(directory, false)) {
+                        // An error occurred while parsing the version number.
+                        return FileVisitResult.SKIP_SUBTREE;
+                    }
+                    role = DirectoryRole.MODULES;
+                    break;
+
+                case MODULES:
+                    /*
+                     * Entering in a `META-INF/versions-modular/<n>/<module>` directory.
+                     */
+                    enterModuleDirectory(directory);
+                    role = DirectoryRole.NAMED_MODULE;
+                    break;
+
+                case NAMED_MODULE:
+                    /*
+                     * Entering in a `<module>` or `META-INF/versions-modular/<n>/<module>` subdirectory.
+                     * A module could have its own `META-INF` subdirectory, so we need to check again.
+                     */
+                    if (directory.endsWith(MetadataFiles.META_INF)) {
+                        role = DirectoryRole.META_INF;
+                        checkForManifest = true;
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+            }
+        }
+        /*
+         * Do not move this condition inside the `switch` block because `role` may have been modified.
+         * The `role` value is now the role of `directory`, not anymore the role of parent directory.
+         */
+        if (addDirectories && role == DirectoryRole.RESOURCES) {
+            currentFilesToArchive.add(directory, attributes, true);
+            /*
+             * Since we are skipping the whole directory, `postVisitDirectory(…)` will not be invoked.
+             * We must reset `currentFilesToArchive` and `currentTargetVersion` by an explicit call.
+             * This is important mostly after we added a whole `META-INF/versions/<n>` directory,
+             * otherwise base files visited afterwards (directory iteration order is unspecified)
+             * would be added to this version's file set instead of the base release.
+             */
+            resetToParentDirectoryState();
+            return FileVisitResult.SKIP_SUBTREE;
+        } else {
+            directoryRoles.addLast(role);
+            return FileVisitResult.CONTINUE;
+        }
+    }
+
+    /**
+     * Updates the {@code FileCollector} state after we finished to scan the content of a directory.
+     * The fields to update depend on which directory has been visited (module, version, <i>etc.</i>).
+     *
+     * @param directory the directory which has been traversed
+     * @param error the error that occurred while traversing the directory, or {@code null} if none
+     */
+    @Override
+    public FileVisitResult postVisitDirectory(final Path directory, final IOException error) throws IOException {
+        if (error != null) {
+            throw error;
+        }
+        switch (directoryRoles.removeLast()) {
+            case NAMED_MODULE:
+                // Exited the directory of a single module.
+                resetToPackageHierarchy();
+                break;
+
+            case ROOT:
+                break;
+
+            default:
+                resetToParentDirectoryState();
+        }
+        return FileVisitResult.CONTINUE;
+    }
+
+    /**
+     * Updates {@code FileCollector} to a state suitable to the parent of the directory that we finished to scan.
+     * Contrarily to {@link #postVisitDirectory(Path, IOException)}, this method expects the last element of
+     * {@link #directoryRoles} to describe the parent directory, not the directory that we finished to visit.
+     */
+    @SuppressWarnings("checkstyle:MissingSwitchDefault")
+    private void resetToParentDirectoryState() {
+        switch (directoryRoles.getLast()) {
+            case VERSIONS:
+            case VERSIONS_MODULAR:
+                // Exited the directory for one target Java release.
+                currentFilesToArchive = currentModule.baseRelease();
+                currentTargetVersion = null;
+                break;
+
+            case META_INF:
+                checkForManifest = true;
+                break;
+        }
+    }
+
+    /**
+     * Archives a single file if accepted by the matcher.
+     *
+     * @param file the file
+     * @param attributes the file's basic attributes
+     */
+    @Override
+    public FileVisitResult visitFile(final Path file, final BasicFileAttributes attributes) {
+        if (fileMatcher.matches(file)) {
+            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.add(file, attributes, false);
+            }
+        }
+        return FileVisitResult.CONTINUE;
+    }
+
+    /**
+     * 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}, then this method ensures that at least one archive
+     * remains even if that archive is empty.
+     *
+     * @param skipIfEmpty value of {@link AbstractJarMojo#skipIfEmpty}
+     */
+    public void prune(boolean skipIfEmpty) {
+        boolean isModuleHierarchy = !moduleHierarchy.isEmpty();
+        moduleHierarchy.values().forEach((archive) -> archive.prune(skipIfEmpty));
+        moduleHierarchy.values().removeIf(Archive::isEmpty);
+        packageHierarchy.prune(isModuleHierarchy || skipIfEmpty);
+    }
+
+    /**
+     * Moves, copies or ignores orphan files.
+     * An orphan file is a file which is not in any module when module hierarchy is used.
+     * For example, some Maven plugins may create files such as {@code META-INF/LICENSE},
+     * {@code META-INF/NOTICE} or {@code META-INF/DEPENDENCIES}. These files are not in
+     * the correct directory (they should be in a {@code "<module>/META-INF"} directory)
+     * because the plugin may not be aware of module hierarchy.
+     *
+     * <p>A possible strategy could be to copy the {@code LICENSE} and {@code NOTICE} files
+     * in each module, and ignore the {@code DEPENDENCIES} file because its content is not
+     * correct for a module. For now, we just log a warning an ignore.</p>
+     *
+     * <h4>Prerequisites</h4>
+     * The {@link #prune(boolean)} method should have been invoked once before to invoke this method.
+     *
+     * @return if this method ignored some files, the root directory of those files
+     */
+    Path handleOrphanFiles() {
+        if (moduleHierarchy.isEmpty() || packageHierarchy.isEmpty()) {
+            // Classpath project or module-project without orphan files. Nothing to do.
+            return null;
+        }
+        // TODO: we may want to copy LICENSE and NOTICE files here.
+        return packageHierarchy.discardAllFiles();
+    }
+
+    /**
+     * Writes all <abbr>JAR</abbr> files.
+     * If the project is multi-module, then this method returns the path to the generated parent <abbr>POM</abbr> file.
+     *
+     * <h4>Prerequisites</h4>
+     * The {@link #prune(boolean)} method should have been invoked once before to invoke this method.
+     *
+     * @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
+     * @throws IOException if an error occurred while reading or writing a manifest file
+     */
+    Path writeAllJARs(final ToolExecutor executor) throws IOException {
+        for (Archive module : moduleHierarchy.values()) {
+            executor.writeSingleJAR(this, module);
+        }
+        if (executor.pomDerivation != null) {
+            return executor.pomDerivation.writeParentPOM(packageHierarchy);
+        }
+        if (!packageHierarchy.isEmpty()) {
+            executor.writeSingleJAR(this, packageHierarchy);
+        }
+        return null;
+    }
+
+    /**
+     * {@return the paths to all root directories of modules in a module hierarchy}
+     * They are usually {@code target/classes/<module>} directories, but could also
+     * be sub-directories in the {@code META-INF/modular-versions/<n>/} directory.
+     * If the project does not use module hierarchy, then this method returns an empty list.
+     *
+     * <h4>Ignored package hierarchy</h4>
+     * Note that an empty list does not necessarily means that the <abbr>JAR</abbr> is not modular,

Review Comment:
   An empty list does not mean



##########
src/main/java/org/apache/maven/plugins/jar/FileCollector.java:
##########
@@ -0,0 +1,496 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.PathMatcher;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayDeque;
+import java.util.Deque;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.services.PathMatcherFactory;
+
+/**
+ * Dispatch the files in the output directory into the <abbr>JAR</abbr> files to create.
+ * Instead of just archiving as-is the content of the output directory, this class separates
+ * the following subdirectories to the options listed below:
+ *
+ * <ul>
+ *   <li>The {@code META-INF/MANIFEST.MF} file will be given to the {@code --manifest} option.</li>
+ *   <li>Files in the following directories will be given to the {@code --release} option:
+ *     <ul>
+ *       <li>{@code META-INF/versions/}</li>
+ *       <li>{@code META-INF/versions-modular/<module>/}</li>
+ *       <li>{@code <module>/META-INF/versions/}</li>
+ *     </ul>
+ *   </li>
+ * </ul>
+ *
+ * The reason for using the options is that they allow the {@code jar} tool to perform additional verifications.
+ * For example, when using the {@code --release} option, {@code jar} verifies the <abbr>API</abbr> compatibility.
+ */
+final class FileCollector extends SimpleFileVisitor<Path> {
+    /**
+     * The file to check for deciding whether the <abbr>JAR</abbr> is modular.
+     */
+    static final String MODULE_DESCRIPTOR_FILE_NAME = "module-info.class";
+
+    /**
+     * The {@value} directory.
+     * This is part of <abbr>JAR</abbr> file specification.
+     */
+    private static final String VERSIONS = "versions";
+
+    /**
+     * The {@value} directory.
+     * This is Maven-specific.
+     */
+    private static final String VERSIONS_MODULAR = "versions-modular";
+
+    /**
+     * Context (logger, configuration) in which the <abbr>JAR</abbr> file are created.
+     */
+    private final ToolExecutor context;
+
+    /**
+     * Whether to detect multi-release <abbr>JAR</abbr> files.
+     * The default value is {@code true}.
+     *
+     * @see AbstractJarMojo#detectMultiReleaseJar
+     */
+    private final boolean detectMultiReleaseJar;
+
+    /**
+     * Combination of includes and excludes path matcher applied on files.
+     */
+    @Nonnull
+    private final PathMatcher fileMatcher;
+
+    /**
+     * Combination of includes and excludes path matcher applied on directories.
+     */
+    @Nonnull
+    private final PathMatcher directoryMatcher;
+
+    /**
+     * Whether the matchers accept all files and there is no need to sort the files.
+     * In such case, we can declare whole directories to the {@code jar} tool instead
+     * of scanning the directory tree ourselves.
+     */
+    private final boolean addDirectories;
+
+    /**
+     * Files found in the output directory when package hierarchy is used.
+     * At most one of {@code packageHierarchy} and {@link #moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Archive packageHierarchy;
+
+    /**
+     * Files found in the output directory when module hierarchy is used. Keys are module names.
+     * At most one of {@link #packageHierarchy} and {@code moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Map<String, Archive> moduleHierarchy;
+
+    /**
+     * The current module being archived. This field is updated every times that {@code FileCollector}
+     * enters in a new module directory.
+     */
+    @Nonnull
+    private Archive currentModule;
+
+    /**
+     * The module and target Java release currently being scanned. This field is updated every times that
+     * {@code FileCollector} enters in a new module directory or in a new target Java release for a given module.
+     */
+    @Nonnull
+    private Archive.FileSet currentFilesToArchive;
+
+    /**
+     * The current target Java release, or {@code null} if none.
+     */
+    @Nullable
+    private Runtime.Version currentTargetVersion;
+
+    /**
+     * Identification of the kinds of directories being traversed.
+     * The length of this list is the depth in the directory hierarchy.
+     * The last element identifies the type of the current directory.
+     */
+    private final Deque<DirectoryRole> directoryRoles;
+
+    /**
+     * Whether to check when a file is the {@code MANIFEST.MF} file.
+     * This is allowed only when scanning the content of a {@code META-INF} directory.
+     */
+    private boolean checkForManifest;
+
+    /**
+     * Creates a new file collector.
+     *
+     * @param mojo the <abbr>MOJO</abbr> from which to get the configuration
+     * @param context context (logger, configuration) in which the <abbr>JAR</abbr> file are created
+     * @param directory the base directory of the files to archive
+     */
+    FileCollector(AbstractJarMojo mojo, ToolExecutor context, Path directory, PathMatcherFactory matcherFactory) {
+        this.context = context;
+        detectMultiReleaseJar = mojo.detectMultiReleaseJar;
+        directoryRoles = new ArrayDeque<>();
+        fileMatcher = matcherFactory.createPathMatcher(directory, mojo.getIncludes(), mojo.getExcludes(), false);
+        directoryMatcher = matcherFactory.deriveDirectoryMatcher(fileMatcher);
+        addDirectories = !context.isReproducible()
+                && matcherFactory.isIncludesAll(fileMatcher)
+                && matcherFactory.isIncludesAll(directoryMatcher);
+        packageHierarchy = context.newArchive(null, null, directory);
+        moduleHierarchy = new LinkedHashMap<>();
+        resetToPackageHierarchy();
+    }
+
+    /**
+     * Resets this {@code FileCollector} to the state where a package hierarchy is presumed.
+     */
+    private void resetToPackageHierarchy() {
+        currentModule = packageHierarchy;
+        currentFilesToArchive = currentModule.baseRelease();
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a module.
+     * For an output generated by {@code javac} from a module source hierarchy,
+     * the directory name is guaranteed to be the module name.
+     *
+     * @param directory a {@code "<module>"} or {@code "META-INF/versions-modular/<module>"} directory
+     */
+    private void enterModuleDirectory(final Path directory) {
+        String moduleName = directory.getFileName().toString();
+        currentModule = moduleHierarchy.computeIfAbsent(
+                moduleName, (name) -> context.newArchive(name, currentTargetVersion, directory));
+        currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a target Java version.
+     * The {@code useDirectly} argument tells whether the content of this directory will be specified directly
+     * as the content to add in the <abbr>JAR</abbr> file. This argument should be {@code false} when there is
+     * another directory level (the module names) to process before to add content.
+     *
+     * @param directory a {@code "META-INF/versions/<n>"} or {@code "META-INF/versions-modular/<n>"} directory
+     * @param useDirectly whether the directory is {@code "META-INF/versions/<n>"}
+     * @return whether to skip the directory because of invalid version number
+     */
+    private boolean enterVersionDirectory(final Path directory, final boolean useDirectly) {
+        try {
+            currentTargetVersion = Runtime.Version.parse(directory.getFileName().toString());
+        } catch (IllegalArgumentException e) {
+            context.warnInvalidVersion(directory, e);
+            return true;
+        }
+        if (useDirectly) {
+            currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+        }
+        return false;
+    }
+
+    /**
+     * Determines if the given directory should be scanned for files to archive.
+     * This method may also update {@link #currentFilesToArchive} if it detects
+     * that we are entering in a new module or a new target Java release.
+     *
+     * @param directory the directory which will be traversed
+     * @param attributes the directory's basic attributes
+     */
+    @Override
+    @SuppressWarnings("checkstyle:MissingSwitchDefault")
+    public FileVisitResult preVisitDirectory(final Path directory, final BasicFileAttributes attributes)
+            throws IOException {
+        DirectoryRole role;
+        if (directoryRoles.isEmpty()) {
+            role = DirectoryRole.ROOT;
+        } else {
+            if (!directoryMatcher.matches(directory)) {
+                return FileVisitResult.SKIP_SUBTREE;
+            }
+            checkForManifest = false;
+            role = directoryRoles.getLast();
+            switch (role) {
+                case ROOT:
+                    /*
+                     * Entering in any subdirectory of `target/classes` (or other directory to archive).
+                     * We need to handle `META-INF` and modules in a special way, and archive the rest.
+                     */
+                    if (directory.endsWith(MetadataFiles.META_INF)) {
+                        role = DirectoryRole.META_INF;
+                        checkForManifest = true;
+                    } else if (Files.isRegularFile(directory.resolve(MODULE_DESCRIPTOR_FILE_NAME))) {
+                        role = DirectoryRole.NAMED_MODULE;
+                        enterModuleDirectory(directory);
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case META_INF:
+                    /*
+                     * Entering in a subdirectory of `META-INF` or `<module>/META-INF`. We will need to handle
+                     * `MANIFEST.MF`, `versions` and `versions-modular` in a special way, and archive the rest.
+                     */
+                    if (detectMultiReleaseJar && directory.endsWith(VERSIONS)) {
+                        role = DirectoryRole.VERSIONS;
+                    } else if (directory.endsWith(VERSIONS_MODULAR)) {
+                        if (!detectMultiReleaseJar) {
+                            // Used asked for no multi-release JAR.
+                            return FileVisitResult.SKIP_SUBTREE;
+                        }
+                        role = DirectoryRole.VERSIONS_MODULAR;
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case VERSIONS:
+                    /*
+                     * Entering in a `META-INF/versions/<n>/` directory for a specific target Java release.
+                     * May also be a `<module>/META-INF/versions/<n>/` directory, even if the latter is not
+                     * the layout generated by Maven Compiler Plugin.
+                     */
+                    if (enterVersionDirectory(directory, true)) {
+                        // An error occurred while parsing the version number.
+                        return FileVisitResult.SKIP_SUBTREE;
+                    }
+                    role = DirectoryRole.RESOURCES;
+                    break;
+
+                case VERSIONS_MODULAR:
+                    /*
+                     * Entering in a `META-INF/versions-modular/<n>/` directory for a specific target Java release.
+                     * That directory contains all modules for the version.
+                     */
+                    resetToPackageHierarchy(); // No module in particular yet.
+                    if (enterVersionDirectory(directory, false)) {
+                        // An error occurred while parsing the version number.
+                        return FileVisitResult.SKIP_SUBTREE;
+                    }
+                    role = DirectoryRole.MODULES;
+                    break;
+
+                case MODULES:
+                    /*
+                     * Entering in a `META-INF/versions-modular/<n>/<module>` directory.
+                     */
+                    enterModuleDirectory(directory);
+                    role = DirectoryRole.NAMED_MODULE;
+                    break;
+
+                case NAMED_MODULE:
+                    /*
+                     * Entering in a `<module>` or `META-INF/versions-modular/<n>/<module>` subdirectory.
+                     * A module could have its own `META-INF` subdirectory, so we need to check again.
+                     */
+                    if (directory.endsWith(MetadataFiles.META_INF)) {
+                        role = DirectoryRole.META_INF;
+                        checkForManifest = true;
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+            }
+        }
+        /*
+         * Do not move this condition inside the `switch` block because `role` may have been modified.
+         * The `role` value is now the role of `directory`, not anymore the role of parent directory.
+         */
+        if (addDirectories && role == DirectoryRole.RESOURCES) {
+            currentFilesToArchive.add(directory, attributes, true);
+            /*
+             * Since we are skipping the whole directory, `postVisitDirectory(…)` will not be invoked.
+             * We must reset `currentFilesToArchive` and `currentTargetVersion` by an explicit call.
+             * This is important mostly after we added a whole `META-INF/versions/<n>` directory,
+             * otherwise base files visited afterwards (directory iteration order is unspecified)
+             * would be added to this version's file set instead of the base release.
+             */
+            resetToParentDirectoryState();
+            return FileVisitResult.SKIP_SUBTREE;
+        } else {
+            directoryRoles.addLast(role);
+            return FileVisitResult.CONTINUE;
+        }
+    }
+
+    /**
+     * Updates the {@code FileCollector} state after we finished to scan the content of a directory.
+     * The fields to update depend on which directory has been visited (module, version, <i>etc.</i>).
+     *
+     * @param directory the directory which has been traversed
+     * @param error the error that occurred while traversing the directory, or {@code null} if none
+     */
+    @Override
+    public FileVisitResult postVisitDirectory(final Path directory, final IOException error) throws IOException {
+        if (error != null) {
+            throw error;
+        }
+        switch (directoryRoles.removeLast()) {
+            case NAMED_MODULE:
+                // Exited the directory of a single module.
+                resetToPackageHierarchy();
+                break;
+
+            case ROOT:
+                break;
+
+            default:
+                resetToParentDirectoryState();
+        }
+        return FileVisitResult.CONTINUE;
+    }
+
+    /**
+     * Updates {@code FileCollector} to a state suitable to the parent of the directory that we finished to scan.
+     * Contrarily to {@link #postVisitDirectory(Path, IOException)}, this method expects the last element of
+     * {@link #directoryRoles} to describe the parent directory, not the directory that we finished to visit.
+     */
+    @SuppressWarnings("checkstyle:MissingSwitchDefault")
+    private void resetToParentDirectoryState() {
+        switch (directoryRoles.getLast()) {
+            case VERSIONS:
+            case VERSIONS_MODULAR:
+                // Exited the directory for one target Java release.
+                currentFilesToArchive = currentModule.baseRelease();
+                currentTargetVersion = null;
+                break;
+
+            case META_INF:
+                checkForManifest = true;
+                break;
+        }
+    }
+
+    /**
+     * Archives a single file if accepted by the matcher.
+     *
+     * @param file the file
+     * @param attributes the file's basic attributes
+     */
+    @Override
+    public FileVisitResult visitFile(final Path file, final BasicFileAttributes attributes) {
+        if (fileMatcher.matches(file)) {
+            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.add(file, attributes, false);
+            }
+        }
+        return FileVisitResult.CONTINUE;
+    }
+
+    /**
+     * 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}, then this method ensures that at least one archive
+     * remains even if that archive is empty.
+     *
+     * @param skipIfEmpty value of {@link AbstractJarMojo#skipIfEmpty}
+     */
+    public void prune(boolean skipIfEmpty) {
+        boolean isModuleHierarchy = !moduleHierarchy.isEmpty();
+        moduleHierarchy.values().forEach((archive) -> archive.prune(skipIfEmpty));
+        moduleHierarchy.values().removeIf(Archive::isEmpty);
+        packageHierarchy.prune(isModuleHierarchy || skipIfEmpty);
+    }
+
+    /**
+     * Moves, copies or ignores orphan files.
+     * An orphan file is a file which is not in any module when module hierarchy is used.
+     * For example, some Maven plugins may create files such as {@code META-INF/LICENSE},
+     * {@code META-INF/NOTICE} or {@code META-INF/DEPENDENCIES}. These files are not in
+     * the correct directory (they should be in a {@code "<module>/META-INF"} directory)
+     * because the plugin may not be aware of module hierarchy.
+     *
+     * <p>A possible strategy could be to copy the {@code LICENSE} and {@code NOTICE} files
+     * in each module, and ignore the {@code DEPENDENCIES} file because its content is not
+     * correct for a module. For now, we just log a warning an ignore.</p>
+     *
+     * <h4>Prerequisites</h4>
+     * The {@link #prune(boolean)} method should have been invoked once before to invoke this method.

Review Comment:
   to invoke this method --> invoking this method



##########
src/main/java/org/apache/maven/plugins/jar/Archive.java:
##########
@@ -0,0 +1,692 @@
+/*
+ * 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.jar;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.TreeMap;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.Type;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.MojoException;
+
+/**
+ * Files or root directories to archive for a single module.
+ * A single instance of {@code Archive} may contain many directories for different target Java releases.
+ * Many instances of {@code Archive} may exist when archiving a multi-modules project.
+ */
+final class Archive {
+    /**
+     * Whether to repeat the {@code -C} option before each file.
+     * Doing so makes the command-line very verbose while the documentation of
+     * <a href="https://docs.oracle.com/en/java/javase/25/docs/specs/man/jar.html">The jar Command</a>
+     * gives the impression that this option can be provided only once.
+     * However, our tests suggest that the first file after the directory specified by the {@code -C} option
+     * must be relative to that directory and all files after the first one must be prefixed by the directory
+     * which was specified in the {@code -C} option. This behavior is not documented, but we couldn't get the
+     * {@code jar} tool to work otherwise (except by repeating {@code -C} before each file).
+     * Furthermore, it seems that the relativized file needs to be the shortest one,
+     * otherwise the {@code jar} tool rejects files after the first one with "names do not match".
+     * Which file is first depends on the unspecified directory-iteration order.
+     *
+     * <p>If this flag is {@code true}, the plugin repeats {@code -C} before each file.
+     * This flag should be set to {@code false} if a future version of the {@code jar}
+     * tool allows to specify {@code -C} only once.</p>
+     *
+     * <p><b>Historical note:</b> we also tried to relativize only the first file after {@code -C}
+     * and keep all subsequent files as absolute. It works, but because we have to repeat the directory
+     * in the file name, it saves only 3 or 4 characters per file compared to repeating {@code -C}.</p>
+     */
+    private static final boolean REPEAT_C = true;
+
+    /**
+     * Path to the <abbr>POM</abbr> file generated for this archive, or {@code null} if none.
+     * This is non-null only if module source hierarchy is used, in which case the dependencies
+     * declared in this file are the intersection of the project dependencies and the content of
+     * the {@code module-info.class} file.
+     */
+    @Nullable
+    Path pomFile;
+
+    /**
+     * The <var>JAR</var> file to create. May be an existing file,

Review Comment:
   avoid "May". Use can or is as appropriate



##########
src/main/java/org/apache/maven/plugins/jar/FileCollector.java:
##########
@@ -0,0 +1,496 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.PathMatcher;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayDeque;
+import java.util.Deque;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.services.PathMatcherFactory;
+
+/**
+ * Dispatch the files in the output directory into the <abbr>JAR</abbr> files to create.
+ * Instead of just archiving as-is the content of the output directory, this class separates
+ * the following subdirectories to the options listed below:
+ *
+ * <ul>
+ *   <li>The {@code META-INF/MANIFEST.MF} file will be given to the {@code --manifest} option.</li>
+ *   <li>Files in the following directories will be given to the {@code --release} option:
+ *     <ul>
+ *       <li>{@code META-INF/versions/}</li>
+ *       <li>{@code META-INF/versions-modular/<module>/}</li>
+ *       <li>{@code <module>/META-INF/versions/}</li>
+ *     </ul>
+ *   </li>
+ * </ul>
+ *
+ * The reason for using the options is that they allow the {@code jar} tool to perform additional verifications.
+ * For example, when using the {@code --release} option, {@code jar} verifies the <abbr>API</abbr> compatibility.
+ */
+final class FileCollector extends SimpleFileVisitor<Path> {
+    /**
+     * The file to check for deciding whether the <abbr>JAR</abbr> is modular.
+     */
+    static final String MODULE_DESCRIPTOR_FILE_NAME = "module-info.class";
+
+    /**
+     * The {@value} directory.
+     * This is part of <abbr>JAR</abbr> file specification.
+     */
+    private static final String VERSIONS = "versions";
+
+    /**
+     * The {@value} directory.
+     * This is Maven-specific.
+     */
+    private static final String VERSIONS_MODULAR = "versions-modular";
+
+    /**
+     * Context (logger, configuration) in which the <abbr>JAR</abbr> file are created.
+     */
+    private final ToolExecutor context;
+
+    /**
+     * Whether to detect multi-release <abbr>JAR</abbr> files.
+     * The default value is {@code true}.
+     *
+     * @see AbstractJarMojo#detectMultiReleaseJar
+     */
+    private final boolean detectMultiReleaseJar;
+
+    /**
+     * Combination of includes and excludes path matcher applied on files.
+     */
+    @Nonnull
+    private final PathMatcher fileMatcher;
+
+    /**
+     * Combination of includes and excludes path matcher applied on directories.
+     */
+    @Nonnull
+    private final PathMatcher directoryMatcher;
+
+    /**
+     * Whether the matchers accept all files and there is no need to sort the files.
+     * In such case, we can declare whole directories to the {@code jar} tool instead
+     * of scanning the directory tree ourselves.
+     */
+    private final boolean addDirectories;
+
+    /**
+     * Files found in the output directory when package hierarchy is used.
+     * At most one of {@code packageHierarchy} and {@link #moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Archive packageHierarchy;
+
+    /**
+     * Files found in the output directory when module hierarchy is used. Keys are module names.
+     * At most one of {@link #packageHierarchy} and {@code moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Map<String, Archive> moduleHierarchy;
+
+    /**
+     * The current module being archived. This field is updated every times that {@code FileCollector}
+     * enters in a new module directory.
+     */
+    @Nonnull
+    private Archive currentModule;
+
+    /**
+     * The module and target Java release currently being scanned. This field is updated every times that
+     * {@code FileCollector} enters in a new module directory or in a new target Java release for a given module.
+     */
+    @Nonnull
+    private Archive.FileSet currentFilesToArchive;
+
+    /**
+     * The current target Java release, or {@code null} if none.
+     */
+    @Nullable
+    private Runtime.Version currentTargetVersion;
+
+    /**
+     * Identification of the kinds of directories being traversed.
+     * The length of this list is the depth in the directory hierarchy.
+     * The last element identifies the type of the current directory.
+     */
+    private final Deque<DirectoryRole> directoryRoles;
+
+    /**
+     * Whether to check when a file is the {@code MANIFEST.MF} file.
+     * This is allowed only when scanning the content of a {@code META-INF} directory.
+     */
+    private boolean checkForManifest;
+
+    /**
+     * Creates a new file collector.
+     *
+     * @param mojo the <abbr>MOJO</abbr> from which to get the configuration
+     * @param context context (logger, configuration) in which the <abbr>JAR</abbr> file are created
+     * @param directory the base directory of the files to archive
+     */
+    FileCollector(AbstractJarMojo mojo, ToolExecutor context, Path directory, PathMatcherFactory matcherFactory) {
+        this.context = context;
+        detectMultiReleaseJar = mojo.detectMultiReleaseJar;
+        directoryRoles = new ArrayDeque<>();
+        fileMatcher = matcherFactory.createPathMatcher(directory, mojo.getIncludes(), mojo.getExcludes(), false);
+        directoryMatcher = matcherFactory.deriveDirectoryMatcher(fileMatcher);
+        addDirectories = !context.isReproducible()
+                && matcherFactory.isIncludesAll(fileMatcher)
+                && matcherFactory.isIncludesAll(directoryMatcher);
+        packageHierarchy = context.newArchive(null, null, directory);
+        moduleHierarchy = new LinkedHashMap<>();
+        resetToPackageHierarchy();
+    }
+
+    /**
+     * Resets this {@code FileCollector} to the state where a package hierarchy is presumed.
+     */
+    private void resetToPackageHierarchy() {
+        currentModule = packageHierarchy;
+        currentFilesToArchive = currentModule.baseRelease();
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a module.
+     * For an output generated by {@code javac} from a module source hierarchy,
+     * the directory name is guaranteed to be the module name.
+     *
+     * @param directory a {@code "<module>"} or {@code "META-INF/versions-modular/<module>"} directory
+     */
+    private void enterModuleDirectory(final Path directory) {
+        String moduleName = directory.getFileName().toString();
+        currentModule = moduleHierarchy.computeIfAbsent(
+                moduleName, (name) -> context.newArchive(name, currentTargetVersion, directory));
+        currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a target Java version.
+     * The {@code useDirectly} argument tells whether the content of this directory will be specified directly
+     * as the content to add in the <abbr>JAR</abbr> file. This argument should be {@code false} when there is
+     * another directory level (the module names) to process before to add content.
+     *
+     * @param directory a {@code "META-INF/versions/<n>"} or {@code "META-INF/versions-modular/<n>"} directory
+     * @param useDirectly whether the directory is {@code "META-INF/versions/<n>"}
+     * @return whether to skip the directory because of invalid version number
+     */
+    private boolean enterVersionDirectory(final Path directory, final boolean useDirectly) {
+        try {
+            currentTargetVersion = Runtime.Version.parse(directory.getFileName().toString());
+        } catch (IllegalArgumentException e) {
+            context.warnInvalidVersion(directory, e);
+            return true;
+        }
+        if (useDirectly) {
+            currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+        }
+        return false;
+    }
+
+    /**
+     * Determines if the given directory should be scanned for files to archive.
+     * This method may also update {@link #currentFilesToArchive} if it detects
+     * that we are entering in a new module or a new target Java release.
+     *
+     * @param directory the directory which will be traversed
+     * @param attributes the directory's basic attributes
+     */
+    @Override
+    @SuppressWarnings("checkstyle:MissingSwitchDefault")
+    public FileVisitResult preVisitDirectory(final Path directory, final BasicFileAttributes attributes)
+            throws IOException {
+        DirectoryRole role;
+        if (directoryRoles.isEmpty()) {
+            role = DirectoryRole.ROOT;
+        } else {
+            if (!directoryMatcher.matches(directory)) {
+                return FileVisitResult.SKIP_SUBTREE;
+            }
+            checkForManifest = false;
+            role = directoryRoles.getLast();
+            switch (role) {
+                case ROOT:
+                    /*
+                     * Entering in any subdirectory of `target/classes` (or other directory to archive).
+                     * We need to handle `META-INF` and modules in a special way, and archive the rest.
+                     */
+                    if (directory.endsWith(MetadataFiles.META_INF)) {
+                        role = DirectoryRole.META_INF;
+                        checkForManifest = true;
+                    } else if (Files.isRegularFile(directory.resolve(MODULE_DESCRIPTOR_FILE_NAME))) {
+                        role = DirectoryRole.NAMED_MODULE;
+                        enterModuleDirectory(directory);
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case META_INF:
+                    /*
+                     * Entering in a subdirectory of `META-INF` or `<module>/META-INF`. We will need to handle
+                     * `MANIFEST.MF`, `versions` and `versions-modular` in a special way, and archive the rest.
+                     */
+                    if (detectMultiReleaseJar && directory.endsWith(VERSIONS)) {
+                        role = DirectoryRole.VERSIONS;
+                    } else if (directory.endsWith(VERSIONS_MODULAR)) {
+                        if (!detectMultiReleaseJar) {
+                            // Used asked for no multi-release JAR.
+                            return FileVisitResult.SKIP_SUBTREE;
+                        }
+                        role = DirectoryRole.VERSIONS_MODULAR;
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case VERSIONS:
+                    /*
+                     * Entering in a `META-INF/versions/<n>/` directory for a specific target Java release.
+                     * May also be a `<module>/META-INF/versions/<n>/` directory, even if the latter is not
+                     * the layout generated by Maven Compiler Plugin.
+                     */
+                    if (enterVersionDirectory(directory, true)) {
+                        // An error occurred while parsing the version number.
+                        return FileVisitResult.SKIP_SUBTREE;
+                    }
+                    role = DirectoryRole.RESOURCES;
+                    break;
+
+                case VERSIONS_MODULAR:
+                    /*
+                     * Entering in a `META-INF/versions-modular/<n>/` directory for a specific target Java release.
+                     * That directory contains all modules for the version.
+                     */
+                    resetToPackageHierarchy(); // No module in particular yet.
+                    if (enterVersionDirectory(directory, false)) {
+                        // An error occurred while parsing the version number.
+                        return FileVisitResult.SKIP_SUBTREE;
+                    }
+                    role = DirectoryRole.MODULES;
+                    break;
+
+                case MODULES:
+                    /*
+                     * Entering in a `META-INF/versions-modular/<n>/<module>` directory.
+                     */
+                    enterModuleDirectory(directory);
+                    role = DirectoryRole.NAMED_MODULE;
+                    break;
+
+                case NAMED_MODULE:
+                    /*
+                     * Entering in a `<module>` or `META-INF/versions-modular/<n>/<module>` subdirectory.
+                     * A module could have its own `META-INF` subdirectory, so we need to check again.
+                     */
+                    if (directory.endsWith(MetadataFiles.META_INF)) {
+                        role = DirectoryRole.META_INF;
+                        checkForManifest = true;
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+            }
+        }
+        /*
+         * Do not move this condition inside the `switch` block because `role` may have been modified.
+         * The `role` value is now the role of `directory`, not anymore the role of parent directory.
+         */
+        if (addDirectories && role == DirectoryRole.RESOURCES) {
+            currentFilesToArchive.add(directory, attributes, true);
+            /*
+             * Since we are skipping the whole directory, `postVisitDirectory(…)` will not be invoked.
+             * We must reset `currentFilesToArchive` and `currentTargetVersion` by an explicit call.
+             * This is important mostly after we added a whole `META-INF/versions/<n>` directory,
+             * otherwise base files visited afterwards (directory iteration order is unspecified)
+             * would be added to this version's file set instead of the base release.
+             */
+            resetToParentDirectoryState();
+            return FileVisitResult.SKIP_SUBTREE;
+        } else {
+            directoryRoles.addLast(role);
+            return FileVisitResult.CONTINUE;
+        }
+    }
+
+    /**
+     * Updates the {@code FileCollector} state after we finished to scan the content of a directory.
+     * The fields to update depend on which directory has been visited (module, version, <i>etc.</i>).
+     *
+     * @param directory the directory which has been traversed
+     * @param error the error that occurred while traversing the directory, or {@code null} if none
+     */
+    @Override
+    public FileVisitResult postVisitDirectory(final Path directory, final IOException error) throws IOException {
+        if (error != null) {
+            throw error;
+        }
+        switch (directoryRoles.removeLast()) {
+            case NAMED_MODULE:
+                // Exited the directory of a single module.
+                resetToPackageHierarchy();
+                break;
+
+            case ROOT:
+                break;
+
+            default:
+                resetToParentDirectoryState();
+        }
+        return FileVisitResult.CONTINUE;
+    }
+
+    /**
+     * Updates {@code FileCollector} to a state suitable to the parent of the directory that we finished to scan.
+     * Contrarily to {@link #postVisitDirectory(Path, IOException)}, this method expects the last element of
+     * {@link #directoryRoles} to describe the parent directory, not the directory that we finished to visit.
+     */
+    @SuppressWarnings("checkstyle:MissingSwitchDefault")
+    private void resetToParentDirectoryState() {
+        switch (directoryRoles.getLast()) {
+            case VERSIONS:
+            case VERSIONS_MODULAR:
+                // Exited the directory for one target Java release.
+                currentFilesToArchive = currentModule.baseRelease();
+                currentTargetVersion = null;
+                break;
+
+            case META_INF:
+                checkForManifest = true;
+                break;
+        }
+    }
+
+    /**
+     * Archives a single file if accepted by the matcher.
+     *
+     * @param file the file
+     * @param attributes the file's basic attributes
+     */
+    @Override
+    public FileVisitResult visitFile(final Path file, final BasicFileAttributes attributes) {
+        if (fileMatcher.matches(file)) {
+            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.add(file, attributes, false);
+            }
+        }
+        return FileVisitResult.CONTINUE;
+    }
+
+    /**
+     * 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}, then this method ensures that at least one archive
+     * remains even if that archive is empty.
+     *
+     * @param skipIfEmpty value of {@link AbstractJarMojo#skipIfEmpty}
+     */
+    public void prune(boolean skipIfEmpty) {
+        boolean isModuleHierarchy = !moduleHierarchy.isEmpty();
+        moduleHierarchy.values().forEach((archive) -> archive.prune(skipIfEmpty));
+        moduleHierarchy.values().removeIf(Archive::isEmpty);
+        packageHierarchy.prune(isModuleHierarchy || skipIfEmpty);
+    }
+
+    /**
+     * Moves, copies or ignores orphan files.
+     * An orphan file is a file which is not in any module when module hierarchy is used.
+     * For example, some Maven plugins may create files such as {@code META-INF/LICENSE},
+     * {@code META-INF/NOTICE} or {@code META-INF/DEPENDENCIES}. These files are not in
+     * the correct directory (they should be in a {@code "<module>/META-INF"} directory)
+     * because the plugin may not be aware of module hierarchy.
+     *
+     * <p>A possible strategy could be to copy the {@code LICENSE} and {@code NOTICE} files
+     * in each module, and ignore the {@code DEPENDENCIES} file because its content is not
+     * correct for a module. For now, we just log a warning an ignore.</p>
+     *
+     * <h4>Prerequisites</h4>
+     * The {@link #prune(boolean)} method should have been invoked once before to invoke this method.
+     *
+     * @return if this method ignored some files, the root directory of those files
+     */
+    Path handleOrphanFiles() {
+        if (moduleHierarchy.isEmpty() || packageHierarchy.isEmpty()) {
+            // Classpath project or module-project without orphan files. Nothing to do.
+            return null;
+        }
+        // TODO: we may want to copy LICENSE and NOTICE files here.
+        return packageHierarchy.discardAllFiles();
+    }
+
+    /**
+     * Writes all <abbr>JAR</abbr> files.
+     * If the project is multi-module, then this method returns the path to the generated parent <abbr>POM</abbr> file.
+     *
+     * <h4>Prerequisites</h4>
+     * The {@link #prune(boolean)} method should have been invoked once before to invoke this method.
+     *
+     * @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
+     * @throws IOException if an error occurred while reading or writing a manifest file
+     */
+    Path writeAllJARs(final ToolExecutor executor) throws IOException {
+        for (Archive module : moduleHierarchy.values()) {
+            executor.writeSingleJAR(this, module);
+        }
+        if (executor.pomDerivation != null) {
+            return executor.pomDerivation.writeParentPOM(packageHierarchy);
+        }
+        if (!packageHierarchy.isEmpty()) {
+            executor.writeSingleJAR(this, packageHierarchy);
+        }
+        return null;
+    }
+
+    /**
+     * {@return the paths to all root directories of modules in a module hierarchy}
+     * They are usually {@code target/classes/<module>} directories, but could also
+     * be sub-directories in the {@code META-INF/modular-versions/<n>/} directory.
+     * If the project does not use module hierarchy, then this method returns an empty list.
+     *
+     * <h4>Ignored package hierarchy</h4>
+     * Note that an empty list does not necessarily means that the <abbr>JAR</abbr> is not modular,
+     * as a modular <abbr>JAR</abbr> can also be built from package hierarchy. But we intentionally
+     * ignore the latter case because this method is used for deriving <abbr>POM</abbr> files, and
+     * we do not perform such derivation for projects organized in the classical Maven 3 way.
+     *
+     * <h4>Prerequisites</h4>
+     * The {@link #prune(boolean)} method should have been invoked once before to invoke this method.

Review Comment:
   to invoke this method --> invoking this method



##########
src/main/java/org/apache/maven/plugins/jar/Providers.java:
##########
@@ -22,25 +22,13 @@
 import org.apache.maven.api.di.Named;
 import org.apache.maven.api.di.Provides;
 import org.apache.maven.api.services.ProjectManager;
-import org.codehaus.plexus.archiver.Archiver;
-import org.codehaus.plexus.archiver.jar.JarArchiver;
-import org.codehaus.plexus.archiver.jar.JarToolModularJarArchiver;
 
+/**
+ * For providing instances to fields annotated with {@code @Inject} if the MOJO.

Review Comment:
   unclear



##########
src/main/java/org/apache/maven/plugins/jar/FileCollector.java:
##########
@@ -0,0 +1,496 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.PathMatcher;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayDeque;
+import java.util.Deque;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.services.PathMatcherFactory;
+
+/**
+ * Dispatch the files in the output directory into the <abbr>JAR</abbr> files to create.
+ * Instead of just archiving as-is the content of the output directory, this class separates
+ * the following subdirectories to the options listed below:
+ *
+ * <ul>
+ *   <li>The {@code META-INF/MANIFEST.MF} file will be given to the {@code --manifest} option.</li>
+ *   <li>Files in the following directories will be given to the {@code --release} option:
+ *     <ul>
+ *       <li>{@code META-INF/versions/}</li>
+ *       <li>{@code META-INF/versions-modular/<module>/}</li>
+ *       <li>{@code <module>/META-INF/versions/}</li>
+ *     </ul>
+ *   </li>
+ * </ul>
+ *
+ * The reason for using the options is that they allow the {@code jar} tool to perform additional verifications.
+ * For example, when using the {@code --release} option, {@code jar} verifies the <abbr>API</abbr> compatibility.
+ */
+final class FileCollector extends SimpleFileVisitor<Path> {
+    /**
+     * The file to check for deciding whether the <abbr>JAR</abbr> is modular.
+     */
+    static final String MODULE_DESCRIPTOR_FILE_NAME = "module-info.class";
+
+    /**
+     * The {@value} directory.
+     * This is part of <abbr>JAR</abbr> file specification.
+     */
+    private static final String VERSIONS = "versions";
+
+    /**
+     * The {@value} directory.
+     * This is Maven-specific.
+     */
+    private static final String VERSIONS_MODULAR = "versions-modular";
+
+    /**
+     * Context (logger, configuration) in which the <abbr>JAR</abbr> file are created.
+     */
+    private final ToolExecutor context;
+
+    /**
+     * Whether to detect multi-release <abbr>JAR</abbr> files.
+     * The default value is {@code true}.
+     *
+     * @see AbstractJarMojo#detectMultiReleaseJar
+     */
+    private final boolean detectMultiReleaseJar;
+
+    /**
+     * Combination of includes and excludes path matcher applied on files.
+     */
+    @Nonnull
+    private final PathMatcher fileMatcher;
+
+    /**
+     * Combination of includes and excludes path matcher applied on directories.
+     */
+    @Nonnull
+    private final PathMatcher directoryMatcher;
+
+    /**
+     * Whether the matchers accept all files and there is no need to sort the files.
+     * In such case, we can declare whole directories to the {@code jar} tool instead
+     * of scanning the directory tree ourselves.
+     */
+    private final boolean addDirectories;
+
+    /**
+     * Files found in the output directory when package hierarchy is used.
+     * At most one of {@code packageHierarchy} and {@link #moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Archive packageHierarchy;
+
+    /**
+     * Files found in the output directory when module hierarchy is used. Keys are module names.
+     * At most one of {@link #packageHierarchy} and {@code moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Map<String, Archive> moduleHierarchy;
+
+    /**
+     * The current module being archived. This field is updated every times that {@code FileCollector}
+     * enters in a new module directory.
+     */
+    @Nonnull
+    private Archive currentModule;
+
+    /**
+     * The module and target Java release currently being scanned. This field is updated every times that
+     * {@code FileCollector} enters in a new module directory or in a new target Java release for a given module.
+     */
+    @Nonnull
+    private Archive.FileSet currentFilesToArchive;
+
+    /**
+     * The current target Java release, or {@code null} if none.
+     */
+    @Nullable
+    private Runtime.Version currentTargetVersion;
+
+    /**
+     * Identification of the kinds of directories being traversed.
+     * The length of this list is the depth in the directory hierarchy.
+     * The last element identifies the type of the current directory.
+     */
+    private final Deque<DirectoryRole> directoryRoles;
+
+    /**
+     * Whether to check when a file is the {@code MANIFEST.MF} file.
+     * This is allowed only when scanning the content of a {@code META-INF} directory.
+     */
+    private boolean checkForManifest;
+
+    /**
+     * Creates a new file collector.
+     *
+     * @param mojo the <abbr>MOJO</abbr> from which to get the configuration
+     * @param context context (logger, configuration) in which the <abbr>JAR</abbr> file are created
+     * @param directory the base directory of the files to archive
+     */
+    FileCollector(AbstractJarMojo mojo, ToolExecutor context, Path directory, PathMatcherFactory matcherFactory) {
+        this.context = context;
+        detectMultiReleaseJar = mojo.detectMultiReleaseJar;
+        directoryRoles = new ArrayDeque<>();
+        fileMatcher = matcherFactory.createPathMatcher(directory, mojo.getIncludes(), mojo.getExcludes(), false);
+        directoryMatcher = matcherFactory.deriveDirectoryMatcher(fileMatcher);
+        addDirectories = !context.isReproducible()
+                && matcherFactory.isIncludesAll(fileMatcher)
+                && matcherFactory.isIncludesAll(directoryMatcher);
+        packageHierarchy = context.newArchive(null, null, directory);
+        moduleHierarchy = new LinkedHashMap<>();
+        resetToPackageHierarchy();
+    }
+
+    /**
+     * Resets this {@code FileCollector} to the state where a package hierarchy is presumed.
+     */
+    private void resetToPackageHierarchy() {
+        currentModule = packageHierarchy;
+        currentFilesToArchive = currentModule.baseRelease();
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a module.
+     * For an output generated by {@code javac} from a module source hierarchy,
+     * the directory name is guaranteed to be the module name.
+     *
+     * @param directory a {@code "<module>"} or {@code "META-INF/versions-modular/<module>"} directory
+     */
+    private void enterModuleDirectory(final Path directory) {
+        String moduleName = directory.getFileName().toString();
+        currentModule = moduleHierarchy.computeIfAbsent(
+                moduleName, (name) -> context.newArchive(name, currentTargetVersion, directory));
+        currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a target Java version.
+     * The {@code useDirectly} argument tells whether the content of this directory will be specified directly
+     * as the content to add in the <abbr>JAR</abbr> file. This argument should be {@code false} when there is
+     * another directory level (the module names) to process before to add content.
+     *
+     * @param directory a {@code "META-INF/versions/<n>"} or {@code "META-INF/versions-modular/<n>"} directory
+     * @param useDirectly whether the directory is {@code "META-INF/versions/<n>"}
+     * @return whether to skip the directory because of invalid version number
+     */
+    private boolean enterVersionDirectory(final Path directory, final boolean useDirectly) {
+        try {
+            currentTargetVersion = Runtime.Version.parse(directory.getFileName().toString());
+        } catch (IllegalArgumentException e) {
+            context.warnInvalidVersion(directory, e);
+            return true;
+        }
+        if (useDirectly) {
+            currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+        }
+        return false;
+    }
+
+    /**
+     * Determines if the given directory should be scanned for files to archive.
+     * This method may also update {@link #currentFilesToArchive} if it detects
+     * that we are entering in a new module or a new target Java release.
+     *
+     * @param directory the directory which will be traversed
+     * @param attributes the directory's basic attributes
+     */
+    @Override
+    @SuppressWarnings("checkstyle:MissingSwitchDefault")
+    public FileVisitResult preVisitDirectory(final Path directory, final BasicFileAttributes attributes)
+            throws IOException {
+        DirectoryRole role;
+        if (directoryRoles.isEmpty()) {
+            role = DirectoryRole.ROOT;
+        } else {
+            if (!directoryMatcher.matches(directory)) {
+                return FileVisitResult.SKIP_SUBTREE;
+            }
+            checkForManifest = false;
+            role = directoryRoles.getLast();
+            switch (role) {
+                case ROOT:
+                    /*
+                     * Entering in any subdirectory of `target/classes` (or other directory to archive).
+                     * We need to handle `META-INF` and modules in a special way, and archive the rest.
+                     */
+                    if (directory.endsWith(MetadataFiles.META_INF)) {
+                        role = DirectoryRole.META_INF;
+                        checkForManifest = true;
+                    } else if (Files.isRegularFile(directory.resolve(MODULE_DESCRIPTOR_FILE_NAME))) {
+                        role = DirectoryRole.NAMED_MODULE;
+                        enterModuleDirectory(directory);
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case META_INF:
+                    /*
+                     * Entering in a subdirectory of `META-INF` or `<module>/META-INF`. We will need to handle
+                     * `MANIFEST.MF`, `versions` and `versions-modular` in a special way, and archive the rest.
+                     */
+                    if (detectMultiReleaseJar && directory.endsWith(VERSIONS)) {
+                        role = DirectoryRole.VERSIONS;
+                    } else if (directory.endsWith(VERSIONS_MODULAR)) {
+                        if (!detectMultiReleaseJar) {
+                            // Used asked for no multi-release JAR.
+                            return FileVisitResult.SKIP_SUBTREE;
+                        }
+                        role = DirectoryRole.VERSIONS_MODULAR;
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case VERSIONS:
+                    /*
+                     * Entering in a `META-INF/versions/<n>/` directory for a specific target Java release.
+                     * May also be a `<module>/META-INF/versions/<n>/` directory, even if the latter is not
+                     * the layout generated by Maven Compiler Plugin.
+                     */
+                    if (enterVersionDirectory(directory, true)) {
+                        // An error occurred while parsing the version number.
+                        return FileVisitResult.SKIP_SUBTREE;
+                    }
+                    role = DirectoryRole.RESOURCES;
+                    break;
+
+                case VERSIONS_MODULAR:
+                    /*
+                     * Entering in a `META-INF/versions-modular/<n>/` directory for a specific target Java release.
+                     * That directory contains all modules for the version.
+                     */
+                    resetToPackageHierarchy(); // No module in particular yet.
+                    if (enterVersionDirectory(directory, false)) {
+                        // An error occurred while parsing the version number.
+                        return FileVisitResult.SKIP_SUBTREE;
+                    }
+                    role = DirectoryRole.MODULES;
+                    break;
+
+                case MODULES:
+                    /*
+                     * Entering in a `META-INF/versions-modular/<n>/<module>` directory.
+                     */
+                    enterModuleDirectory(directory);
+                    role = DirectoryRole.NAMED_MODULE;
+                    break;
+
+                case NAMED_MODULE:
+                    /*
+                     * Entering in a `<module>` or `META-INF/versions-modular/<n>/<module>` subdirectory.
+                     * A module could have its own `META-INF` subdirectory, so we need to check again.
+                     */
+                    if (directory.endsWith(MetadataFiles.META_INF)) {
+                        role = DirectoryRole.META_INF;
+                        checkForManifest = true;
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+            }
+        }
+        /*
+         * Do not move this condition inside the `switch` block because `role` may have been modified.
+         * The `role` value is now the role of `directory`, not anymore the role of parent directory.
+         */
+        if (addDirectories && role == DirectoryRole.RESOURCES) {
+            currentFilesToArchive.add(directory, attributes, true);
+            /*
+             * Since we are skipping the whole directory, `postVisitDirectory(…)` will not be invoked.
+             * We must reset `currentFilesToArchive` and `currentTargetVersion` by an explicit call.
+             * This is important mostly after we added a whole `META-INF/versions/<n>` directory,
+             * otherwise base files visited afterwards (directory iteration order is unspecified)
+             * would be added to this version's file set instead of the base release.
+             */
+            resetToParentDirectoryState();
+            return FileVisitResult.SKIP_SUBTREE;
+        } else {
+            directoryRoles.addLast(role);
+            return FileVisitResult.CONTINUE;
+        }
+    }
+
+    /**
+     * Updates the {@code FileCollector} state after we finished to scan the content of a directory.
+     * The fields to update depend on which directory has been visited (module, version, <i>etc.</i>).
+     *
+     * @param directory the directory which has been traversed
+     * @param error the error that occurred while traversing the directory, or {@code null} if none
+     */
+    @Override
+    public FileVisitResult postVisitDirectory(final Path directory, final IOException error) throws IOException {
+        if (error != null) {
+            throw error;
+        }
+        switch (directoryRoles.removeLast()) {
+            case NAMED_MODULE:
+                // Exited the directory of a single module.
+                resetToPackageHierarchy();
+                break;
+
+            case ROOT:
+                break;
+
+            default:
+                resetToParentDirectoryState();
+        }
+        return FileVisitResult.CONTINUE;
+    }
+
+    /**
+     * Updates {@code FileCollector} to a state suitable to the parent of the directory that we finished to scan.
+     * Contrarily to {@link #postVisitDirectory(Path, IOException)}, this method expects the last element of
+     * {@link #directoryRoles} to describe the parent directory, not the directory that we finished to visit.
+     */
+    @SuppressWarnings("checkstyle:MissingSwitchDefault")
+    private void resetToParentDirectoryState() {
+        switch (directoryRoles.getLast()) {
+            case VERSIONS:
+            case VERSIONS_MODULAR:
+                // Exited the directory for one target Java release.
+                currentFilesToArchive = currentModule.baseRelease();
+                currentTargetVersion = null;
+                break;
+
+            case META_INF:
+                checkForManifest = true;
+                break;
+        }
+    }
+
+    /**
+     * Archives a single file if accepted by the matcher.
+     *
+     * @param file the file
+     * @param attributes the file's basic attributes
+     */
+    @Override
+    public FileVisitResult visitFile(final Path file, final BasicFileAttributes attributes) {
+        if (fileMatcher.matches(file)) {
+            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.add(file, attributes, false);
+            }
+        }
+        return FileVisitResult.CONTINUE;
+    }
+
+    /**
+     * 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}, then this method ensures that at least one archive
+     * remains even if that archive is empty.
+     *
+     * @param skipIfEmpty value of {@link AbstractJarMojo#skipIfEmpty}
+     */
+    public void prune(boolean skipIfEmpty) {
+        boolean isModuleHierarchy = !moduleHierarchy.isEmpty();
+        moduleHierarchy.values().forEach((archive) -> archive.prune(skipIfEmpty));
+        moduleHierarchy.values().removeIf(Archive::isEmpty);
+        packageHierarchy.prune(isModuleHierarchy || skipIfEmpty);
+    }
+
+    /**
+     * Moves, copies or ignores orphan files.
+     * An orphan file is a file which is not in any module when module hierarchy is used.
+     * For example, some Maven plugins may create files such as {@code META-INF/LICENSE},
+     * {@code META-INF/NOTICE} or {@code META-INF/DEPENDENCIES}. These files are not in
+     * the correct directory (they should be in a {@code "<module>/META-INF"} directory)
+     * because the plugin may not be aware of module hierarchy.
+     *
+     * <p>A possible strategy could be to copy the {@code LICENSE} and {@code NOTICE} files
+     * in each module, and ignore the {@code DEPENDENCIES} file because its content is not
+     * correct for a module. For now, we just log a warning an ignore.</p>
+     *
+     * <h4>Prerequisites</h4>
+     * The {@link #prune(boolean)} method should have been invoked once before to invoke this method.
+     *
+     * @return if this method ignored some files, the root directory of those files
+     */
+    Path handleOrphanFiles() {
+        if (moduleHierarchy.isEmpty() || packageHierarchy.isEmpty()) {
+            // Classpath project or module-project without orphan files. Nothing to do.
+            return null;
+        }
+        // TODO: we may want to copy LICENSE and NOTICE files here.
+        return packageHierarchy.discardAllFiles();
+    }
+
+    /**
+     * Writes all <abbr>JAR</abbr> files.
+     * If the project is multi-module, then this method returns the path to the generated parent <abbr>POM</abbr> file.
+     *
+     * <h4>Prerequisites</h4>
+     * The {@link #prune(boolean)} method should have been invoked once before to invoke this method.
+     *
+     * @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
+     * @throws IOException if an error occurred while reading or writing a manifest file
+     */
+    Path writeAllJARs(final ToolExecutor executor) throws IOException {
+        for (Archive module : moduleHierarchy.values()) {
+            executor.writeSingleJAR(this, module);
+        }
+        if (executor.pomDerivation != null) {
+            return executor.pomDerivation.writeParentPOM(packageHierarchy);
+        }
+        if (!packageHierarchy.isEmpty()) {
+            executor.writeSingleJAR(this, packageHierarchy);
+        }
+        return null;
+    }
+
+    /**
+     * {@return the paths to all root directories of modules in a module hierarchy}
+     * They are usually {@code target/classes/<module>} directories, but could also
+     * be sub-directories in the {@code META-INF/modular-versions/<n>/} directory.
+     * If the project does not use module hierarchy, then this method returns an empty list.
+     *
+     * <h4>Ignored package hierarchy</h4>
+     * Note that an empty list does not necessarily means that the <abbr>JAR</abbr> is not modular,
+     * as a modular <abbr>JAR</abbr> can also be built from package hierarchy. But we intentionally
+     * ignore the latter case because this method is used for deriving <abbr>POM</abbr> files, and
+     * we do not perform such derivation for projects organized in the classical Maven 3 way.

Review Comment:
   delete classical



##########
src/main/java/org/apache/maven/plugins/jar/AbstractJarMojo.java:
##########
@@ -207,167 +205,208 @@ protected final Log getLog() {
     protected abstract String getType();
 
     /**
-     * Returns the JAR file to generate, based on an optional classifier.
+     * {@return the scope of dependencies}
+     * It should be {@link PathScope#MAIN_COMPILE} or {@link PathScope#TEST_COMPILE}.
+     * Note that we use compile scope rather than runtime scope because dependencies
+     * cannot appear in {@code requires} statement if they didn't had compile scope.
+     */
+    protected abstract PathScope getDependencyScope();
+
+    /**
+     * {@return the JAR tool to use for archiving the code}
      *
-     * @param basedir the output directory
-     * @param resultFinalName the name of the JAR file
-     * @param classifier an optional classifier
-     * @return the file to generate
+     * @throws MojoException if no JAR tool was found
+     *
+     * @since 4.0.0-beta-2
      */
-    protected Path getJarFile(Path basedir, String resultFinalName, String classifier) {
-        Objects.requireNonNull(basedir, "basedir is not allowed to be null");
-        Objects.requireNonNull(resultFinalName, "finalName is not allowed to be null");
-        String fileName = resultFinalName + (hasClassifier(classifier) ? '-' + classifier : "") + ".jar";
-        return basedir.resolve(fileName);
+    protected ToolProvider getJarTool() throws MojoException {
+        return ToolProvider.findFirst(toolId).orElseThrow(() -> new MojoException("No such \"" + toolId + "\" tool."));
     }
 
     /**
-     * Generates the JAR.
+     * Returns the output time stamp or, as a fallback, the {@code SOURCE_DATE_EPOCH} environment variable.
+     * If the time stamp is expressed in seconds, it is converted to ISO 8601 format. Otherwise it is returned as-is.
      *
-     * @return the path to the created archive file
-     * @throws MojoException in case of an error
+     * @return the time stamp in presumed ISO 8601 format, or {@code null} if none
+     *
+     * @since 4.0.0-beta-2
      */
-    public Path createArchive() throws MojoException {
-        Path basedir = outputDirectory != null
-                ? outputDirectory
-                : Path.of(project.getBuild().getDirectory());
-        String resultFinalName =
-                finalName != null ? finalName : project.getBuild().getFinalName();
-        Path jarFile = getJarFile(basedir, resultFinalName, getClassifier());
-
-        FileSetManager fileSetManager = new FileSetManager();
-        FileSet jarContentFileSet = new FileSet();
-        jarContentFileSet.setDirectory(getClassesDirectory().toAbsolutePath().toString());
-        jarContentFileSet.setIncludes(Arrays.asList(getIncludes()));
-        jarContentFileSet.setExcludes(Arrays.asList(getExcludes()));
-
-        String[] includedFiles = fileSetManager.getIncludedFiles(jarContentFileSet);
-
-        if (detectMultiReleaseJar
-                && Arrays.stream(includedFiles)
-                        .anyMatch(
-                                p -> p.startsWith("META-INF" + File.separatorChar + "versions" + File.separatorChar))) {
-            getLog().debug("Adding 'Multi-Release: true' manifest entry.");
-            archive.addManifestEntry(Attributes.Name.MULTI_RELEASE.toString(), "true");
+    protected String getOutputTimestamp() {
+        String time = nullIfAbsent(outputTimestamp);
+        if (time == null) {
+            time = nullIfAbsent(System.getenv("SOURCE_DATE_EPOCH"));
+            if (time == null) {
+                return null;
+            }
         }
+        if (Runtime.version().feature() < ToolExecutor.JDK_SUPPORT_DATE) {
+            log.warn("Reproducible build requires Java " + ToolExecutor.JDK_SUPPORT_DATE + " or later.");
+            return null;
+        }
+        for (int i = time.length(); --i >= 0; ) {
+            char c = time.charAt(i);
+            if ((c < '0' || c > '9') && (i != 0 || c != '-')) {
+                return time;
+            }
+        }
+        return Instant.ofEpochSecond(Long.parseLong(time)).toString();
+    }
 
-        // May give false positives if the files is named as module descriptor
-        // but is not in the root of the archive or in the versioned area
-        // (and hence not actually a module descriptor).
-        // That is fine since the modular Jar archiver will gracefully
-        // handle such case.
-        // And also such case is unlikely to happen as file ending
-        // with "module-info.class" is unlikely to be included in Jar file
-        // unless it is a module descriptor.
-        boolean containsModuleDescriptor =
-                Arrays.stream(includedFiles).anyMatch(p -> p.endsWith(MODULE_DESCRIPTOR_FILE_NAME));
-
-        String archiverName = containsModuleDescriptor ? "mjar" : "jar";
+    /**
+     * {@return the patterns of files to include, or an empty list if no include pattern was specified}
+     */
+    protected List<String> getIncludes() {
+        return asList(includes);
+    }
 
-        MavenArchiver archiver = new MavenArchiver();
-        archiver.setCreatedBy("Maven JAR Plugin", "org.apache.maven.plugins", "maven-jar-plugin");
-        archiver.setBuildJdkSpecDefaultEntry(archive.getManifest().isAddBuildEnvironmentEntries());
-        archiver.setArchiver((JarArchiver) archivers.get(archiverName));
-        archiver.setOutputFile(jarFile.toFile());
+    /**
+     * {@return the patterns of files to exclude, or an empty list if no exclude pattern was specified}
+     */
+    protected List<String> getExcludes() {
+        return asList(excludes);
+    }
 
-        // configure for Reproducible Builds based on outputTimestamp value
-        archiver.configureReproducibleBuild(outputTimestamp);
+    /**
+     * Returns the output directory and ensures that the directory exists.
+     * The returned directory will be either {@link #outputDirectory} if non-null,
+     * or {@link org.apache.maven.api.model.Build#getDirectory()} otherwise.
+     *
+     * <p>The directory is usually {@code target} and should always exist since it is usually the output
+     * of the compiler plugin. If nevertheless the directory does not exist, then this method creates it.
+     * However, this method does not try to create the parent directory, which should be the Maven sub-project.</p>
+     *
+     * @return the directory containing the generated <abbr>JAR</abbr> files.
+     * @throws IOException if the output directory did not existed and could not be created
+     */
+    protected Path getOutputDirectory() throws IOException {
+        Path dir = outputDirectory;
+        if (dir == null) {
+            dir = Path.of(project.getBuild().getDirectory());
+        }
+        if (Files.notExists(dir)) {
+            dir = Files.createDirectory(dir);
+        }
+        return dir;
+    }
 
-        archive.setForced(forceCreation);
+    /**
+     * Returns the given elements as a list if non-null.
+     *
+     * @param elements the elements, or {@code null}
+     * @return the elements as a list, or {@code null} if the given array was null
+     */
+    private static List<String> asList(String[] elements) {
+        return (elements == null) ? List.of() : Arrays.asList(elements);
+    }
 
-        try {
-            Path contentDirectory = getClassesDirectory();
-            if (!Files.exists(contentDirectory)) {
-                if (!forceCreation) {
-                    getLog().warn("JAR will be empty - no content was marked for inclusion!");
-                }
-            } else {
-                archiver.getArchiver().addDirectory(contentDirectory.toFile(), getIncludes(), getExcludes());
+    /**
+     * Generates the <abbr>JAR</abbr> files.
+     * Map keys are module names or {@code null} if the project does not use module hierarchy.
+     * Values are (<var>type</var>, <var>path</var>) pairs associated with each module where
+     * <var>type</var> is {@code "pom"}, {@code "jar"} or {@code "test-jar"} and <var>path</var>
+     * is the path to the <abbr>POM</abbr> or <abbr>JAR</abbr> file.
+     *
+     * <p>Note that a null key does not necessarily means that the <abbr>JAR</abbr> is not modular.

Review Comment:
   A null key does not necessarily mean that the <abbr>JAR</abbr> is not modular.



##########
src/main/java/org/apache/maven/plugins/jar/TimestampCheck.java:
##########
@@ -0,0 +1,237 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.nio.file.attribute.FileTime;
+import java.util.Collection;
+import java.util.Enumeration;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+
+import org.apache.maven.api.plugin.Log;
+
+/**
+ * Checks file timestamps in order to determine if anything changed compared to an existing <abbr>JAR</abbr> file.
+ * This class may scan directories, but only if they have not already been visited by {@link FileCollector}.
+ * Note that the latter can occur only if {@link FileCollector} has no {@code PathMatcher}.

Review Comment:
   Note that the latter can occur only  --> The latter can only occur



##########
src/main/java/org/apache/maven/plugins/jar/TimestampCheck.java:
##########
@@ -0,0 +1,237 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.nio.file.attribute.FileTime;
+import java.util.Collection;
+import java.util.Enumeration;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+
+import org.apache.maven.api.plugin.Log;
+
+/**
+ * Checks file timestamps in order to determine if anything changed compared to an existing <abbr>JAR</abbr> file.
+ * This class may scan directories, but only if they have not already been visited by {@link FileCollector}.
+ * Note that the latter can occur only if {@link FileCollector} has no {@code PathMatcher}.
+ * Therefore, this class uses no {@code PathMatcher} neither.
+ *
+ * <h2>Ignore files</h2>
+ * The {@code META-INF/MANIFEST.MF} file and the {@code META-INF/maven/} directory are ignored.
+ * See {@link #isIgnored(Path)} for the rational.
+ */
+final class TimestampCheck extends SimpleFileVisitor<Path> {
+    /**
+     * The base directory of archived files.
+     */
+    private final Path classesDir;
+
+    /**
+     * Path to the existing <abbr>JAR</abbr> file.
+     */
+    private final Path jarFile;
+
+    /**
+     * The last modified time of the <abbr>JAR</abbr> file.
+     */
+    private final FileTime jarFileTime;
+
+    /**
+     * Where to send non-fatal error messages.
+     */
+    private final Log logger;
+
+    /**
+     * Entries of the <abbr>JAR</abbr> file. Note that getting elements from this enumeration can be costly.
+     * Therefore, we do not fetch all elements in advance but only when needed.

Review Comment:
   we only fetch elements when needed.



##########
src/main/java/org/apache/maven/plugins/jar/AbstractJarMojo.java:
##########
@@ -207,167 +205,208 @@ protected final Log getLog() {
     protected abstract String getType();
 
     /**
-     * Returns the JAR file to generate, based on an optional classifier.
+     * {@return the scope of dependencies}
+     * It should be {@link PathScope#MAIN_COMPILE} or {@link PathScope#TEST_COMPILE}.
+     * Note that we use compile scope rather than runtime scope because dependencies
+     * cannot appear in {@code requires} statement if they didn't had compile scope.
+     */
+    protected abstract PathScope getDependencyScope();
+
+    /**
+     * {@return the JAR tool to use for archiving the code}
      *
-     * @param basedir the output directory
-     * @param resultFinalName the name of the JAR file
-     * @param classifier an optional classifier
-     * @return the file to generate
+     * @throws MojoException if no JAR tool was found
+     *
+     * @since 4.0.0-beta-2
      */
-    protected Path getJarFile(Path basedir, String resultFinalName, String classifier) {
-        Objects.requireNonNull(basedir, "basedir is not allowed to be null");
-        Objects.requireNonNull(resultFinalName, "finalName is not allowed to be null");
-        String fileName = resultFinalName + (hasClassifier(classifier) ? '-' + classifier : "") + ".jar";
-        return basedir.resolve(fileName);
+    protected ToolProvider getJarTool() throws MojoException {
+        return ToolProvider.findFirst(toolId).orElseThrow(() -> new MojoException("No such \"" + toolId + "\" tool."));
     }
 
     /**
-     * Generates the JAR.
+     * Returns the output time stamp or, as a fallback, the {@code SOURCE_DATE_EPOCH} environment variable.
+     * If the time stamp is expressed in seconds, it is converted to ISO 8601 format. Otherwise it is returned as-is.
      *
-     * @return the path to the created archive file
-     * @throws MojoException in case of an error
+     * @return the time stamp in presumed ISO 8601 format, or {@code null} if none
+     *
+     * @since 4.0.0-beta-2
      */
-    public Path createArchive() throws MojoException {
-        Path basedir = outputDirectory != null
-                ? outputDirectory
-                : Path.of(project.getBuild().getDirectory());
-        String resultFinalName =
-                finalName != null ? finalName : project.getBuild().getFinalName();
-        Path jarFile = getJarFile(basedir, resultFinalName, getClassifier());
-
-        FileSetManager fileSetManager = new FileSetManager();
-        FileSet jarContentFileSet = new FileSet();
-        jarContentFileSet.setDirectory(getClassesDirectory().toAbsolutePath().toString());
-        jarContentFileSet.setIncludes(Arrays.asList(getIncludes()));
-        jarContentFileSet.setExcludes(Arrays.asList(getExcludes()));
-
-        String[] includedFiles = fileSetManager.getIncludedFiles(jarContentFileSet);
-
-        if (detectMultiReleaseJar
-                && Arrays.stream(includedFiles)
-                        .anyMatch(
-                                p -> p.startsWith("META-INF" + File.separatorChar + "versions" + File.separatorChar))) {
-            getLog().debug("Adding 'Multi-Release: true' manifest entry.");
-            archive.addManifestEntry(Attributes.Name.MULTI_RELEASE.toString(), "true");
+    protected String getOutputTimestamp() {
+        String time = nullIfAbsent(outputTimestamp);
+        if (time == null) {
+            time = nullIfAbsent(System.getenv("SOURCE_DATE_EPOCH"));
+            if (time == null) {
+                return null;
+            }
         }
+        if (Runtime.version().feature() < ToolExecutor.JDK_SUPPORT_DATE) {
+            log.warn("Reproducible build requires Java " + ToolExecutor.JDK_SUPPORT_DATE + " or later.");
+            return null;
+        }
+        for (int i = time.length(); --i >= 0; ) {
+            char c = time.charAt(i);
+            if ((c < '0' || c > '9') && (i != 0 || c != '-')) {
+                return time;
+            }
+        }
+        return Instant.ofEpochSecond(Long.parseLong(time)).toString();
+    }
 
-        // May give false positives if the files is named as module descriptor
-        // but is not in the root of the archive or in the versioned area
-        // (and hence not actually a module descriptor).
-        // That is fine since the modular Jar archiver will gracefully
-        // handle such case.
-        // And also such case is unlikely to happen as file ending
-        // with "module-info.class" is unlikely to be included in Jar file
-        // unless it is a module descriptor.
-        boolean containsModuleDescriptor =
-                Arrays.stream(includedFiles).anyMatch(p -> p.endsWith(MODULE_DESCRIPTOR_FILE_NAME));
-
-        String archiverName = containsModuleDescriptor ? "mjar" : "jar";
+    /**
+     * {@return the patterns of files to include, or an empty list if no include pattern was specified}
+     */
+    protected List<String> getIncludes() {
+        return asList(includes);
+    }
 
-        MavenArchiver archiver = new MavenArchiver();
-        archiver.setCreatedBy("Maven JAR Plugin", "org.apache.maven.plugins", "maven-jar-plugin");
-        archiver.setBuildJdkSpecDefaultEntry(archive.getManifest().isAddBuildEnvironmentEntries());
-        archiver.setArchiver((JarArchiver) archivers.get(archiverName));
-        archiver.setOutputFile(jarFile.toFile());
+    /**
+     * {@return the patterns of files to exclude, or an empty list if no exclude pattern was specified}
+     */
+    protected List<String> getExcludes() {
+        return asList(excludes);
+    }
 
-        // configure for Reproducible Builds based on outputTimestamp value
-        archiver.configureReproducibleBuild(outputTimestamp);
+    /**
+     * Returns the output directory and ensures that the directory exists.
+     * The returned directory will be either {@link #outputDirectory} if non-null,
+     * or {@link org.apache.maven.api.model.Build#getDirectory()} otherwise.
+     *
+     * <p>The directory is usually {@code target} and should always exist since it is usually the output
+     * of the compiler plugin. If nevertheless the directory does not exist, then this method creates it.
+     * However, this method does not try to create the parent directory, which should be the Maven sub-project.</p>
+     *
+     * @return the directory containing the generated <abbr>JAR</abbr> files.
+     * @throws IOException if the output directory did not existed and could not be created
+     */
+    protected Path getOutputDirectory() throws IOException {
+        Path dir = outputDirectory;
+        if (dir == null) {
+            dir = Path.of(project.getBuild().getDirectory());
+        }
+        if (Files.notExists(dir)) {
+            dir = Files.createDirectory(dir);
+        }
+        return dir;
+    }
 
-        archive.setForced(forceCreation);
+    /**
+     * Returns the given elements as a list if non-null.
+     *
+     * @param elements the elements, or {@code null}
+     * @return the elements as a list, or {@code null} if the given array was null
+     */
+    private static List<String> asList(String[] elements) {
+        return (elements == null) ? List.of() : Arrays.asList(elements);
+    }
 
-        try {
-            Path contentDirectory = getClassesDirectory();
-            if (!Files.exists(contentDirectory)) {
-                if (!forceCreation) {
-                    getLog().warn("JAR will be empty - no content was marked for inclusion!");
-                }
-            } else {
-                archiver.getArchiver().addDirectory(contentDirectory.toFile(), getIncludes(), getExcludes());
+    /**
+     * Generates the <abbr>JAR</abbr> files.
+     * Map keys are module names or {@code null} if the project does not use module hierarchy.
+     * Values are (<var>type</var>, <var>path</var>) pairs associated with each module where
+     * <var>type</var> is {@code "pom"}, {@code "jar"} or {@code "test-jar"} and <var>path</var>
+     * is the path to the <abbr>POM</abbr> or <abbr>JAR</abbr> file.
+     *
+     * <p>Note that a null key does not necessarily means that the <abbr>JAR</abbr> is not modular.
+     * It only means that the project was not compiled with module hierarchy,
+     * i.e. {@code target/classes/} subdirectories having module names.
+     * A project can be compiled with package hierarchy and still be modular.</p>
+     *
+     * @return the paths to the created archive files
+     * @throws IOException if an error occurred while walking the file tree
+     * @throws MojoException if an error occurred while writing a <abbr>JAR</abbr> file
+     */
+    public Map<String, Map<String, Path>> createArchives() throws IOException, MojoException {
+        final Path classesDirectory = getClassesDirectory();
+        final boolean notExists = Files.notExists(classesDirectory);
+        if (notExists) {
+            if (forceCreation) {
+                log.warn("No JAR created because no content was marked for inclusion.");
+            }
+            if (skipIfEmpty) {
+                log.info(String.format("Skipping packaging of the %s.", getType()));
+                return Map.of();
             }
-
-            archiver.createArchive(session, project, archive);
-
-            return jarFile;
-        } catch (Exception e) {
-            // TODO: improve error handling
-            throw new MojoException("Error assembling JAR", e);
         }
+        archive.setForced(forceCreation);
+        // TODO: we want a null manifest if there is no <archive> configuration.
+        final var archiver = new MavenArchiver();

Review Comment:
   personal preference, but I avoid var



##########
src/main/java/org/apache/maven/plugins/jar/AbstractJarMojo.java:
##########
@@ -207,167 +205,208 @@ protected final Log getLog() {
     protected abstract String getType();
 
     /**
-     * Returns the JAR file to generate, based on an optional classifier.
+     * {@return the scope of dependencies}
+     * It should be {@link PathScope#MAIN_COMPILE} or {@link PathScope#TEST_COMPILE}.
+     * Note that we use compile scope rather than runtime scope because dependencies
+     * cannot appear in {@code requires} statement if they didn't had compile scope.
+     */
+    protected abstract PathScope getDependencyScope();
+
+    /**
+     * {@return the JAR tool to use for archiving the code}
      *
-     * @param basedir the output directory
-     * @param resultFinalName the name of the JAR file
-     * @param classifier an optional classifier
-     * @return the file to generate
+     * @throws MojoException if no JAR tool was found
+     *
+     * @since 4.0.0-beta-2
      */
-    protected Path getJarFile(Path basedir, String resultFinalName, String classifier) {
-        Objects.requireNonNull(basedir, "basedir is not allowed to be null");
-        Objects.requireNonNull(resultFinalName, "finalName is not allowed to be null");
-        String fileName = resultFinalName + (hasClassifier(classifier) ? '-' + classifier : "") + ".jar";
-        return basedir.resolve(fileName);
+    protected ToolProvider getJarTool() throws MojoException {
+        return ToolProvider.findFirst(toolId).orElseThrow(() -> new MojoException("No such \"" + toolId + "\" tool."));
     }
 
     /**
-     * Generates the JAR.
+     * Returns the output time stamp or, as a fallback, the {@code SOURCE_DATE_EPOCH} environment variable.
+     * If the time stamp is expressed in seconds, it is converted to ISO 8601 format. Otherwise it is returned as-is.
      *
-     * @return the path to the created archive file
-     * @throws MojoException in case of an error
+     * @return the time stamp in presumed ISO 8601 format, or {@code null} if none
+     *
+     * @since 4.0.0-beta-2
      */
-    public Path createArchive() throws MojoException {
-        Path basedir = outputDirectory != null
-                ? outputDirectory
-                : Path.of(project.getBuild().getDirectory());
-        String resultFinalName =
-                finalName != null ? finalName : project.getBuild().getFinalName();
-        Path jarFile = getJarFile(basedir, resultFinalName, getClassifier());
-
-        FileSetManager fileSetManager = new FileSetManager();
-        FileSet jarContentFileSet = new FileSet();
-        jarContentFileSet.setDirectory(getClassesDirectory().toAbsolutePath().toString());
-        jarContentFileSet.setIncludes(Arrays.asList(getIncludes()));
-        jarContentFileSet.setExcludes(Arrays.asList(getExcludes()));
-
-        String[] includedFiles = fileSetManager.getIncludedFiles(jarContentFileSet);
-
-        if (detectMultiReleaseJar
-                && Arrays.stream(includedFiles)
-                        .anyMatch(
-                                p -> p.startsWith("META-INF" + File.separatorChar + "versions" + File.separatorChar))) {
-            getLog().debug("Adding 'Multi-Release: true' manifest entry.");
-            archive.addManifestEntry(Attributes.Name.MULTI_RELEASE.toString(), "true");
+    protected String getOutputTimestamp() {
+        String time = nullIfAbsent(outputTimestamp);
+        if (time == null) {
+            time = nullIfAbsent(System.getenv("SOURCE_DATE_EPOCH"));
+            if (time == null) {
+                return null;
+            }
         }
+        if (Runtime.version().feature() < ToolExecutor.JDK_SUPPORT_DATE) {
+            log.warn("Reproducible build requires Java " + ToolExecutor.JDK_SUPPORT_DATE + " or later.");
+            return null;
+        }
+        for (int i = time.length(); --i >= 0; ) {
+            char c = time.charAt(i);
+            if ((c < '0' || c > '9') && (i != 0 || c != '-')) {
+                return time;
+            }
+        }
+        return Instant.ofEpochSecond(Long.parseLong(time)).toString();
+    }
 
-        // May give false positives if the files is named as module descriptor
-        // but is not in the root of the archive or in the versioned area
-        // (and hence not actually a module descriptor).
-        // That is fine since the modular Jar archiver will gracefully
-        // handle such case.
-        // And also such case is unlikely to happen as file ending
-        // with "module-info.class" is unlikely to be included in Jar file
-        // unless it is a module descriptor.
-        boolean containsModuleDescriptor =
-                Arrays.stream(includedFiles).anyMatch(p -> p.endsWith(MODULE_DESCRIPTOR_FILE_NAME));
-
-        String archiverName = containsModuleDescriptor ? "mjar" : "jar";
+    /**
+     * {@return the patterns of files to include, or an empty list if no include pattern was specified}
+     */
+    protected List<String> getIncludes() {
+        return asList(includes);
+    }
 
-        MavenArchiver archiver = new MavenArchiver();
-        archiver.setCreatedBy("Maven JAR Plugin", "org.apache.maven.plugins", "maven-jar-plugin");
-        archiver.setBuildJdkSpecDefaultEntry(archive.getManifest().isAddBuildEnvironmentEntries());
-        archiver.setArchiver((JarArchiver) archivers.get(archiverName));
-        archiver.setOutputFile(jarFile.toFile());
+    /**
+     * {@return the patterns of files to exclude, or an empty list if no exclude pattern was specified}
+     */
+    protected List<String> getExcludes() {
+        return asList(excludes);
+    }
 
-        // configure for Reproducible Builds based on outputTimestamp value
-        archiver.configureReproducibleBuild(outputTimestamp);
+    /**
+     * Returns the output directory and ensures that the directory exists.
+     * The returned directory will be either {@link #outputDirectory} if non-null,
+     * or {@link org.apache.maven.api.model.Build#getDirectory()} otherwise.
+     *
+     * <p>The directory is usually {@code target} and should always exist since it is usually the output
+     * of the compiler plugin. If nevertheless the directory does not exist, then this method creates it.
+     * However, this method does not try to create the parent directory, which should be the Maven sub-project.</p>
+     *
+     * @return the directory containing the generated <abbr>JAR</abbr> files.
+     * @throws IOException if the output directory did not existed and could not be created
+     */
+    protected Path getOutputDirectory() throws IOException {
+        Path dir = outputDirectory;
+        if (dir == null) {
+            dir = Path.of(project.getBuild().getDirectory());
+        }
+        if (Files.notExists(dir)) {
+            dir = Files.createDirectory(dir);
+        }
+        return dir;
+    }
 
-        archive.setForced(forceCreation);
+    /**
+     * Returns the given elements as a list if non-null.
+     *
+     * @param elements the elements, or {@code null}
+     * @return the elements as a list, or {@code null} if the given array was null
+     */
+    private static List<String> asList(String[] elements) {
+        return (elements == null) ? List.of() : Arrays.asList(elements);
+    }
 
-        try {
-            Path contentDirectory = getClassesDirectory();
-            if (!Files.exists(contentDirectory)) {
-                if (!forceCreation) {
-                    getLog().warn("JAR will be empty - no content was marked for inclusion!");
-                }
-            } else {
-                archiver.getArchiver().addDirectory(contentDirectory.toFile(), getIncludes(), getExcludes());
+    /**
+     * Generates the <abbr>JAR</abbr> files.
+     * Map keys are module names or {@code null} if the project does not use module hierarchy.
+     * Values are (<var>type</var>, <var>path</var>) pairs associated with each module where
+     * <var>type</var> is {@code "pom"}, {@code "jar"} or {@code "test-jar"} and <var>path</var>
+     * is the path to the <abbr>POM</abbr> or <abbr>JAR</abbr> file.
+     *
+     * <p>Note that a null key does not necessarily means that the <abbr>JAR</abbr> is not modular.
+     * It only means that the project was not compiled with module hierarchy,
+     * i.e. {@code target/classes/} subdirectories having module names.
+     * A project can be compiled with package hierarchy and still be modular.</p>
+     *
+     * @return the paths to the created archive files
+     * @throws IOException if an error occurred while walking the file tree
+     * @throws MojoException if an error occurred while writing a <abbr>JAR</abbr> file
+     */
+    public Map<String, Map<String, Path>> createArchives() throws IOException, MojoException {
+        final Path classesDirectory = getClassesDirectory();
+        final boolean notExists = Files.notExists(classesDirectory);
+        if (notExists) {
+            if (forceCreation) {
+                log.warn("No JAR created because no content was marked for inclusion.");
+            }
+            if (skipIfEmpty) {
+                log.info(String.format("Skipping packaging of the %s.", getType()));
+                return Map.of();
             }
-
-            archiver.createArchive(session, project, archive);
-
-            return jarFile;
-        } catch (Exception e) {
-            // TODO: improve error handling
-            throw new MojoException("Error assembling JAR", e);
         }
+        archive.setForced(forceCreation);
+        // TODO: we want a null manifest if there is no <archive> configuration.
+        final var archiver = new MavenArchiver();
+        archiver.setCreatedBy("Maven JAR Plugin", "org.apache.maven.plugins", "maven-jar-plugin");
+        archiver.setBuildJdkSpecDefaultEntry(archive.getManifest().isAddBuildEnvironmentEntries());
+        var executor = new ToolExecutor(this, archiver.getManifest(session, project, archive), archive);
+        var files = new FileCollector(this, executor, classesDirectory, matcherFactory);
+        if (!notExists) {
+            Files.walkFileTree(classesDirectory, files);
+        }
+        files.prune(skipIfEmpty);
+        List<Path> moduleRoots = files.getModuleHierarchyRoots();
+        if (!moduleRoots.isEmpty()) {
+            executor.pomDerivation = new PomDerivation(this, moduleRoots);
+        }
+        return executor.writeAllJARs(files);
     }
 
     /**
-     * Generates the JAR.
+     * Generates the <abbr>JAR</abbr> file, then attaches the artifact.
      *
      * @throws MojoException in case of an error
      */
     @Override
+    @SuppressWarnings("UseSpecificCatch")
     public void execute() throws MojoException {
-        if (skipIfEmpty && isEmpty(getClassesDirectory())) {
-            getLog().info(String.format("Skipping packaging of the %s.", getType()));
-        } else {
-            Path jarFile = createArchive();
-
-            if (attach) {
-                ProducedArtifact artifact;
-                String classifier = getClassifier();
-                if (hasClassifier(classifier)) {
-                    artifact = session.createProducedArtifact(
-                            project.getGroupId(),
-                            project.getArtifactId(),
-                            project.getVersion(),
-                            classifier,
-                            null,
-                            getType());
-                } else {
-                    if (projectHasAlreadySetAnArtifact()) {
-                        throw new MojoException("You have to use a classifier "
-                                + "to attach supplemental artifacts to the project instead of replacing them.");
+        final Map<String, Map<String, Path>> artifactFiles;
+        try {
+            artifactFiles = createArchives();
+        } catch (MojoException e) {
+            throw e;
+        } catch (Exception e) {

Review Comment:
   shouldn't need to catch a raw Exception



##########
src/main/java/org/apache/maven/plugins/jar/TimestampCheck.java:
##########
@@ -0,0 +1,237 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.nio.file.attribute.FileTime;
+import java.util.Collection;
+import java.util.Enumeration;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+
+import org.apache.maven.api.plugin.Log;
+
+/**
+ * Checks file timestamps in order to determine if anything changed compared to an existing <abbr>JAR</abbr> file.
+ * This class may scan directories, but only if they have not already been visited by {@link FileCollector}.
+ * Note that the latter can occur only if {@link FileCollector} has no {@code PathMatcher}.
+ * Therefore, this class uses no {@code PathMatcher} neither.
+ *
+ * <h2>Ignore files</h2>
+ * The {@code META-INF/MANIFEST.MF} file and the {@code META-INF/maven/} directory are ignored.
+ * See {@link #isIgnored(Path)} for the rational.
+ */
+final class TimestampCheck extends SimpleFileVisitor<Path> {
+    /**
+     * The base directory of archived files.
+     */
+    private final Path classesDir;
+
+    /**
+     * Path to the existing <abbr>JAR</abbr> file.
+     */
+    private final Path jarFile;
+
+    /**
+     * The last modified time of the <abbr>JAR</abbr> file.
+     */
+    private final FileTime jarFileTime;
+
+    /**
+     * Where to send non-fatal error messages.
+     */
+    private final Log logger;
+
+    /**
+     * Entries of the <abbr>JAR</abbr> file. Note that getting elements from this enumeration can be costly.
+     * Therefore, we do not fetch all elements in advance but only when needed.
+     */
+    private Enumeration<? extends ZipEntry> entries;
+
+    /**
+     * Files found in the <abbr>JAR</abbr> file but not yet traversed by the file visitor.
+     * Files are added lazily only when needed, and removed as soon as they have been traversed.
+     * Path are absolute (resolved with {@link #classesDir}).
+     */
+    private final Set<Path> filesInJAR;
+
+    /**
+     * Some of the files in the build directory. This list contains only the files for which we have already
+     * verified the timestamp. We store them in a separated list for avoiding to check the timestamp twice.

Review Comment:
   separated --> separate



##########
src/main/java/org/apache/maven/plugins/jar/TimestampCheck.java:
##########
@@ -0,0 +1,237 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.nio.file.attribute.FileTime;
+import java.util.Collection;
+import java.util.Enumeration;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+
+import org.apache.maven.api.plugin.Log;
+
+/**
+ * Checks file timestamps in order to determine if anything changed compared to an existing <abbr>JAR</abbr> file.
+ * This class may scan directories, but only if they have not already been visited by {@link FileCollector}.
+ * Note that the latter can occur only if {@link FileCollector} has no {@code PathMatcher}.
+ * Therefore, this class uses no {@code PathMatcher} neither.
+ *
+ * <h2>Ignore files</h2>
+ * The {@code META-INF/MANIFEST.MF} file and the {@code META-INF/maven/} directory are ignored.
+ * See {@link #isIgnored(Path)} for the rational.
+ */
+final class TimestampCheck extends SimpleFileVisitor<Path> {
+    /**
+     * The base directory of archived files.
+     */
+    private final Path classesDir;
+
+    /**
+     * Path to the existing <abbr>JAR</abbr> file.
+     */
+    private final Path jarFile;
+
+    /**
+     * The last modified time of the <abbr>JAR</abbr> file.
+     */
+    private final FileTime jarFileTime;
+
+    /**
+     * Where to send non-fatal error messages.
+     */
+    private final Log logger;
+
+    /**
+     * Entries of the <abbr>JAR</abbr> file. Note that getting elements from this enumeration can be costly.
+     * Therefore, we do not fetch all elements in advance but only when needed.
+     */
+    private Enumeration<? extends ZipEntry> entries;
+
+    /**
+     * Files found in the <abbr>JAR</abbr> file but not yet traversed by the file visitor.
+     * Files are added lazily only when needed, and removed as soon as they have been traversed.
+     * Path are absolute (resolved with {@link #classesDir}).
+     */
+    private final Set<Path> filesInJAR;
+
+    /**
+     * Some of the files in the build directory. This list contains only the files for which we have already
+     * verified the timestamp. We store them in a separated list for avoiding to check the timestamp twice.
+     * We need this list because we still need to verify if the files are in the {@link #jarFile}.
+     */
+    private final Set<Path> filesInBuild;
+
+    /**
+     * Whether at least one file is more recent than the <abbr>JAR</abbr> file.
+     * The scan of files will stop quickly after this flag become {@code true}.

Review Comment:
   quickly? or immediately?



##########
src/main/java/org/apache/maven/plugins/jar/Archive.java:
##########
@@ -0,0 +1,692 @@
+/*
+ * 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.jar;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.TreeMap;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.Type;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.MojoException;
+
+/**
+ * Files or root directories to archive for a single module.
+ * A single instance of {@code Archive} may contain many directories for different target Java releases.
+ * Many instances of {@code Archive} may exist when archiving a multi-modules project.
+ */
+final class Archive {
+    /**
+     * Whether to repeat the {@code -C} option before each file.
+     * Doing so makes the command-line very verbose while the documentation of
+     * <a href="https://docs.oracle.com/en/java/javase/25/docs/specs/man/jar.html">The jar Command</a>
+     * gives the impression that this option can be provided only once.
+     * However, our tests suggest that the first file after the directory specified by the {@code -C} option
+     * must be relative to that directory and all files after the first one must be prefixed by the directory
+     * which was specified in the {@code -C} option. This behavior is not documented, but we couldn't get the
+     * {@code jar} tool to work otherwise (except by repeating {@code -C} before each file).
+     * Furthermore, it seems that the relativized file needs to be the shortest one,
+     * otherwise the {@code jar} tool rejects files after the first one with "names do not match".
+     * Which file is first depends on the unspecified directory-iteration order.
+     *
+     * <p>If this flag is {@code true}, the plugin repeats {@code -C} before each file.
+     * This flag should be set to {@code false} if a future version of the {@code jar}
+     * tool allows to specify {@code -C} only once.</p>
+     *
+     * <p><b>Historical note:</b> we also tried to relativize only the first file after {@code -C}
+     * and keep all subsequent files as absolute. It works, but because we have to repeat the directory
+     * in the file name, it saves only 3 or 4 characters per file compared to repeating {@code -C}.</p>
+     */
+    private static final boolean REPEAT_C = true;
+
+    /**
+     * Path to the <abbr>POM</abbr> file generated for this archive, or {@code null} if none.
+     * This is non-null only if module source hierarchy is used, in which case the dependencies
+     * declared in this file are the intersection of the project dependencies and the content of
+     * the {@code module-info.class} file.
+     */
+    @Nullable
+    Path pomFile;
+
+    /**
+     * The <var>JAR</var> file to create. May be an existing file,
+     * in which case the file creation may be skipped if the file is still up-to-date.
+     */
+    @Nonnull
+    final Path jarFile;
+
+    /**
+     * A helper class for checking whether an existing <abbr>JAR</abbr> file is still up-to-date.
+     * This is null if there is no existing JAR file, or if we determined that the file is outdated.
+     */
+    private TimestampCheck existingJAR;
+
+    /**
+     * Name of the module being archived when the project is using module hierarchy.
+     * This is {@code null} if the project is using package hierarchy, either because it is a classical
+     * class-path project or because it is a single module compiled without using the module hierarchy.
+     * When using module source hierarchy, {@code javac} guarantees that the module name in the output
+     * directory is the name of the parent directory of {@code module-info.class}.
+     */
+    @Nullable
+    final String moduleName;
+
+    /**
+     * Path to {@code META-INF/MANIFEST.MF}, or {@code null} if none.
+     * If non-null, this value will be given to the {@code --manifest} option.
+     * The use of this option is preferable to adding {@code MANIFEST.MF} as an ordinary file.
+     *
+     * @see #setManifest(Path, boolean)
+     * @see #mergeManifest(Path, Manifest)
+     */
+    @Nullable
+    private Path manifest;
+
+    /**
+     * The Maven generated {@code pom.xml} and {@code pom.properties} files, or {@code null} if none.
+     * This first item shall be the base directory where the files are located.
+     */
+    @Nullable
+    List<Path> mavenFiles;
+
+    /**
+     * Fully-qualified name of the main class, or {@code null} if none.
+     * This is the value to provide to the {@code --main-class} option.
+     */
+    private String mainClass;
+
+    /**
+     * Files or root directories to store in the <abbr>JAR</abbr> file for each target Java release
+     * other than the base release. Keys are the target Java release with {@code null} for the base
+     * release.
+     */
+    @Nonnull
+    private final NavigableMap<Runtime.Version, FileSet> filesetForRelease;
+
+    /**
+     * Files or root directories to archive for a single target Java release of a single module.
+     * The {@link Archive} enclosing shall contain at least one instance of {@code FileSet} for
+     * the base release, and an arbitrary amount of other instances for other target releases.
+     */
+    final class FileSet {
+        /**
+         * A comparator for sorting paths in a reproducible order.
+         * This comparator assumes that all paths are relative to the same base directory (this is not verified).
+         * Note: we do not use {@link Path#compareTo(Path)} because the Javadoc said that it is platform dependent.
+         */
+        private static final Comparator<Path> REPRODUCIBLE_ORDER = (p1, p2) -> {
+            final int c1 = p1.getNameCount();
+            final int c2 = p2.getNameCount();
+            final int c = Math.min(c1, c2);
+            for (int i = 0; i < c; i++) {
+                String n1 = p1.getName(i).toString();
+                String n2 = p2.getName(i).toString();
+                int r = n1.compareTo(n2); // Case-sensitive comparison on all platforms.
+                if (r != 0) {
+                    return r;
+                }
+            }
+            return c1 - c2;
+        };
+
+        /**
+         * The root directory of all files or directories to archive.
+         * This is the value to pass to the {@code -C} tool option.
+         */
+        @Nonnull
+        final Path directory;
+
+        /**
+         * The files or directories to include in the <var>JAR</var> file.
+         * May be absolute paths or paths relative to {@link #directory}.
+         */
+        @Nonnull
+        final List<Path> files;
+
+        /**
+         * Creates an initially empty set of files or directories for a specific target Java release.
+         *
+         * @param directory the base directory of the files or directories to archive
+         */
+        private FileSet(Path directory) {
+            this.directory = directory;
+            this.files = new ArrayList<>();
+        }
+
+        /**
+         * 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.
+         * The caller should use that common directory for logging a warning message.
+         *
+         * @param base base directory found by previous invocations of this method, or {@code null} if none
+         * @return common directory of discarded files
+         */
+        private Path discardAllFiles(Path base) {
+            for (Path file : files) {
+                file = directory.resolve(file);
+                if (base == null) {
+                    base = file.getParent();
+                } else {
+                    while (!file.startsWith(base)) {
+                        base = base.getParent();
+                        if (base == null) {
+                            break;
+                        }
+                    }
+                }
+            }
+            files.clear();
+            return base;
+        }
+
+        /**
+         * Adds the given path to the list of files or directories to archive.
+         * This method may store a relative path instead of the absolute path.
+         *
+         * @param item a file or directory to archive
+         * @param attributes the file's basic attributes
+         * @param isDirectory whether the file is a directory
+         * @throws IllegalArgumentException if the given path cannot be made relative to the base directory
+         */
+        void add(Path item, BasicFileAttributes attributes, boolean isDirectory) {
+            TimestampCheck tc = existingJAR;
+            if (tc != null && tc.isUpdated(item, attributes, isDirectory)) {
+                existingJAR = null; // Signal that the existing file is outdated.
+            }
+            item = directory.relativize(item);
+            if (item.getNameCount() <= 1 && item.toString().isEmpty()) {
+                /*
+                 * The item is the `-C` directory itself (e.g. a `META-INF/versions/<n>` directory
+                 * added as a whole). An empty file argument is invalid for the `jar` tool
+                 * (some implementations reject it, others silently misbehave),
+                 * so archive the whole directory content with ".".
+                 */
+                item = Path.of(".");
+            }
+            files.add(item);
+        }
+
+        /**
+         * Adds to the given list the arguments to provide to the "jar" tool for this version.
+         * Elements added to the list shall be instances of {@link String} or {@link Path}.
+         *
+         * @param addTo the list where to add the arguments as {@link String} or {@link Path} instances
+         * @param version the target Java release, or {@code null} for the base version of the <abbr>JAR</abbr> file
+         */
+        private void arguments(List<Object> addTo, Runtime.Version version) {
+            if (!files.isEmpty()) {
+                if (version != null) {
+                    addTo.add("--release");
+                    addTo.add(version);
+                }
+                if (isReproducible) {
+                    files.sort(REPRODUCIBLE_ORDER);
+                }
+                if (REPEAT_C) {
+                    for (Path file : files) {
+                        addTo.add("-C");
+                        addTo.add(directory);
+                        addTo.add(file);
+                    }
+                } else {
+                    addTo.add("-C");
+                    addTo.add(directory);
+                    addTo.addAll(files);
+                }
+            }
+        }
+
+        /**
+         * {@return a string representation for debugging purposes}
+         */
+        @Override
+        public String toString() {
+            return getClass().getSimpleName() + '[' + directory.getFileName() + ": " + files.size() + " files]";
+        }
+    }
+
+    /**
+     * Whether reproducible build was requested.
+     */
+    private final boolean isReproducible;
+
+    /**
+     * Creates an initially empty set of files or directories.
+     *
+     * @param jarFile path to the <abbr>JAR</abbr> file to create
+     * @param moduleName the module name if using module hierarchy, or {@code null} if using package hierarchy
+     * @param version the target Java release, or {@code null} for the base version
+     * @param directory the directory of the classes targeting the base Java release
+     * @param forceCreation whether to force a new <abbr>JAR</abbr> file even if the content seems unchanged
+     * @param isReproducible whether reproducible build was requested
+     * @param logger where to send a warning if an error occurred while checking an existing <abbr>JAR</abbr> file
+     */
+    @SuppressWarnings("checkstyle:NeedBraces")
+    Archive(
+            final Path jarFile,
+            final String moduleName,
+            final Runtime.Version version,
+            final Path directory,
+            final boolean forceCreation,
+            final boolean isReproducible,
+            final Log logger) {
+        this.jarFile = jarFile;
+        this.moduleName = moduleName;
+        this.isReproducible = isReproducible;
+        filesetForRelease = new TreeMap<>((v1, v2) -> {
+            if (v1 == v2) return 0;
+            if (v1 == null) return -1;
+            if (v2 == null) return +1;
+            return v1.compareTo(v2);
+        });
+        filesetForRelease.put(version, new FileSet(directory));
+        if (!forceCreation && Files.isRegularFile(jarFile)) {
+            try {
+                existingJAR = new TimestampCheck(jarFile, directory, logger);
+            } catch (IOException e) {
+                // Ignore, we will regenerate the JAR file.
+                logger.warn(e);
+            }
+        }
+    }
+
+    /**
+     * {@return the files or directories to store in the <abbr>JAR</abbr> file for targeting the base Java release}
+     *
+     * @throws NoSuchElementException should not happen unless {@link #prune(boolean)} has been invoked
+     */
+    FileSet baseRelease() {
+        Map.Entry<Runtime.Version, FileSet> entry = filesetForRelease.firstEntry();
+        String message = null;
+        if (entry != null) {
+            Runtime.Version version = entry.getKey();
+            if (version == null) {
+                return entry.getValue();
+            }
+            message = "Expected base version but found version " + version;
+        }
+        throw new NoSuchElementException(message);
+    }
+
+    /**
+     * Returns the {@code module-info.class} files. Conceptually, there is at most once such file per module.
+     * However, more than one file may exist if additional files are provided for additional Java releases.
+     * This method returns only the files that exist.
+     *
+     * @return all {@code module-info.class} files found for all target Java releases
+     */
+    public List<Path> moduleInfoFiles() {
+        var files = new ArrayList<Path>();
+        filesetForRelease.values().forEach((release) -> {
+            Path file = release.directory.resolve(FileCollector.MODULE_DESCRIPTOR_FILE_NAME);
+            if (Files.isRegularFile(file)) {
+                files.add(file);
+            }
+        });
+        return files;
+    }
+
+    /**
+     * Discards all files in this archive, normally because those files are not in any module.
+     * This method returns a common parent directory for all the files that were discarded.
+     * The caller should use that common directory for logging a warning message.
+     *
+     * @return common directory of discarded files, or {@code null} if none
+     */
+    Path discardAllFiles() {
+        Path base = null;
+        for (FileSet release : filesetForRelease.values()) {
+            base = release.discardAllFiles(base);
+        }
+        filesetForRelease.clear();
+        return base;
+    }
+
+    /**
+     * Removes all empty file sets 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}, then this method ensures that at least one file set
+     * remains even if that file set is empty.
+     *
+     * @param skipIfEmpty value of {@link AbstractJarMojo#skipIfEmpty}
+     */
+    public void prune(final boolean skipIfEmpty) {
+        FileSet keep = (skipIfEmpty || isEmpty())
+                ? null
+                : filesetForRelease.firstEntry().getValue();
+        filesetForRelease.values().removeIf((fs) -> fs.files.isEmpty());
+        Iterator<Map.Entry<Runtime.Version, FileSet>> it =
+                filesetForRelease.entrySet().iterator();
+        if (it.hasNext()) {
+            Map.Entry<Runtime.Version, FileSet> first = it.next();
+            if (first.getKey() == null) {
+                return; // Already contains an entry for the base version, nothing to do.
+            }
+            keep = first.getValue();
+            it.remove();
+        }
+        if (keep != null) {
+            filesetForRelease.put(null, keep);
+        }
+    }
+
+    /**
+     * {@return whether this archive has nothing to archive}
+     * Note that this method may return {@code false} even when there is zero file to archive.
+     * It may happen if {@link AbstractJarMojo#skipIfEmpty} is {@code false}. In such case, the
+     * "empty" <abbr>JAR</abbr> file will still contain at {@code META-INF/MANIFEST.MF} file.
+     *
+     * <h4>Prerequisites</h4>
+     * The {@link #prune(boolean)} method should be invoked before this method for accurate result.
+     */
+    public boolean isEmpty() {
+        return filesetForRelease.isEmpty();
+    }
+
+    /**
+     * Checks whether the <abbr>JAR</abbr> file already exists and can be reused.
+     * This method verifies that the <abbr>JAR</abbr> file contains all the files to archive,
+     * contains no extra file, and no file to archive is newer than the <abbr>JAR</abbr> file.
+     *
+     * <p>This method can be invoked only once.
+     * If invoked more often, it returns {@code false} on all subsequent invocations.</p>
+     *
+     * @return whether the <abbr>JAR</abbr> file already exists and can be reused
+     */
+    public boolean isUpToDateJAR() {
+        final TimestampCheck tc = existingJAR;
+        if (tc == null) {
+            return false;
+        }
+        existingJAR = null; // Let GC do its job.
+        return tc.isUpToDateJAR(filesetForRelease.values());
+    }
+
+    /**
+     * Returns an initially empty set of files or directories for the specified target Java release.
+     *
+     * @param directory the base directory of the files to archive
+     * @param version the target Java release, or {@code null} for the base version
+     * @return container where to declare files and directories to archive
+     */
+    FileSet newTargetRelease(Path directory, Runtime.Version version) {
+        return filesetForRelease.computeIfAbsent(version, (key) -> new FileSet(directory));
+    }
+
+    /**
+     * Sets the {@code --main-class} option to the value of the {@code Main-Class} entry of the given manifest.
+     * As an extension, this method accepts the {@code module/classname} syntax (a syntax already used in some
+     * Java tools). If a module is specified, the main class is kept only if the module match. The intent is to
+     * allow users to specify on which module the main class applies when they use plugin configuration.
+     *
+     * <p>This method may modify the {@code content} manifest. Caller shall ensure that the given manifest
+     * is not a shared instance. This method returns whether a change has actually been done.</p>
+     *
+     * @param content combination of existing {@code MANIFEST.MF} and manifest inferred from configuration, or null
+     * @return whether the given manifest has been modified by this method
+     */
+    boolean setMainClass(Manifest content) {
+        if (content == null || mainClass != null) {
+            return false;
+        }
+        // We need to remove the attribute, otherwise it will conflict with `--main-class`.
+        mainClass = (String) content.getMainAttributes().remove(Attributes.Name.MAIN_CLASS);
+        if (mainClass != null) {
+            int s = mainClass.indexOf('/');
+            if (s >= 0) {
+                if (mainClass.substring(0, s).strip().equals(moduleName)) {
+                    mainClass = mainClass.substring(s + 1).strip();
+                } else {
+                    mainClass = null; // Main class is defined for another module.
+                }
+            }
+        }
+        return mainClass != null;
+    }
+
+    /**
+     * Sets the {@code --manifest} option to the given value if that option was not already set.
+     *
+     * @param file path to the manifest file
+     * @param force whether to set the manifest even if already set
+     * @return whether the manifest has been set
+     */
+    boolean setManifest(Path file, boolean force) {
+        if (manifest == null || force) {
+            manifest = file;
+            return true;
+        }
+        return false;
+    }
+
+    /**
+     * Merges the manifest of this module with the manifest specified in plugin configuration.
+     * If both {@code file} and {@code content} are non-null, then {@code content} must be the
+     * result of reading {@code file}.
+     *
+     * <p>This method never modifies the given {@code content} object. If manifest are merged,
+     * a new {@link Manifest} instance is created. Therefore, caller can check whether this
+     * method returned a new instance as a way to recognize that a merge occurred.</p>
+     *
+     * <p>If a merge occurs, the content specified to {@link #setManifest(Path)} has precedence.
+     * It should be the {@code target/classes/META-INF/MANIFEST.MF} file (or modular equivalent).</p>
+     *
+     * @param  file     an additional manifest file, or {@code null}
+     * @param  content  the content of {@code file}, or a standalone manifest produced at runtime
+     * @return the merged manifest as a new instance if some changes were necessary
+     * @throws IOException if an error occurred while reading a manifest file
+     */
+    Manifest mergeManifest(Path file, Manifest content) throws IOException {
+        if (manifest == null) {
+            manifest = file;
+        } else if (file != null && Files.isSameFile(file, manifest)) {
+            // Nothing to merge because of the constraint that `content` must be the content of `file`.
+        } else {
+            try (InputStream in = Files.newInputStream(manifest)) {
+                // No need to wrap in `BufferedInputStream`.
+                if (content != null) {
+                    content = new Manifest(content);
+                    content.read(in);
+                } else {
+                    content = new Manifest(in);
+                }
+            }
+        }
+        return content;
+    }
+
+    /**
+     * Adds to the given list the arguments to provide to the "jar" tool for each version.

Review Comment:
   delete "to the given list"



##########
src/main/java/org/apache/maven/plugins/jar/TimestampCheck.java:
##########
@@ -0,0 +1,237 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.nio.file.attribute.FileTime;
+import java.util.Collection;
+import java.util.Enumeration;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+
+import org.apache.maven.api.plugin.Log;
+
+/**
+ * Checks file timestamps in order to determine if anything changed compared to an existing <abbr>JAR</abbr> file.
+ * This class may scan directories, but only if they have not already been visited by {@link FileCollector}.
+ * Note that the latter can occur only if {@link FileCollector} has no {@code PathMatcher}.
+ * Therefore, this class uses no {@code PathMatcher} neither.
+ *
+ * <h2>Ignore files</h2>
+ * The {@code META-INF/MANIFEST.MF} file and the {@code META-INF/maven/} directory are ignored.
+ * See {@link #isIgnored(Path)} for the rational.
+ */
+final class TimestampCheck extends SimpleFileVisitor<Path> {
+    /**
+     * The base directory of archived files.
+     */
+    private final Path classesDir;
+
+    /**
+     * Path to the existing <abbr>JAR</abbr> file.
+     */
+    private final Path jarFile;
+
+    /**
+     * The last modified time of the <abbr>JAR</abbr> file.
+     */
+    private final FileTime jarFileTime;
+
+    /**
+     * Where to send non-fatal error messages.
+     */
+    private final Log logger;
+
+    /**
+     * Entries of the <abbr>JAR</abbr> file. Note that getting elements from this enumeration can be costly.
+     * Therefore, we do not fetch all elements in advance but only when needed.
+     */
+    private Enumeration<? extends ZipEntry> entries;
+
+    /**
+     * Files found in the <abbr>JAR</abbr> file but not yet traversed by the file visitor.
+     * Files are added lazily only when needed, and removed as soon as they have been traversed.

Review Comment:
   delete only



##########
src/main/java/org/apache/maven/plugins/jar/TimestampCheck.java:
##########
@@ -0,0 +1,237 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.nio.file.attribute.FileTime;
+import java.util.Collection;
+import java.util.Enumeration;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+
+import org.apache.maven.api.plugin.Log;
+
+/**
+ * Checks file timestamps in order to determine if anything changed compared to an existing <abbr>JAR</abbr> file.
+ * This class may scan directories, but only if they have not already been visited by {@link FileCollector}.
+ * Note that the latter can occur only if {@link FileCollector} has no {@code PathMatcher}.
+ * Therefore, this class uses no {@code PathMatcher} neither.
+ *
+ * <h2>Ignore files</h2>
+ * The {@code META-INF/MANIFEST.MF} file and the {@code META-INF/maven/} directory are ignored.
+ * See {@link #isIgnored(Path)} for the rational.
+ */
+final class TimestampCheck extends SimpleFileVisitor<Path> {
+    /**
+     * The base directory of archived files.
+     */
+    private final Path classesDir;
+
+    /**
+     * Path to the existing <abbr>JAR</abbr> file.
+     */
+    private final Path jarFile;
+
+    /**
+     * The last modified time of the <abbr>JAR</abbr> file.
+     */
+    private final FileTime jarFileTime;
+
+    /**
+     * Where to send non-fatal error messages.
+     */
+    private final Log logger;
+
+    /**
+     * Entries of the <abbr>JAR</abbr> file. Note that getting elements from this enumeration can be costly.
+     * Therefore, we do not fetch all elements in advance but only when needed.
+     */
+    private Enumeration<? extends ZipEntry> entries;
+
+    /**
+     * Files found in the <abbr>JAR</abbr> file but not yet traversed by the file visitor.
+     * Files are added lazily only when needed, and removed as soon as they have been traversed.
+     * Path are absolute (resolved with {@link #classesDir}).
+     */
+    private final Set<Path> filesInJAR;
+
+    /**
+     * Some of the files in the build directory. This list contains only the files for which we have already
+     * verified the timestamp. We store them in a separated list for avoiding to check the timestamp twice.
+     * We need this list because we still need to verify if the files are in the {@link #jarFile}.
+     */
+    private final Set<Path> filesInBuild;
+
+    /**
+     * Whether at least one file is more recent than the <abbr>JAR</abbr> file.
+     * The scan of files will stop quickly after this flag become {@code true}.
+     */
+    private boolean hasUpdates;
+
+    /**
+     * Creates a new visitor for checking the validity of a <abbr>JAR</abbr> file.
+     *
+     * @param jarFile the existing <abbr>JAR</abbr> file
+     * @param jarFileTime the last modified time of the <abbr>JAR</abbr> file
+     * @param classesDir base directory of archived files
+     * @param logger where to send a warning if an error occurred while checking an existing <abbr>JAR</abbr> file
+     * @throws IOException if an error occurred while fetching the <abbr>JAR</abbr> file modification time
+     */
+    TimestampCheck(final Path jarFile, final Path classesDir, final Log logger) throws IOException {
+        this.classesDir = classesDir;
+        this.jarFile = jarFile;
+        this.logger = logger;
+        jarFileTime = Files.getLastModifiedTime(jarFile);
+        filesInJAR = new HashSet<>();
+        filesInBuild = new HashSet<>();
+    }
+
+    /**
+     * Returns {@code true} if the given file is more recent that the <abbr>JAR</abbr> file.
+     *
+     * @param file the file to check
+     * @param attributes the file's basic attributes
+     * @param isDirectory whether the file is a directory
+     * @return whether the modification time is more recent that the <abbr>JAR</abbr> file
+     */
+    boolean isUpdated(final Path file, final BasicFileAttributes attributes, final boolean isDirectory) {
+        if (jarFileTime.compareTo(attributes.lastModifiedTime()) < 0) {
+            return true;
+        }
+        if (!isDirectory) {
+            filesInBuild.add(file);
+        }
+        return false;
+    }
+
+    /**
+     * Checks if the <abbr>JAR</abbr> file contains all the given files, no extra entry, and no outdated entry.
+     *
+     * @param fileSets pairs of base directory and files potentially relative to the base directory
+     * @return whether the <abbr>JAR</abbr> file is up-to-date
+     */
+    boolean isUpToDateJAR(final Collection<Archive.FileSet> fileSets) {
+        // No need to use JarFile because no need to handle META-INF in a special way.
+        try (ZipFile jar = new ZipFile(jarFile.toFile())) {
+            entries = jar.entries();
+            for (Path file : filesInBuild) {
+                if (!isFoundInJAR(file)) {
+                    return false;
+                }
+            }
+            for (Archive.FileSet fileSet : fileSets) {
+                final Path baseDir = fileSet.directory;
+                for (Path file : fileSet.files) {
+                    file = baseDir.resolve(file);
+                    if (!filesInBuild.remove(file)) { // For skipping the files already verified by above loop.
+                        Files.walkFileTree(file, this);
+                        if (hasUpdates) {
+                            return false;
+                        }
+                    }
+                }
+            }
+            // Check for remaining files in the JAR which were not in the build directory.
+            for (Path file : filesInJAR) {
+                if (!isIgnored(classesDir.relativize(file))) {
+                    return false;
+                }
+            }
+            while (entries.hasMoreElements()) {
+                ZipEntry entry = entries.nextElement();
+                if (!(entry.isDirectory() || isIgnored(Path.of(entry.getName())))) {
+                    return false;
+                }
+            }
+        } catch (IOException e) {
+            logger.warn(e);
+            return false;
+        } finally {
+            entries = null;
+        }
+        return true;
+    }
+
+    /**
+     * Returns whether the given file in a <abbr>JAR</abbr> file should be ignored.
+     * We have to ignore the files that are generated in a temporary directory
+     * because they do not exist yet when the directory is traversed. Furthermore,
+     * their timestamp would always be newer then the <abbr>JAR</abbr> file anyway.
+     *
+     * @param file path to a file relative to the root of the <abbr>JAR</abbr> file
+     */
+    private static boolean isIgnored(Path file) {
+        if (file.startsWith(MetadataFiles.META_INF)) {
+            file = file.subpath(1, file.getNameCount());
+            if (file.startsWith(MetadataFiles.MANIFEST)) {
+                return file.getNameCount() == 1;
+            } else if (file.startsWith(MetadataFiles.MAVEN_DIR)) {
+                return true; // Ignore all subdirectories.
+            }
+        }
+        return false;
+    }
+
+    /**
+     * Checks if the given file is new or more recent than the <abbr>JAR</abbr> file.
+     * Checks also if the file exists in the <abbr>JAR</abbr> file.
+     *
+     * @param file the traversed file
+     * @param attributes the file's basic attributes
+     */
+    @Override
+    public FileVisitResult visitFile(final Path file, final BasicFileAttributes attributes) {
+        if (jarFileTime.compareTo(attributes.lastModifiedTime()) >= 0 && isFoundInJAR(file)) {
+            return FileVisitResult.CONTINUE;
+        } else {
+            hasUpdates = true;
+            return FileVisitResult.TERMINATE;
+        }
+    }
+
+    /**
+     * Returns whether the given file is found in the <abbr>JAR</abbr> file.
+     *
+     * @param file the file to check
+     * @return whether the given file was found in the <abbr>JAR</abbr> file
+     */
+    private boolean isFoundInJAR(final Path file) {
+        if (filesInJAR.remove(file)) {

Review Comment:
   This method probably shouldn't be mutating things. Or if it should, it needs a different name.



##########
src/main/java/org/apache/maven/plugins/jar/Archive.java:
##########
@@ -0,0 +1,692 @@
+/*
+ * 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.jar;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.TreeMap;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.Type;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.MojoException;
+
+/**
+ * Files or root directories to archive for a single module.
+ * A single instance of {@code Archive} may contain many directories for different target Java releases.
+ * Many instances of {@code Archive} may exist when archiving a multi-modules project.
+ */
+final class Archive {
+    /**
+     * Whether to repeat the {@code -C} option before each file.
+     * Doing so makes the command-line very verbose while the documentation of
+     * <a href="https://docs.oracle.com/en/java/javase/25/docs/specs/man/jar.html">The jar Command</a>
+     * gives the impression that this option can be provided only once.
+     * However, our tests suggest that the first file after the directory specified by the {@code -C} option
+     * must be relative to that directory and all files after the first one must be prefixed by the directory
+     * which was specified in the {@code -C} option. This behavior is not documented, but we couldn't get the
+     * {@code jar} tool to work otherwise (except by repeating {@code -C} before each file).
+     * Furthermore, it seems that the relativized file needs to be the shortest one,
+     * otherwise the {@code jar} tool rejects files after the first one with "names do not match".
+     * Which file is first depends on the unspecified directory-iteration order.
+     *
+     * <p>If this flag is {@code true}, the plugin repeats {@code -C} before each file.
+     * This flag should be set to {@code false} if a future version of the {@code jar}
+     * tool allows to specify {@code -C} only once.</p>
+     *
+     * <p><b>Historical note:</b> we also tried to relativize only the first file after {@code -C}
+     * and keep all subsequent files as absolute. It works, but because we have to repeat the directory
+     * in the file name, it saves only 3 or 4 characters per file compared to repeating {@code -C}.</p>
+     */
+    private static final boolean REPEAT_C = true;
+
+    /**
+     * Path to the <abbr>POM</abbr> file generated for this archive, or {@code null} if none.
+     * This is non-null only if module source hierarchy is used, in which case the dependencies
+     * declared in this file are the intersection of the project dependencies and the content of
+     * the {@code module-info.class} file.
+     */
+    @Nullable
+    Path pomFile;
+
+    /**
+     * The <var>JAR</var> file to create. May be an existing file,
+     * in which case the file creation may be skipped if the file is still up-to-date.
+     */
+    @Nonnull
+    final Path jarFile;
+
+    /**
+     * A helper class for checking whether an existing <abbr>JAR</abbr> file is still up-to-date.
+     * This is null if there is no existing JAR file, or if we determined that the file is outdated.
+     */
+    private TimestampCheck existingJAR;
+
+    /**
+     * Name of the module being archived when the project is using module hierarchy.
+     * This is {@code null} if the project is using package hierarchy, either because it is a classical
+     * class-path project or because it is a single module compiled without using the module hierarchy.
+     * When using module source hierarchy, {@code javac} guarantees that the module name in the output
+     * directory is the name of the parent directory of {@code module-info.class}.
+     */
+    @Nullable
+    final String moduleName;
+
+    /**
+     * Path to {@code META-INF/MANIFEST.MF}, or {@code null} if none.
+     * If non-null, this value will be given to the {@code --manifest} option.
+     * The use of this option is preferable to adding {@code MANIFEST.MF} as an ordinary file.
+     *
+     * @see #setManifest(Path, boolean)
+     * @see #mergeManifest(Path, Manifest)
+     */
+    @Nullable
+    private Path manifest;
+
+    /**
+     * The Maven generated {@code pom.xml} and {@code pom.properties} files, or {@code null} if none.
+     * This first item shall be the base directory where the files are located.
+     */
+    @Nullable
+    List<Path> mavenFiles;
+
+    /**
+     * Fully-qualified name of the main class, or {@code null} if none.
+     * This is the value to provide to the {@code --main-class} option.
+     */
+    private String mainClass;
+
+    /**
+     * Files or root directories to store in the <abbr>JAR</abbr> file for each target Java release
+     * other than the base release. Keys are the target Java release with {@code null} for the base
+     * release.
+     */
+    @Nonnull
+    private final NavigableMap<Runtime.Version, FileSet> filesetForRelease;
+
+    /**
+     * Files or root directories to archive for a single target Java release of a single module.
+     * The {@link Archive} enclosing shall contain at least one instance of {@code FileSet} for
+     * the base release, and an arbitrary amount of other instances for other target releases.
+     */
+    final class FileSet {
+        /**
+         * A comparator for sorting paths in a reproducible order.
+         * This comparator assumes that all paths are relative to the same base directory (this is not verified).
+         * Note: we do not use {@link Path#compareTo(Path)} because the Javadoc said that it is platform dependent.
+         */
+        private static final Comparator<Path> REPRODUCIBLE_ORDER = (p1, p2) -> {
+            final int c1 = p1.getNameCount();
+            final int c2 = p2.getNameCount();
+            final int c = Math.min(c1, c2);
+            for (int i = 0; i < c; i++) {
+                String n1 = p1.getName(i).toString();
+                String n2 = p2.getName(i).toString();
+                int r = n1.compareTo(n2); // Case-sensitive comparison on all platforms.
+                if (r != 0) {
+                    return r;
+                }
+            }
+            return c1 - c2;
+        };
+
+        /**
+         * The root directory of all files or directories to archive.
+         * This is the value to pass to the {@code -C} tool option.
+         */
+        @Nonnull
+        final Path directory;
+
+        /**
+         * The files or directories to include in the <var>JAR</var> file.
+         * May be absolute paths or paths relative to {@link #directory}.
+         */
+        @Nonnull
+        final List<Path> files;
+
+        /**
+         * Creates an initially empty set of files or directories for a specific target Java release.
+         *
+         * @param directory the base directory of the files or directories to archive
+         */
+        private FileSet(Path directory) {
+            this.directory = directory;
+            this.files = new ArrayList<>();
+        }
+
+        /**
+         * 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.
+         * The caller should use that common directory for logging a warning message.
+         *
+         * @param base base directory found by previous invocations of this method, or {@code null} if none
+         * @return common directory of discarded files
+         */
+        private Path discardAllFiles(Path base) {
+            for (Path file : files) {
+                file = directory.resolve(file);
+                if (base == null) {
+                    base = file.getParent();
+                } else {
+                    while (!file.startsWith(base)) {
+                        base = base.getParent();
+                        if (base == null) {
+                            break;
+                        }
+                    }
+                }
+            }
+            files.clear();
+            return base;
+        }
+
+        /**
+         * Adds the given path to the list of files or directories to archive.
+         * This method may store a relative path instead of the absolute path.
+         *
+         * @param item a file or directory to archive
+         * @param attributes the file's basic attributes
+         * @param isDirectory whether the file is a directory
+         * @throws IllegalArgumentException if the given path cannot be made relative to the base directory
+         */
+        void add(Path item, BasicFileAttributes attributes, boolean isDirectory) {
+            TimestampCheck tc = existingJAR;
+            if (tc != null && tc.isUpdated(item, attributes, isDirectory)) {
+                existingJAR = null; // Signal that the existing file is outdated.
+            }
+            item = directory.relativize(item);
+            if (item.getNameCount() <= 1 && item.toString().isEmpty()) {
+                /*
+                 * The item is the `-C` directory itself (e.g. a `META-INF/versions/<n>` directory
+                 * added as a whole). An empty file argument is invalid for the `jar` tool
+                 * (some implementations reject it, others silently misbehave),
+                 * so archive the whole directory content with ".".
+                 */
+                item = Path.of(".");
+            }
+            files.add(item);
+        }
+
+        /**
+         * Adds to the given list the arguments to provide to the "jar" tool for this version.
+         * Elements added to the list shall be instances of {@link String} or {@link Path}.
+         *
+         * @param addTo the list where to add the arguments as {@link String} or {@link Path} instances
+         * @param version the target Java release, or {@code null} for the base version of the <abbr>JAR</abbr> file
+         */
+        private void arguments(List<Object> addTo, Runtime.Version version) {
+            if (!files.isEmpty()) {
+                if (version != null) {
+                    addTo.add("--release");
+                    addTo.add(version);
+                }
+                if (isReproducible) {
+                    files.sort(REPRODUCIBLE_ORDER);
+                }
+                if (REPEAT_C) {
+                    for (Path file : files) {
+                        addTo.add("-C");
+                        addTo.add(directory);
+                        addTo.add(file);
+                    }
+                } else {
+                    addTo.add("-C");
+                    addTo.add(directory);
+                    addTo.addAll(files);
+                }
+            }
+        }
+
+        /**
+         * {@return a string representation for debugging purposes}
+         */
+        @Override
+        public String toString() {
+            return getClass().getSimpleName() + '[' + directory.getFileName() + ": " + files.size() + " files]";
+        }
+    }
+
+    /**
+     * Whether reproducible build was requested.
+     */
+    private final boolean isReproducible;
+
+    /**
+     * Creates an initially empty set of files or directories.
+     *
+     * @param jarFile path to the <abbr>JAR</abbr> file to create
+     * @param moduleName the module name if using module hierarchy, or {@code null} if using package hierarchy
+     * @param version the target Java release, or {@code null} for the base version
+     * @param directory the directory of the classes targeting the base Java release
+     * @param forceCreation whether to force a new <abbr>JAR</abbr> file even if the content seems unchanged
+     * @param isReproducible whether reproducible build was requested
+     * @param logger where to send a warning if an error occurred while checking an existing <abbr>JAR</abbr> file
+     */
+    @SuppressWarnings("checkstyle:NeedBraces")
+    Archive(
+            final Path jarFile,
+            final String moduleName,
+            final Runtime.Version version,
+            final Path directory,
+            final boolean forceCreation,
+            final boolean isReproducible,
+            final Log logger) {
+        this.jarFile = jarFile;
+        this.moduleName = moduleName;
+        this.isReproducible = isReproducible;
+        filesetForRelease = new TreeMap<>((v1, v2) -> {
+            if (v1 == v2) return 0;
+            if (v1 == null) return -1;
+            if (v2 == null) return +1;
+            return v1.compareTo(v2);
+        });
+        filesetForRelease.put(version, new FileSet(directory));
+        if (!forceCreation && Files.isRegularFile(jarFile)) {
+            try {
+                existingJAR = new TimestampCheck(jarFile, directory, logger);
+            } catch (IOException e) {
+                // Ignore, we will regenerate the JAR file.
+                logger.warn(e);
+            }
+        }
+    }
+
+    /**
+     * {@return the files or directories to store in the <abbr>JAR</abbr> file for targeting the base Java release}
+     *
+     * @throws NoSuchElementException should not happen unless {@link #prune(boolean)} has been invoked
+     */
+    FileSet baseRelease() {
+        Map.Entry<Runtime.Version, FileSet> entry = filesetForRelease.firstEntry();
+        String message = null;
+        if (entry != null) {
+            Runtime.Version version = entry.getKey();
+            if (version == null) {
+                return entry.getValue();
+            }
+            message = "Expected base version but found version " + version;
+        }
+        throw new NoSuchElementException(message);
+    }
+
+    /**
+     * Returns the {@code module-info.class} files. Conceptually, there is at most once such file per module.
+     * However, more than one file may exist if additional files are provided for additional Java releases.
+     * This method returns only the files that exist.
+     *
+     * @return all {@code module-info.class} files found for all target Java releases
+     */
+    public List<Path> moduleInfoFiles() {
+        var files = new ArrayList<Path>();
+        filesetForRelease.values().forEach((release) -> {
+            Path file = release.directory.resolve(FileCollector.MODULE_DESCRIPTOR_FILE_NAME);
+            if (Files.isRegularFile(file)) {
+                files.add(file);
+            }
+        });
+        return files;
+    }
+
+    /**
+     * Discards all files in this archive, normally because those files are not in any module.
+     * This method returns a common parent directory for all the files that were discarded.
+     * The caller should use that common directory for logging a warning message.
+     *
+     * @return common directory of discarded files, or {@code null} if none
+     */
+    Path discardAllFiles() {
+        Path base = null;
+        for (FileSet release : filesetForRelease.values()) {
+            base = release.discardAllFiles(base);
+        }
+        filesetForRelease.clear();
+        return base;
+    }
+
+    /**
+     * Removes all empty file sets 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}, then this method ensures that at least one file set
+     * remains even if that file set is empty.
+     *
+     * @param skipIfEmpty value of {@link AbstractJarMojo#skipIfEmpty}
+     */
+    public void prune(final boolean skipIfEmpty) {
+        FileSet keep = (skipIfEmpty || isEmpty())
+                ? null
+                : filesetForRelease.firstEntry().getValue();
+        filesetForRelease.values().removeIf((fs) -> fs.files.isEmpty());
+        Iterator<Map.Entry<Runtime.Version, FileSet>> it =
+                filesetForRelease.entrySet().iterator();
+        if (it.hasNext()) {
+            Map.Entry<Runtime.Version, FileSet> first = it.next();
+            if (first.getKey() == null) {
+                return; // Already contains an entry for the base version, nothing to do.
+            }
+            keep = first.getValue();
+            it.remove();
+        }
+        if (keep != null) {
+            filesetForRelease.put(null, keep);
+        }
+    }
+
+    /**
+     * {@return whether this archive has nothing to archive}
+     * Note that this method may return {@code false} even when there is zero file to archive.
+     * It may happen if {@link AbstractJarMojo#skipIfEmpty} is {@code false}. In such case, the
+     * "empty" <abbr>JAR</abbr> file will still contain at {@code META-INF/MANIFEST.MF} file.
+     *
+     * <h4>Prerequisites</h4>
+     * The {@link #prune(boolean)} method should be invoked before this method for accurate result.
+     */
+    public boolean isEmpty() {
+        return filesetForRelease.isEmpty();
+    }
+
+    /**
+     * Checks whether the <abbr>JAR</abbr> file already exists and can be reused.
+     * This method verifies that the <abbr>JAR</abbr> file contains all the files to archive,
+     * contains no extra file, and no file to archive is newer than the <abbr>JAR</abbr> file.
+     *
+     * <p>This method can be invoked only once.
+     * If invoked more often, it returns {@code false} on all subsequent invocations.</p>
+     *
+     * @return whether the <abbr>JAR</abbr> file already exists and can be reused
+     */
+    public boolean isUpToDateJAR() {
+        final TimestampCheck tc = existingJAR;
+        if (tc == null) {
+            return false;
+        }
+        existingJAR = null; // Let GC do its job.
+        return tc.isUpToDateJAR(filesetForRelease.values());
+    }
+
+    /**
+     * Returns an initially empty set of files or directories for the specified target Java release.
+     *
+     * @param directory the base directory of the files to archive
+     * @param version the target Java release, or {@code null} for the base version
+     * @return container where to declare files and directories to archive
+     */
+    FileSet newTargetRelease(Path directory, Runtime.Version version) {
+        return filesetForRelease.computeIfAbsent(version, (key) -> new FileSet(directory));
+    }
+
+    /**
+     * Sets the {@code --main-class} option to the value of the {@code Main-Class} entry of the given manifest.
+     * As an extension, this method accepts the {@code module/classname} syntax (a syntax already used in some
+     * Java tools). If a module is specified, the main class is kept only if the module match. The intent is to
+     * allow users to specify on which module the main class applies when they use plugin configuration.
+     *
+     * <p>This method may modify the {@code content} manifest. Caller shall ensure that the given manifest
+     * is not a shared instance. This method returns whether a change has actually been done.</p>
+     *
+     * @param content combination of existing {@code MANIFEST.MF} and manifest inferred from configuration, or null
+     * @return whether the given manifest has been modified by this method
+     */
+    boolean setMainClass(Manifest content) {
+        if (content == null || mainClass != null) {
+            return false;
+        }
+        // We need to remove the attribute, otherwise it will conflict with `--main-class`.
+        mainClass = (String) content.getMainAttributes().remove(Attributes.Name.MAIN_CLASS);
+        if (mainClass != null) {
+            int s = mainClass.indexOf('/');
+            if (s >= 0) {
+                if (mainClass.substring(0, s).strip().equals(moduleName)) {
+                    mainClass = mainClass.substring(s + 1).strip();
+                } else {
+                    mainClass = null; // Main class is defined for another module.
+                }
+            }
+        }
+        return mainClass != null;
+    }
+
+    /**
+     * Sets the {@code --manifest} option to the given value if that option was not already set.
+     *
+     * @param file path to the manifest file
+     * @param force whether to set the manifest even if already set
+     * @return whether the manifest has been set
+     */
+    boolean setManifest(Path file, boolean force) {
+        if (manifest == null || force) {
+            manifest = file;
+            return true;
+        }
+        return false;
+    }
+
+    /**
+     * Merges the manifest of this module with the manifest specified in plugin configuration.
+     * If both {@code file} and {@code content} are non-null, then {@code content} must be the
+     * result of reading {@code file}.
+     *
+     * <p>This method never modifies the given {@code content} object. If manifest are merged,
+     * a new {@link Manifest} instance is created. Therefore, caller can check whether this
+     * method returned a new instance as a way to recognize that a merge occurred.</p>
+     *
+     * <p>If a merge occurs, the content specified to {@link #setManifest(Path)} has precedence.
+     * It should be the {@code target/classes/META-INF/MANIFEST.MF} file (or modular equivalent).</p>
+     *
+     * @param  file     an additional manifest file, or {@code null}
+     * @param  content  the content of {@code file}, or a standalone manifest produced at runtime
+     * @return the merged manifest as a new instance if some changes were necessary
+     * @throws IOException if an error occurred while reading a manifest file
+     */
+    Manifest mergeManifest(Path file, Manifest content) throws IOException {
+        if (manifest == null) {
+            manifest = file;
+        } else if (file != null && Files.isSameFile(file, manifest)) {
+            // Nothing to merge because of the constraint that `content` must be the content of `file`.
+        } else {
+            try (InputStream in = Files.newInputStream(manifest)) {
+                // No need to wrap in `BufferedInputStream`.
+                if (content != null) {
+                    content = new Manifest(content);
+                    content.read(in);
+                } else {
+                    content = new Manifest(in);
+                }
+            }
+        }
+        return content;
+    }
+
+    /**
+     * Adds to the given list the arguments to provide to the "jar" tool for each version.
+     * Elements added to the list shall be instances of {@link String} or {@link Path}.
+     * Callers should have added the following options (if applicable) before to invoke this method:

Review Comment:
   unclear



##########
src/main/java/org/apache/maven/plugins/jar/DirectoryRole.java:
##########
@@ -0,0 +1,73 @@
+/*
+ * 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.jar;
+
+/**
+ * Directories that the archiver needs to handle in a special way.
+ */
+enum DirectoryRole {
+    /**
+     * The root directory. This is usually {@code "target/classes"}.
+     * The next locations can be {@link #META_INF}, {@link #NAMED_MODULE} or {@link #RESOURCES}.
+     */
+    ROOT,
+
+    /**
+     * The {@code "META-INF"} or {@code "<module>/META-INF"} directory.
+     * This is part of the <abbr>JAR</abbr> specification.
+     * The next locations can be {@link #VERSIONS} or {@link #VERSIONS_MODULAR}.
+     */
+    META_INF,
+
+    /**
+     * The {@code "META-INF/versions"} or {@code "<module>/META-INF/versions"} directory.
+     * This is part of the <abbr>JAR</abbr> specification, except the {@code <module>} prefix.
+     * The sub-directories are named according Java releases such as "21".
+     * The next location can only be {@link #RESOURCES}.
+     */
+    VERSIONS,
+
+    /**
+     * The Maven-specific {@code "META-INF/versions-modular"} directory.
+     * Note that {@code "<module>/META-INF/versions-modular"} is not forbidden, but does not make sense.

Review Comment:
   delete "Note that"



##########
src/main/java/org/apache/maven/plugins/jar/FileCollector.java:
##########
@@ -0,0 +1,496 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.PathMatcher;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayDeque;
+import java.util.Deque;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.services.PathMatcherFactory;
+
+/**
+ * Dispatch the files in the output directory into the <abbr>JAR</abbr> files to create.
+ * Instead of just archiving as-is the content of the output directory, this class separates
+ * the following subdirectories to the options listed below:
+ *
+ * <ul>
+ *   <li>The {@code META-INF/MANIFEST.MF} file will be given to the {@code --manifest} option.</li>
+ *   <li>Files in the following directories will be given to the {@code --release} option:
+ *     <ul>
+ *       <li>{@code META-INF/versions/}</li>
+ *       <li>{@code META-INF/versions-modular/<module>/}</li>
+ *       <li>{@code <module>/META-INF/versions/}</li>
+ *     </ul>
+ *   </li>
+ * </ul>
+ *
+ * The reason for using the options is that they allow the {@code jar} tool to perform additional verifications.
+ * For example, when using the {@code --release} option, {@code jar} verifies the <abbr>API</abbr> compatibility.
+ */
+final class FileCollector extends SimpleFileVisitor<Path> {
+    /**
+     * The file to check for deciding whether the <abbr>JAR</abbr> is modular.
+     */
+    static final String MODULE_DESCRIPTOR_FILE_NAME = "module-info.class";
+
+    /**
+     * The {@value} directory.
+     * This is part of <abbr>JAR</abbr> file specification.
+     */
+    private static final String VERSIONS = "versions";
+
+    /**
+     * The {@value} directory.
+     * This is Maven-specific.
+     */
+    private static final String VERSIONS_MODULAR = "versions-modular";
+
+    /**
+     * Context (logger, configuration) in which the <abbr>JAR</abbr> file are created.
+     */
+    private final ToolExecutor context;
+
+    /**
+     * Whether to detect multi-release <abbr>JAR</abbr> files.
+     * The default value is {@code true}.
+     *
+     * @see AbstractJarMojo#detectMultiReleaseJar
+     */
+    private final boolean detectMultiReleaseJar;
+
+    /**
+     * Combination of includes and excludes path matcher applied on files.
+     */
+    @Nonnull
+    private final PathMatcher fileMatcher;
+
+    /**
+     * Combination of includes and excludes path matcher applied on directories.
+     */
+    @Nonnull
+    private final PathMatcher directoryMatcher;
+
+    /**
+     * Whether the matchers accept all files and there is no need to sort the files.
+     * In such case, we can declare whole directories to the {@code jar} tool instead
+     * of scanning the directory tree ourselves.
+     */
+    private final boolean addDirectories;
+
+    /**
+     * Files found in the output directory when package hierarchy is used.
+     * At most one of {@code packageHierarchy} and {@link #moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Archive packageHierarchy;
+
+    /**
+     * Files found in the output directory when module hierarchy is used. Keys are module names.
+     * At most one of {@link #packageHierarchy} and {@code moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Map<String, Archive> moduleHierarchy;
+
+    /**
+     * The current module being archived. This field is updated every times that {@code FileCollector}
+     * enters in a new module directory.
+     */
+    @Nonnull
+    private Archive currentModule;
+
+    /**
+     * The module and target Java release currently being scanned. This field is updated every times that
+     * {@code FileCollector} enters in a new module directory or in a new target Java release for a given module.
+     */
+    @Nonnull
+    private Archive.FileSet currentFilesToArchive;
+
+    /**
+     * The current target Java release, or {@code null} if none.
+     */
+    @Nullable
+    private Runtime.Version currentTargetVersion;
+
+    /**
+     * Identification of the kinds of directories being traversed.
+     * The length of this list is the depth in the directory hierarchy.
+     * The last element identifies the type of the current directory.
+     */
+    private final Deque<DirectoryRole> directoryRoles;
+
+    /**
+     * Whether to check when a file is the {@code MANIFEST.MF} file.
+     * This is allowed only when scanning the content of a {@code META-INF} directory.
+     */
+    private boolean checkForManifest;
+
+    /**
+     * Creates a new file collector.
+     *
+     * @param mojo the <abbr>MOJO</abbr> from which to get the configuration
+     * @param context context (logger, configuration) in which the <abbr>JAR</abbr> file are created
+     * @param directory the base directory of the files to archive
+     */
+    FileCollector(AbstractJarMojo mojo, ToolExecutor context, Path directory, PathMatcherFactory matcherFactory) {
+        this.context = context;
+        detectMultiReleaseJar = mojo.detectMultiReleaseJar;
+        directoryRoles = new ArrayDeque<>();
+        fileMatcher = matcherFactory.createPathMatcher(directory, mojo.getIncludes(), mojo.getExcludes(), false);
+        directoryMatcher = matcherFactory.deriveDirectoryMatcher(fileMatcher);
+        addDirectories = !context.isReproducible()
+                && matcherFactory.isIncludesAll(fileMatcher)
+                && matcherFactory.isIncludesAll(directoryMatcher);
+        packageHierarchy = context.newArchive(null, null, directory);
+        moduleHierarchy = new LinkedHashMap<>();
+        resetToPackageHierarchy();
+    }
+
+    /**
+     * Resets this {@code FileCollector} to the state where a package hierarchy is presumed.
+     */
+    private void resetToPackageHierarchy() {
+        currentModule = packageHierarchy;
+        currentFilesToArchive = currentModule.baseRelease();
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a module.
+     * For an output generated by {@code javac} from a module source hierarchy,
+     * the directory name is guaranteed to be the module name.
+     *
+     * @param directory a {@code "<module>"} or {@code "META-INF/versions-modular/<module>"} directory
+     */
+    private void enterModuleDirectory(final Path directory) {
+        String moduleName = directory.getFileName().toString();
+        currentModule = moduleHierarchy.computeIfAbsent(
+                moduleName, (name) -> context.newArchive(name, currentTargetVersion, directory));
+        currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a target Java version.
+     * The {@code useDirectly} argument tells whether the content of this directory will be specified directly
+     * as the content to add in the <abbr>JAR</abbr> file. This argument should be {@code false} when there is
+     * another directory level (the module names) to process before to add content.
+     *
+     * @param directory a {@code "META-INF/versions/<n>"} or {@code "META-INF/versions-modular/<n>"} directory
+     * @param useDirectly whether the directory is {@code "META-INF/versions/<n>"}
+     * @return whether to skip the directory because of invalid version number
+     */
+    private boolean enterVersionDirectory(final Path directory, final boolean useDirectly) {
+        try {
+            currentTargetVersion = Runtime.Version.parse(directory.getFileName().toString());
+        } catch (IllegalArgumentException e) {
+            context.warnInvalidVersion(directory, e);
+            return true;
+        }
+        if (useDirectly) {
+            currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+        }
+        return false;
+    }
+
+    /**
+     * Determines if the given directory should be scanned for files to archive.
+     * This method may also update {@link #currentFilesToArchive} if it detects
+     * that we are entering in a new module or a new target Java release.
+     *
+     * @param directory the directory which will be traversed
+     * @param attributes the directory's basic attributes
+     */
+    @Override
+    @SuppressWarnings("checkstyle:MissingSwitchDefault")
+    public FileVisitResult preVisitDirectory(final Path directory, final BasicFileAttributes attributes)
+            throws IOException {
+        DirectoryRole role;
+        if (directoryRoles.isEmpty()) {
+            role = DirectoryRole.ROOT;
+        } else {
+            if (!directoryMatcher.matches(directory)) {
+                return FileVisitResult.SKIP_SUBTREE;
+            }
+            checkForManifest = false;
+            role = directoryRoles.getLast();
+            switch (role) {
+                case ROOT:
+                    /*
+                     * Entering in any subdirectory of `target/classes` (or other directory to archive).
+                     * We need to handle `META-INF` and modules in a special way, and archive the rest.
+                     */
+                    if (directory.endsWith(MetadataFiles.META_INF)) {
+                        role = DirectoryRole.META_INF;
+                        checkForManifest = true;
+                    } else if (Files.isRegularFile(directory.resolve(MODULE_DESCRIPTOR_FILE_NAME))) {
+                        role = DirectoryRole.NAMED_MODULE;
+                        enterModuleDirectory(directory);
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case META_INF:
+                    /*
+                     * Entering in a subdirectory of `META-INF` or `<module>/META-INF`. We will need to handle
+                     * `MANIFEST.MF`, `versions` and `versions-modular` in a special way, and archive the rest.
+                     */
+                    if (detectMultiReleaseJar && directory.endsWith(VERSIONS)) {
+                        role = DirectoryRole.VERSIONS;
+                    } else if (directory.endsWith(VERSIONS_MODULAR)) {
+                        if (!detectMultiReleaseJar) {
+                            // Used asked for no multi-release JAR.
+                            return FileVisitResult.SKIP_SUBTREE;
+                        }
+                        role = DirectoryRole.VERSIONS_MODULAR;
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case VERSIONS:
+                    /*
+                     * Entering in a `META-INF/versions/<n>/` directory for a specific target Java release.
+                     * May also be a `<module>/META-INF/versions/<n>/` directory, even if the latter is not

Review Comment:
   May --> Can



##########
src/main/java/org/apache/maven/plugins/jar/Archive.java:
##########
@@ -0,0 +1,692 @@
+/*
+ * 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.jar;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.TreeMap;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.Type;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.MojoException;
+
+/**
+ * Files or root directories to archive for a single module.
+ * A single instance of {@code Archive} may contain many directories for different target Java releases.
+ * Many instances of {@code Archive} may exist when archiving a multi-modules project.
+ */
+final class Archive {
+    /**
+     * Whether to repeat the {@code -C} option before each file.
+     * Doing so makes the command-line very verbose while the documentation of
+     * <a href="https://docs.oracle.com/en/java/javase/25/docs/specs/man/jar.html">The jar Command</a>
+     * gives the impression that this option can be provided only once.
+     * However, our tests suggest that the first file after the directory specified by the {@code -C} option
+     * must be relative to that directory and all files after the first one must be prefixed by the directory
+     * which was specified in the {@code -C} option. This behavior is not documented, but we couldn't get the
+     * {@code jar} tool to work otherwise (except by repeating {@code -C} before each file).
+     * Furthermore, it seems that the relativized file needs to be the shortest one,
+     * otherwise the {@code jar} tool rejects files after the first one with "names do not match".
+     * Which file is first depends on the unspecified directory-iteration order.
+     *
+     * <p>If this flag is {@code true}, the plugin repeats {@code -C} before each file.
+     * This flag should be set to {@code false} if a future version of the {@code jar}
+     * tool allows to specify {@code -C} only once.</p>
+     *
+     * <p><b>Historical note:</b> we also tried to relativize only the first file after {@code -C}
+     * and keep all subsequent files as absolute. It works, but because we have to repeat the directory
+     * in the file name, it saves only 3 or 4 characters per file compared to repeating {@code -C}.</p>
+     */
+    private static final boolean REPEAT_C = true;
+
+    /**
+     * Path to the <abbr>POM</abbr> file generated for this archive, or {@code null} if none.
+     * This is non-null only if module source hierarchy is used, in which case the dependencies
+     * declared in this file are the intersection of the project dependencies and the content of
+     * the {@code module-info.class} file.
+     */
+    @Nullable
+    Path pomFile;
+
+    /**
+     * The <var>JAR</var> file to create. May be an existing file,
+     * in which case the file creation may be skipped if the file is still up-to-date.
+     */
+    @Nonnull
+    final Path jarFile;
+
+    /**
+     * A helper class for checking whether an existing <abbr>JAR</abbr> file is still up-to-date.
+     * This is null if there is no existing JAR file, or if we determined that the file is outdated.
+     */
+    private TimestampCheck existingJAR;
+
+    /**
+     * Name of the module being archived when the project is using module hierarchy.
+     * This is {@code null} if the project is using package hierarchy, either because it is a classical
+     * class-path project or because it is a single module compiled without using the module hierarchy.
+     * When using module source hierarchy, {@code javac} guarantees that the module name in the output
+     * directory is the name of the parent directory of {@code module-info.class}.
+     */
+    @Nullable
+    final String moduleName;
+
+    /**
+     * Path to {@code META-INF/MANIFEST.MF}, or {@code null} if none.
+     * If non-null, this value will be given to the {@code --manifest} option.
+     * The use of this option is preferable to adding {@code MANIFEST.MF} as an ordinary file.
+     *
+     * @see #setManifest(Path, boolean)
+     * @see #mergeManifest(Path, Manifest)
+     */
+    @Nullable
+    private Path manifest;
+
+    /**
+     * The Maven generated {@code pom.xml} and {@code pom.properties} files, or {@code null} if none.
+     * This first item shall be the base directory where the files are located.
+     */
+    @Nullable
+    List<Path> mavenFiles;
+
+    /**
+     * Fully-qualified name of the main class, or {@code null} if none.
+     * This is the value to provide to the {@code --main-class} option.
+     */
+    private String mainClass;
+
+    /**
+     * Files or root directories to store in the <abbr>JAR</abbr> file for each target Java release
+     * other than the base release. Keys are the target Java release with {@code null} for the base
+     * release.
+     */
+    @Nonnull
+    private final NavigableMap<Runtime.Version, FileSet> filesetForRelease;
+
+    /**
+     * Files or root directories to archive for a single target Java release of a single module.
+     * The {@link Archive} enclosing shall contain at least one instance of {@code FileSet} for
+     * the base release, and an arbitrary amount of other instances for other target releases.
+     */
+    final class FileSet {
+        /**
+         * A comparator for sorting paths in a reproducible order.
+         * This comparator assumes that all paths are relative to the same base directory (this is not verified).
+         * Note: we do not use {@link Path#compareTo(Path)} because the Javadoc said that it is platform dependent.
+         */
+        private static final Comparator<Path> REPRODUCIBLE_ORDER = (p1, p2) -> {
+            final int c1 = p1.getNameCount();
+            final int c2 = p2.getNameCount();
+            final int c = Math.min(c1, c2);
+            for (int i = 0; i < c; i++) {
+                String n1 = p1.getName(i).toString();
+                String n2 = p2.getName(i).toString();
+                int r = n1.compareTo(n2); // Case-sensitive comparison on all platforms.
+                if (r != 0) {
+                    return r;
+                }
+            }
+            return c1 - c2;
+        };
+
+        /**
+         * The root directory of all files or directories to archive.
+         * This is the value to pass to the {@code -C} tool option.
+         */
+        @Nonnull
+        final Path directory;
+
+        /**
+         * The files or directories to include in the <var>JAR</var> file.
+         * May be absolute paths or paths relative to {@link #directory}.
+         */
+        @Nonnull
+        final List<Path> files;
+
+        /**
+         * Creates an initially empty set of files or directories for a specific target Java release.
+         *
+         * @param directory the base directory of the files or directories to archive
+         */
+        private FileSet(Path directory) {
+            this.directory = directory;
+            this.files = new ArrayList<>();
+        }
+
+        /**
+         * 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.
+         * The caller should use that common directory for logging a warning message.
+         *
+         * @param base base directory found by previous invocations of this method, or {@code null} if none
+         * @return common directory of discarded files
+         */
+        private Path discardAllFiles(Path base) {
+            for (Path file : files) {
+                file = directory.resolve(file);
+                if (base == null) {
+                    base = file.getParent();
+                } else {
+                    while (!file.startsWith(base)) {
+                        base = base.getParent();
+                        if (base == null) {
+                            break;
+                        }
+                    }
+                }
+            }
+            files.clear();
+            return base;
+        }
+
+        /**
+         * Adds the given path to the list of files or directories to archive.
+         * This method may store a relative path instead of the absolute path.
+         *
+         * @param item a file or directory to archive
+         * @param attributes the file's basic attributes
+         * @param isDirectory whether the file is a directory
+         * @throws IllegalArgumentException if the given path cannot be made relative to the base directory
+         */
+        void add(Path item, BasicFileAttributes attributes, boolean isDirectory) {
+            TimestampCheck tc = existingJAR;
+            if (tc != null && tc.isUpdated(item, attributes, isDirectory)) {
+                existingJAR = null; // Signal that the existing file is outdated.
+            }
+            item = directory.relativize(item);
+            if (item.getNameCount() <= 1 && item.toString().isEmpty()) {
+                /*
+                 * The item is the `-C` directory itself (e.g. a `META-INF/versions/<n>` directory
+                 * added as a whole). An empty file argument is invalid for the `jar` tool
+                 * (some implementations reject it, others silently misbehave),
+                 * so archive the whole directory content with ".".
+                 */
+                item = Path.of(".");
+            }
+            files.add(item);
+        }
+
+        /**
+         * Adds to the given list the arguments to provide to the "jar" tool for this version.
+         * Elements added to the list shall be instances of {@link String} or {@link Path}.
+         *
+         * @param addTo the list where to add the arguments as {@link String} or {@link Path} instances
+         * @param version the target Java release, or {@code null} for the base version of the <abbr>JAR</abbr> file
+         */
+        private void arguments(List<Object> addTo, Runtime.Version version) {
+            if (!files.isEmpty()) {
+                if (version != null) {
+                    addTo.add("--release");
+                    addTo.add(version);
+                }
+                if (isReproducible) {
+                    files.sort(REPRODUCIBLE_ORDER);
+                }
+                if (REPEAT_C) {
+                    for (Path file : files) {
+                        addTo.add("-C");
+                        addTo.add(directory);
+                        addTo.add(file);
+                    }
+                } else {
+                    addTo.add("-C");
+                    addTo.add(directory);
+                    addTo.addAll(files);
+                }
+            }
+        }
+
+        /**
+         * {@return a string representation for debugging purposes}
+         */
+        @Override
+        public String toString() {
+            return getClass().getSimpleName() + '[' + directory.getFileName() + ": " + files.size() + " files]";
+        }
+    }
+
+    /**
+     * Whether reproducible build was requested.
+     */
+    private final boolean isReproducible;
+
+    /**
+     * Creates an initially empty set of files or directories.
+     *
+     * @param jarFile path to the <abbr>JAR</abbr> file to create
+     * @param moduleName the module name if using module hierarchy, or {@code null} if using package hierarchy
+     * @param version the target Java release, or {@code null} for the base version
+     * @param directory the directory of the classes targeting the base Java release
+     * @param forceCreation whether to force a new <abbr>JAR</abbr> file even if the content seems unchanged
+     * @param isReproducible whether reproducible build was requested
+     * @param logger where to send a warning if an error occurred while checking an existing <abbr>JAR</abbr> file
+     */
+    @SuppressWarnings("checkstyle:NeedBraces")
+    Archive(
+            final Path jarFile,
+            final String moduleName,
+            final Runtime.Version version,
+            final Path directory,
+            final boolean forceCreation,
+            final boolean isReproducible,
+            final Log logger) {
+        this.jarFile = jarFile;
+        this.moduleName = moduleName;
+        this.isReproducible = isReproducible;
+        filesetForRelease = new TreeMap<>((v1, v2) -> {
+            if (v1 == v2) return 0;
+            if (v1 == null) return -1;
+            if (v2 == null) return +1;
+            return v1.compareTo(v2);
+        });
+        filesetForRelease.put(version, new FileSet(directory));
+        if (!forceCreation && Files.isRegularFile(jarFile)) {
+            try {
+                existingJAR = new TimestampCheck(jarFile, directory, logger);
+            } catch (IOException e) {
+                // Ignore, we will regenerate the JAR file.
+                logger.warn(e);
+            }
+        }
+    }
+
+    /**
+     * {@return the files or directories to store in the <abbr>JAR</abbr> file for targeting the base Java release}
+     *
+     * @throws NoSuchElementException should not happen unless {@link #prune(boolean)} has been invoked
+     */
+    FileSet baseRelease() {
+        Map.Entry<Runtime.Version, FileSet> entry = filesetForRelease.firstEntry();
+        String message = null;
+        if (entry != null) {
+            Runtime.Version version = entry.getKey();
+            if (version == null) {
+                return entry.getValue();
+            }
+            message = "Expected base version but found version " + version;
+        }
+        throw new NoSuchElementException(message);
+    }
+
+    /**
+     * Returns the {@code module-info.class} files. Conceptually, there is at most once such file per module.
+     * However, more than one file may exist if additional files are provided for additional Java releases.
+     * This method returns only the files that exist.
+     *
+     * @return all {@code module-info.class} files found for all target Java releases
+     */
+    public List<Path> moduleInfoFiles() {
+        var files = new ArrayList<Path>();
+        filesetForRelease.values().forEach((release) -> {
+            Path file = release.directory.resolve(FileCollector.MODULE_DESCRIPTOR_FILE_NAME);
+            if (Files.isRegularFile(file)) {
+                files.add(file);
+            }
+        });
+        return files;
+    }
+
+    /**
+     * Discards all files in this archive, normally because those files are not in any module.
+     * This method returns a common parent directory for all the files that were discarded.
+     * The caller should use that common directory for logging a warning message.
+     *
+     * @return common directory of discarded files, or {@code null} if none
+     */
+    Path discardAllFiles() {
+        Path base = null;
+        for (FileSet release : filesetForRelease.values()) {
+            base = release.discardAllFiles(base);
+        }
+        filesetForRelease.clear();
+        return base;
+    }
+
+    /**
+     * Removes all empty file sets 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}, then this method ensures that at least one file set
+     * remains even if that file set is empty.
+     *
+     * @param skipIfEmpty value of {@link AbstractJarMojo#skipIfEmpty}
+     */
+    public void prune(final boolean skipIfEmpty) {
+        FileSet keep = (skipIfEmpty || isEmpty())
+                ? null
+                : filesetForRelease.firstEntry().getValue();
+        filesetForRelease.values().removeIf((fs) -> fs.files.isEmpty());
+        Iterator<Map.Entry<Runtime.Version, FileSet>> it =
+                filesetForRelease.entrySet().iterator();
+        if (it.hasNext()) {
+            Map.Entry<Runtime.Version, FileSet> first = it.next();
+            if (first.getKey() == null) {
+                return; // Already contains an entry for the base version, nothing to do.
+            }
+            keep = first.getValue();
+            it.remove();
+        }
+        if (keep != null) {
+            filesetForRelease.put(null, keep);
+        }
+    }
+
+    /**
+     * {@return whether this archive has nothing to archive}
+     * Note that this method may return {@code false} even when there is zero file to archive.
+     * It may happen if {@link AbstractJarMojo#skipIfEmpty} is {@code false}. In such case, the
+     * "empty" <abbr>JAR</abbr> file will still contain at {@code META-INF/MANIFEST.MF} file.
+     *
+     * <h4>Prerequisites</h4>
+     * The {@link #prune(boolean)} method should be invoked before this method for accurate result.
+     */
+    public boolean isEmpty() {
+        return filesetForRelease.isEmpty();
+    }
+
+    /**
+     * Checks whether the <abbr>JAR</abbr> file already exists and can be reused.
+     * This method verifies that the <abbr>JAR</abbr> file contains all the files to archive,
+     * contains no extra file, and no file to archive is newer than the <abbr>JAR</abbr> file.
+     *
+     * <p>This method can be invoked only once.
+     * If invoked more often, it returns {@code false} on all subsequent invocations.</p>
+     *
+     * @return whether the <abbr>JAR</abbr> file already exists and can be reused
+     */
+    public boolean isUpToDateJAR() {
+        final TimestampCheck tc = existingJAR;
+        if (tc == null) {
+            return false;
+        }
+        existingJAR = null; // Let GC do its job.
+        return tc.isUpToDateJAR(filesetForRelease.values());
+    }
+
+    /**
+     * Returns an initially empty set of files or directories for the specified target Java release.
+     *
+     * @param directory the base directory of the files to archive
+     * @param version the target Java release, or {@code null} for the base version
+     * @return container where to declare files and directories to archive
+     */
+    FileSet newTargetRelease(Path directory, Runtime.Version version) {
+        return filesetForRelease.computeIfAbsent(version, (key) -> new FileSet(directory));
+    }
+
+    /**
+     * Sets the {@code --main-class} option to the value of the {@code Main-Class} entry of the given manifest.
+     * As an extension, this method accepts the {@code module/classname} syntax (a syntax already used in some
+     * Java tools). If a module is specified, the main class is kept only if the module match. The intent is to
+     * allow users to specify on which module the main class applies when they use plugin configuration.
+     *
+     * <p>This method may modify the {@code content} manifest. Caller shall ensure that the given manifest
+     * is not a shared instance. This method returns whether a change has actually been done.</p>
+     *
+     * @param content combination of existing {@code MANIFEST.MF} and manifest inferred from configuration, or null
+     * @return whether the given manifest has been modified by this method
+     */
+    boolean setMainClass(Manifest content) {
+        if (content == null || mainClass != null) {
+            return false;
+        }
+        // We need to remove the attribute, otherwise it will conflict with `--main-class`.
+        mainClass = (String) content.getMainAttributes().remove(Attributes.Name.MAIN_CLASS);
+        if (mainClass != null) {
+            int s = mainClass.indexOf('/');
+            if (s >= 0) {
+                if (mainClass.substring(0, s).strip().equals(moduleName)) {
+                    mainClass = mainClass.substring(s + 1).strip();
+                } else {
+                    mainClass = null; // Main class is defined for another module.
+                }
+            }
+        }
+        return mainClass != null;
+    }
+
+    /**
+     * Sets the {@code --manifest} option to the given value if that option was not already set.
+     *
+     * @param file path to the manifest file
+     * @param force whether to set the manifest even if already set
+     * @return whether the manifest has been set
+     */
+    boolean setManifest(Path file, boolean force) {
+        if (manifest == null || force) {
+            manifest = file;
+            return true;
+        }
+        return false;
+    }
+
+    /**
+     * Merges the manifest of this module with the manifest specified in plugin configuration.
+     * If both {@code file} and {@code content} are non-null, then {@code content} must be the
+     * result of reading {@code file}.
+     *
+     * <p>This method never modifies the given {@code content} object. If manifest are merged,
+     * a new {@link Manifest} instance is created. Therefore, caller can check whether this
+     * method returned a new instance as a way to recognize that a merge occurred.</p>
+     *
+     * <p>If a merge occurs, the content specified to {@link #setManifest(Path)} has precedence.
+     * It should be the {@code target/classes/META-INF/MANIFEST.MF} file (or modular equivalent).</p>
+     *
+     * @param  file     an additional manifest file, or {@code null}
+     * @param  content  the content of {@code file}, or a standalone manifest produced at runtime
+     * @return the merged manifest as a new instance if some changes were necessary
+     * @throws IOException if an error occurred while reading a manifest file
+     */
+    Manifest mergeManifest(Path file, Manifest content) throws IOException {
+        if (manifest == null) {
+            manifest = file;
+        } else if (file != null && Files.isSameFile(file, manifest)) {
+            // Nothing to merge because of the constraint that `content` must be the content of `file`.
+        } else {
+            try (InputStream in = Files.newInputStream(manifest)) {
+                // No need to wrap in `BufferedInputStream`.
+                if (content != null) {
+                    content = new Manifest(content);
+                    content.read(in);
+                } else {
+                    content = new Manifest(in);
+                }
+            }
+        }
+        return content;
+    }
+
+    /**
+     * Adds to the given list the arguments to provide to the "jar" tool for each version.
+     * Elements added to the list shall be instances of {@link String} or {@link Path}.
+     * Callers should have added the following options (if applicable) before to invoke this method:
+     *
+     * <ul>
+     *   <li>{@code --create}</li>
+     *   <li>{@code --no-compress}</li>
+     *   <li>{@code --date} followed by the output time stamp</li>
+     *   <li>{@code --module-version} followed by module version</li>
+     *   <li>{@code --hash-modules} followed by patters of module names</li>
+     *   <li>{@code --module-path} followed by module path</li>
+     * </ul>
+     *
+     * This method adds the following options:
+     *
+     * <ul>
+     *   <li>{@code --file} followed by the path to the <abbr>JAR</abbr> file</li>
+     *   <li>{@code --manifest} followed by path to the manifest file</li>
+     *   <li>{@code --main-class} followed by fully qualified name class</li>
+     *   <li>{@code --release} followed by Java target release</li>
+     *   <li>{@code -C} followed by directory</li>
+     *   <li>files or directories to archive</li>
+     * </ul>
+     *
+     * @param addTo the list where to add the arguments as {@link String} or {@link Path} instances
+     */
+    void arguments(final List<Object> addTo) {
+        addTo.add("--file");
+        addTo.add(jarFile);
+        if (manifest != null) {
+            addTo.add("--manifest");
+            addTo.add(manifest);
+        }
+        if (mainClass != null) {
+            addTo.add("--main-class");
+            addTo.add(mainClass);
+        }
+        if (mavenFiles != null) {
+            addTo.add("-C");
+            addTo.addAll(mavenFiles);
+        }
+        for (Map.Entry<Runtime.Version, FileSet> entry : filesetForRelease.entrySet()) {
+            entry.getValue().arguments(addTo, entry.getKey());
+        }
+    }
+
+    /**
+     * Adds to the given list the arguments to provide to the "jar" tool for validating the <abbr>JAR</abbr> file.
+     * The file is validated only if the validation was not done implicitly at <abbr>JAR</abbr> creation time.
+     * This is the case if no {@code --release} option was used.
+     * This method adds the following options:
+     *
+     * <ul>
+     *   <li>{@code --validate} operation mode</li>
+     *   <li>{@code --file} followed by the path to the <abbr>JAR</abbr> file</li>
+     * </ul>
+     *
+     * @param  addTo the list where to add the arguments as {@link String} or {@link Path} instances

Review Comment:
   as above



##########
src/main/java/org/apache/maven/plugins/jar/DirectoryRole.java:
##########
@@ -0,0 +1,73 @@
+/*
+ * 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.jar;
+
+/**
+ * Directories that the archiver needs to handle in a special way.
+ */
+enum DirectoryRole {
+    /**
+     * The root directory. This is usually {@code "target/classes"}.
+     * The next locations can be {@link #META_INF}, {@link #NAMED_MODULE} or {@link #RESOURCES}.
+     */
+    ROOT,
+
+    /**
+     * The {@code "META-INF"} or {@code "<module>/META-INF"} directory.
+     * This is part of the <abbr>JAR</abbr> specification.
+     * The next locations can be {@link #VERSIONS} or {@link #VERSIONS_MODULAR}.
+     */
+    META_INF,
+
+    /**
+     * The {@code "META-INF/versions"} or {@code "<module>/META-INF/versions"} directory.
+     * This is part of the <abbr>JAR</abbr> specification, except the {@code <module>} prefix.
+     * The sub-directories are named according Java releases such as "21".
+     * The next location can only be {@link #RESOURCES}.
+     */
+    VERSIONS,
+
+    /**
+     * The Maven-specific {@code "META-INF/versions-modular"} directory.
+     * Note that {@code "<module>/META-INF/versions-modular"} is not forbidden, but does not make sense.
+     * The sub-directories are named according Java releases such as "21".
+     * The next location can only be {@link #MODULES}.
+     */
+    VERSIONS_MODULAR,
+
+    /**
+     * The Maven-specific {@code "META-INF/versions-modular"} directory.
+     * All sub-directories shall have the name of a Java module.
+     * The next location can only be {@link #NAMED_MODULE}.
+     */
+    MODULES,
+
+    /**
+     * The root of a single Java module in a module hierarchy.
+     * The name of this directory is the Java module name.
+     * The next location can only be {@link #RESOURCES}.
+     */
+    NAMED_MODULE,
+
+    /**
+     * The classes or other types of resources to include in a single archive.
+     * May also be other files in the {@code META-INF} directory.

Review Comment:
   May --> Can



##########
src/main/java/org/apache/maven/plugins/jar/FileCollector.java:
##########
@@ -0,0 +1,496 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.PathMatcher;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayDeque;
+import java.util.Deque;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.services.PathMatcherFactory;
+
+/**
+ * Dispatch the files in the output directory into the <abbr>JAR</abbr> files to create.
+ * Instead of just archiving as-is the content of the output directory, this class separates
+ * the following subdirectories to the options listed below:
+ *
+ * <ul>
+ *   <li>The {@code META-INF/MANIFEST.MF} file will be given to the {@code --manifest} option.</li>
+ *   <li>Files in the following directories will be given to the {@code --release} option:
+ *     <ul>
+ *       <li>{@code META-INF/versions/}</li>
+ *       <li>{@code META-INF/versions-modular/<module>/}</li>
+ *       <li>{@code <module>/META-INF/versions/}</li>
+ *     </ul>
+ *   </li>
+ * </ul>
+ *
+ * The reason for using the options is that they allow the {@code jar} tool to perform additional verifications.
+ * For example, when using the {@code --release} option, {@code jar} verifies the <abbr>API</abbr> compatibility.
+ */
+final class FileCollector extends SimpleFileVisitor<Path> {
+    /**
+     * The file to check for deciding whether the <abbr>JAR</abbr> is modular.
+     */
+    static final String MODULE_DESCRIPTOR_FILE_NAME = "module-info.class";
+
+    /**
+     * The {@value} directory.
+     * This is part of <abbr>JAR</abbr> file specification.
+     */
+    private static final String VERSIONS = "versions";
+
+    /**
+     * The {@value} directory.
+     * This is Maven-specific.
+     */
+    private static final String VERSIONS_MODULAR = "versions-modular";
+
+    /**
+     * Context (logger, configuration) in which the <abbr>JAR</abbr> file are created.
+     */
+    private final ToolExecutor context;
+
+    /**
+     * Whether to detect multi-release <abbr>JAR</abbr> files.
+     * The default value is {@code true}.
+     *
+     * @see AbstractJarMojo#detectMultiReleaseJar
+     */
+    private final boolean detectMultiReleaseJar;
+
+    /**
+     * Combination of includes and excludes path matcher applied on files.
+     */
+    @Nonnull
+    private final PathMatcher fileMatcher;
+
+    /**
+     * Combination of includes and excludes path matcher applied on directories.
+     */
+    @Nonnull
+    private final PathMatcher directoryMatcher;
+
+    /**
+     * Whether the matchers accept all files and there is no need to sort the files.
+     * In such case, we can declare whole directories to the {@code jar} tool instead
+     * of scanning the directory tree ourselves.
+     */
+    private final boolean addDirectories;
+
+    /**
+     * Files found in the output directory when package hierarchy is used.
+     * At most one of {@code packageHierarchy} and {@link #moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Archive packageHierarchy;
+
+    /**
+     * Files found in the output directory when module hierarchy is used. Keys are module names.
+     * At most one of {@link #packageHierarchy} and {@code moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Map<String, Archive> moduleHierarchy;
+
+    /**
+     * The current module being archived. This field is updated every times that {@code FileCollector}
+     * enters in a new module directory.
+     */
+    @Nonnull
+    private Archive currentModule;
+
+    /**
+     * The module and target Java release currently being scanned. This field is updated every times that
+     * {@code FileCollector} enters in a new module directory or in a new target Java release for a given module.
+     */
+    @Nonnull
+    private Archive.FileSet currentFilesToArchive;
+
+    /**
+     * The current target Java release, or {@code null} if none.
+     */
+    @Nullable
+    private Runtime.Version currentTargetVersion;
+
+    /**
+     * Identification of the kinds of directories being traversed.
+     * The length of this list is the depth in the directory hierarchy.
+     * The last element identifies the type of the current directory.
+     */
+    private final Deque<DirectoryRole> directoryRoles;
+
+    /**
+     * Whether to check when a file is the {@code MANIFEST.MF} file.
+     * This is allowed only when scanning the content of a {@code META-INF} directory.
+     */
+    private boolean checkForManifest;
+
+    /**
+     * Creates a new file collector.
+     *
+     * @param mojo the <abbr>MOJO</abbr> from which to get the configuration
+     * @param context context (logger, configuration) in which the <abbr>JAR</abbr> file are created
+     * @param directory the base directory of the files to archive
+     */
+    FileCollector(AbstractJarMojo mojo, ToolExecutor context, Path directory, PathMatcherFactory matcherFactory) {
+        this.context = context;
+        detectMultiReleaseJar = mojo.detectMultiReleaseJar;
+        directoryRoles = new ArrayDeque<>();
+        fileMatcher = matcherFactory.createPathMatcher(directory, mojo.getIncludes(), mojo.getExcludes(), false);
+        directoryMatcher = matcherFactory.deriveDirectoryMatcher(fileMatcher);
+        addDirectories = !context.isReproducible()
+                && matcherFactory.isIncludesAll(fileMatcher)
+                && matcherFactory.isIncludesAll(directoryMatcher);
+        packageHierarchy = context.newArchive(null, null, directory);
+        moduleHierarchy = new LinkedHashMap<>();
+        resetToPackageHierarchy();
+    }
+
+    /**
+     * Resets this {@code FileCollector} to the state where a package hierarchy is presumed.
+     */
+    private void resetToPackageHierarchy() {
+        currentModule = packageHierarchy;
+        currentFilesToArchive = currentModule.baseRelease();
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a module.
+     * For an output generated by {@code javac} from a module source hierarchy,
+     * the directory name is guaranteed to be the module name.
+     *
+     * @param directory a {@code "<module>"} or {@code "META-INF/versions-modular/<module>"} directory
+     */
+    private void enterModuleDirectory(final Path directory) {
+        String moduleName = directory.getFileName().toString();
+        currentModule = moduleHierarchy.computeIfAbsent(
+                moduleName, (name) -> context.newArchive(name, currentTargetVersion, directory));
+        currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a target Java version.
+     * The {@code useDirectly} argument tells whether the content of this directory will be specified directly
+     * as the content to add in the <abbr>JAR</abbr> file. This argument should be {@code false} when there is
+     * another directory level (the module names) to process before to add content.
+     *
+     * @param directory a {@code "META-INF/versions/<n>"} or {@code "META-INF/versions-modular/<n>"} directory
+     * @param useDirectly whether the directory is {@code "META-INF/versions/<n>"}
+     * @return whether to skip the directory because of invalid version number
+     */
+    private boolean enterVersionDirectory(final Path directory, final boolean useDirectly) {
+        try {
+            currentTargetVersion = Runtime.Version.parse(directory.getFileName().toString());
+        } catch (IllegalArgumentException e) {
+            context.warnInvalidVersion(directory, e);
+            return true;
+        }
+        if (useDirectly) {
+            currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+        }
+        return false;
+    }
+
+    /**
+     * Determines if the given directory should be scanned for files to archive.
+     * This method may also update {@link #currentFilesToArchive} if it detects
+     * that we are entering in a new module or a new target Java release.
+     *
+     * @param directory the directory which will be traversed
+     * @param attributes the directory's basic attributes
+     */
+    @Override
+    @SuppressWarnings("checkstyle:MissingSwitchDefault")
+    public FileVisitResult preVisitDirectory(final Path directory, final BasicFileAttributes attributes)
+            throws IOException {
+        DirectoryRole role;
+        if (directoryRoles.isEmpty()) {
+            role = DirectoryRole.ROOT;
+        } else {
+            if (!directoryMatcher.matches(directory)) {
+                return FileVisitResult.SKIP_SUBTREE;
+            }
+            checkForManifest = false;
+            role = directoryRoles.getLast();
+            switch (role) {
+                case ROOT:
+                    /*
+                     * Entering in any subdirectory of `target/classes` (or other directory to archive).

Review Comment:
   I'm not sure what "Entering in" means here and below. Entering is probably the wrong word.



##########
src/main/java/org/apache/maven/plugins/jar/FileCollector.java:
##########
@@ -0,0 +1,496 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.PathMatcher;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayDeque;
+import java.util.Deque;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.services.PathMatcherFactory;
+
+/**
+ * Dispatch the files in the output directory into the <abbr>JAR</abbr> files to create.
+ * Instead of just archiving as-is the content of the output directory, this class separates
+ * the following subdirectories to the options listed below:
+ *
+ * <ul>
+ *   <li>The {@code META-INF/MANIFEST.MF} file will be given to the {@code --manifest} option.</li>
+ *   <li>Files in the following directories will be given to the {@code --release} option:
+ *     <ul>
+ *       <li>{@code META-INF/versions/}</li>
+ *       <li>{@code META-INF/versions-modular/<module>/}</li>
+ *       <li>{@code <module>/META-INF/versions/}</li>
+ *     </ul>
+ *   </li>
+ * </ul>
+ *
+ * The reason for using the options is that they allow the {@code jar} tool to perform additional verifications.
+ * For example, when using the {@code --release} option, {@code jar} verifies the <abbr>API</abbr> compatibility.
+ */
+final class FileCollector extends SimpleFileVisitor<Path> {
+    /**
+     * The file to check for deciding whether the <abbr>JAR</abbr> is modular.
+     */
+    static final String MODULE_DESCRIPTOR_FILE_NAME = "module-info.class";
+
+    /**
+     * The {@value} directory.
+     * This is part of <abbr>JAR</abbr> file specification.
+     */
+    private static final String VERSIONS = "versions";
+
+    /**
+     * The {@value} directory.
+     * This is Maven-specific.
+     */
+    private static final String VERSIONS_MODULAR = "versions-modular";
+
+    /**
+     * Context (logger, configuration) in which the <abbr>JAR</abbr> file are created.
+     */
+    private final ToolExecutor context;
+
+    /**
+     * Whether to detect multi-release <abbr>JAR</abbr> files.
+     * The default value is {@code true}.
+     *
+     * @see AbstractJarMojo#detectMultiReleaseJar
+     */
+    private final boolean detectMultiReleaseJar;
+
+    /**
+     * Combination of includes and excludes path matcher applied on files.
+     */
+    @Nonnull
+    private final PathMatcher fileMatcher;
+
+    /**
+     * Combination of includes and excludes path matcher applied on directories.
+     */
+    @Nonnull
+    private final PathMatcher directoryMatcher;
+
+    /**
+     * Whether the matchers accept all files and there is no need to sort the files.
+     * In such case, we can declare whole directories to the {@code jar} tool instead
+     * of scanning the directory tree ourselves.
+     */
+    private final boolean addDirectories;
+
+    /**
+     * Files found in the output directory when package hierarchy is used.
+     * At most one of {@code packageHierarchy} and {@link #moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Archive packageHierarchy;
+
+    /**
+     * Files found in the output directory when module hierarchy is used. Keys are module names.
+     * At most one of {@link #packageHierarchy} and {@code moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Map<String, Archive> moduleHierarchy;
+
+    /**
+     * The current module being archived. This field is updated every times that {@code FileCollector}
+     * enters in a new module directory.
+     */
+    @Nonnull
+    private Archive currentModule;
+
+    /**
+     * The module and target Java release currently being scanned. This field is updated every times that
+     * {@code FileCollector} enters in a new module directory or in a new target Java release for a given module.
+     */
+    @Nonnull
+    private Archive.FileSet currentFilesToArchive;
+
+    /**
+     * The current target Java release, or {@code null} if none.
+     */
+    @Nullable
+    private Runtime.Version currentTargetVersion;
+
+    /**
+     * Identification of the kinds of directories being traversed.
+     * The length of this list is the depth in the directory hierarchy.
+     * The last element identifies the type of the current directory.
+     */
+    private final Deque<DirectoryRole> directoryRoles;
+
+    /**
+     * Whether to check when a file is the {@code MANIFEST.MF} file.
+     * This is allowed only when scanning the content of a {@code META-INF} directory.
+     */
+    private boolean checkForManifest;
+
+    /**
+     * Creates a new file collector.
+     *
+     * @param mojo the <abbr>MOJO</abbr> from which to get the configuration
+     * @param context context (logger, configuration) in which the <abbr>JAR</abbr> file are created
+     * @param directory the base directory of the files to archive
+     */
+    FileCollector(AbstractJarMojo mojo, ToolExecutor context, Path directory, PathMatcherFactory matcherFactory) {
+        this.context = context;
+        detectMultiReleaseJar = mojo.detectMultiReleaseJar;
+        directoryRoles = new ArrayDeque<>();
+        fileMatcher = matcherFactory.createPathMatcher(directory, mojo.getIncludes(), mojo.getExcludes(), false);
+        directoryMatcher = matcherFactory.deriveDirectoryMatcher(fileMatcher);
+        addDirectories = !context.isReproducible()
+                && matcherFactory.isIncludesAll(fileMatcher)
+                && matcherFactory.isIncludesAll(directoryMatcher);
+        packageHierarchy = context.newArchive(null, null, directory);
+        moduleHierarchy = new LinkedHashMap<>();
+        resetToPackageHierarchy();
+    }
+
+    /**
+     * Resets this {@code FileCollector} to the state where a package hierarchy is presumed.
+     */
+    private void resetToPackageHierarchy() {
+        currentModule = packageHierarchy;
+        currentFilesToArchive = currentModule.baseRelease();
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a module.
+     * For an output generated by {@code javac} from a module source hierarchy,
+     * the directory name is guaranteed to be the module name.
+     *
+     * @param directory a {@code "<module>"} or {@code "META-INF/versions-modular/<module>"} directory
+     */
+    private void enterModuleDirectory(final Path directory) {
+        String moduleName = directory.getFileName().toString();
+        currentModule = moduleHierarchy.computeIfAbsent(
+                moduleName, (name) -> context.newArchive(name, currentTargetVersion, directory));
+        currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a target Java version.
+     * The {@code useDirectly} argument tells whether the content of this directory will be specified directly
+     * as the content to add in the <abbr>JAR</abbr> file. This argument should be {@code false} when there is
+     * another directory level (the module names) to process before to add content.
+     *
+     * @param directory a {@code "META-INF/versions/<n>"} or {@code "META-INF/versions-modular/<n>"} directory
+     * @param useDirectly whether the directory is {@code "META-INF/versions/<n>"}
+     * @return whether to skip the directory because of invalid version number
+     */
+    private boolean enterVersionDirectory(final Path directory, final boolean useDirectly) {
+        try {
+            currentTargetVersion = Runtime.Version.parse(directory.getFileName().toString());
+        } catch (IllegalArgumentException e) {
+            context.warnInvalidVersion(directory, e);
+            return true;
+        }
+        if (useDirectly) {
+            currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+        }
+        return false;
+    }
+
+    /**
+     * Determines if the given directory should be scanned for files to archive.
+     * This method may also update {@link #currentFilesToArchive} if it detects
+     * that we are entering in a new module or a new target Java release.
+     *
+     * @param directory the directory which will be traversed
+     * @param attributes the directory's basic attributes
+     */
+    @Override
+    @SuppressWarnings("checkstyle:MissingSwitchDefault")
+    public FileVisitResult preVisitDirectory(final Path directory, final BasicFileAttributes attributes)
+            throws IOException {
+        DirectoryRole role;
+        if (directoryRoles.isEmpty()) {
+            role = DirectoryRole.ROOT;
+        } else {
+            if (!directoryMatcher.matches(directory)) {
+                return FileVisitResult.SKIP_SUBTREE;
+            }
+            checkForManifest = false;
+            role = directoryRoles.getLast();
+            switch (role) {
+                case ROOT:
+                    /*
+                     * Entering in any subdirectory of `target/classes` (or other directory to archive).
+                     * We need to handle `META-INF` and modules in a special way, and archive the rest.
+                     */
+                    if (directory.endsWith(MetadataFiles.META_INF)) {
+                        role = DirectoryRole.META_INF;
+                        checkForManifest = true;
+                    } else if (Files.isRegularFile(directory.resolve(MODULE_DESCRIPTOR_FILE_NAME))) {
+                        role = DirectoryRole.NAMED_MODULE;
+                        enterModuleDirectory(directory);
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case META_INF:
+                    /*
+                     * Entering in a subdirectory of `META-INF` or `<module>/META-INF`. We will need to handle
+                     * `MANIFEST.MF`, `versions` and `versions-modular` in a special way, and archive the rest.
+                     */
+                    if (detectMultiReleaseJar && directory.endsWith(VERSIONS)) {
+                        role = DirectoryRole.VERSIONS;
+                    } else if (directory.endsWith(VERSIONS_MODULAR)) {
+                        if (!detectMultiReleaseJar) {
+                            // Used asked for no multi-release JAR.
+                            return FileVisitResult.SKIP_SUBTREE;
+                        }
+                        role = DirectoryRole.VERSIONS_MODULAR;
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case VERSIONS:
+                    /*
+                     * Entering in a `META-INF/versions/<n>/` directory for a specific target Java release.
+                     * May also be a `<module>/META-INF/versions/<n>/` directory, even if the latter is not
+                     * the layout generated by Maven Compiler Plugin.
+                     */
+                    if (enterVersionDirectory(directory, true)) {
+                        // An error occurred while parsing the version number.
+                        return FileVisitResult.SKIP_SUBTREE;
+                    }
+                    role = DirectoryRole.RESOURCES;
+                    break;
+
+                case VERSIONS_MODULAR:
+                    /*
+                     * Entering in a `META-INF/versions-modular/<n>/` directory for a specific target Java release.
+                     * That directory contains all modules for the version.
+                     */
+                    resetToPackageHierarchy(); // No module in particular yet.
+                    if (enterVersionDirectory(directory, false)) {
+                        // An error occurred while parsing the version number.
+                        return FileVisitResult.SKIP_SUBTREE;
+                    }
+                    role = DirectoryRole.MODULES;
+                    break;
+
+                case MODULES:
+                    /*
+                     * Entering in a `META-INF/versions-modular/<n>/<module>` directory.
+                     */
+                    enterModuleDirectory(directory);
+                    role = DirectoryRole.NAMED_MODULE;
+                    break;
+
+                case NAMED_MODULE:
+                    /*
+                     * Entering in a `<module>` or `META-INF/versions-modular/<n>/<module>` subdirectory.
+                     * A module could have its own `META-INF` subdirectory, so we need to check again.
+                     */
+                    if (directory.endsWith(MetadataFiles.META_INF)) {
+                        role = DirectoryRole.META_INF;
+                        checkForManifest = true;
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+            }
+        }
+        /*
+         * Do not move this condition inside the `switch` block because `role` may have been modified.
+         * The `role` value is now the role of `directory`, not anymore the role of parent directory.
+         */
+        if (addDirectories && role == DirectoryRole.RESOURCES) {
+            currentFilesToArchive.add(directory, attributes, true);
+            /*
+             * Since we are skipping the whole directory, `postVisitDirectory(…)` will not be invoked.
+             * We must reset `currentFilesToArchive` and `currentTargetVersion` by an explicit call.
+             * This is important mostly after we added a whole `META-INF/versions/<n>` directory,
+             * otherwise base files visited afterwards (directory iteration order is unspecified)
+             * would be added to this version's file set instead of the base release.
+             */
+            resetToParentDirectoryState();
+            return FileVisitResult.SKIP_SUBTREE;
+        } else {
+            directoryRoles.addLast(role);
+            return FileVisitResult.CONTINUE;
+        }
+    }
+
+    /**
+     * Updates the {@code FileCollector} state after we finished to scan the content of a directory.

Review Comment:
   to scan the content --> scaninng the contents



##########
src/main/java/org/apache/maven/plugins/jar/FileCollector.java:
##########
@@ -0,0 +1,496 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.PathMatcher;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayDeque;
+import java.util.Deque;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.services.PathMatcherFactory;
+
+/**
+ * Dispatch the files in the output directory into the <abbr>JAR</abbr> files to create.
+ * Instead of just archiving as-is the content of the output directory, this class separates
+ * the following subdirectories to the options listed below:
+ *
+ * <ul>
+ *   <li>The {@code META-INF/MANIFEST.MF} file will be given to the {@code --manifest} option.</li>
+ *   <li>Files in the following directories will be given to the {@code --release} option:
+ *     <ul>
+ *       <li>{@code META-INF/versions/}</li>
+ *       <li>{@code META-INF/versions-modular/<module>/}</li>
+ *       <li>{@code <module>/META-INF/versions/}</li>
+ *     </ul>
+ *   </li>
+ * </ul>
+ *
+ * The reason for using the options is that they allow the {@code jar} tool to perform additional verifications.
+ * For example, when using the {@code --release} option, {@code jar} verifies the <abbr>API</abbr> compatibility.
+ */
+final class FileCollector extends SimpleFileVisitor<Path> {
+    /**
+     * The file to check for deciding whether the <abbr>JAR</abbr> is modular.
+     */
+    static final String MODULE_DESCRIPTOR_FILE_NAME = "module-info.class";
+
+    /**
+     * The {@value} directory.
+     * This is part of <abbr>JAR</abbr> file specification.
+     */
+    private static final String VERSIONS = "versions";
+
+    /**
+     * The {@value} directory.
+     * This is Maven-specific.
+     */
+    private static final String VERSIONS_MODULAR = "versions-modular";
+
+    /**
+     * Context (logger, configuration) in which the <abbr>JAR</abbr> file are created.
+     */
+    private final ToolExecutor context;
+
+    /**
+     * Whether to detect multi-release <abbr>JAR</abbr> files.
+     * The default value is {@code true}.
+     *
+     * @see AbstractJarMojo#detectMultiReleaseJar
+     */
+    private final boolean detectMultiReleaseJar;
+
+    /**
+     * Combination of includes and excludes path matcher applied on files.
+     */
+    @Nonnull
+    private final PathMatcher fileMatcher;
+
+    /**
+     * Combination of includes and excludes path matcher applied on directories.
+     */
+    @Nonnull
+    private final PathMatcher directoryMatcher;
+
+    /**
+     * Whether the matchers accept all files and there is no need to sort the files.
+     * In such case, we can declare whole directories to the {@code jar} tool instead
+     * of scanning the directory tree ourselves.
+     */
+    private final boolean addDirectories;
+
+    /**
+     * Files found in the output directory when package hierarchy is used.
+     * At most one of {@code packageHierarchy} and {@link #moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Archive packageHierarchy;
+
+    /**
+     * Files found in the output directory when module hierarchy is used. Keys are module names.
+     * At most one of {@link #packageHierarchy} and {@code moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Map<String, Archive> moduleHierarchy;
+
+    /**
+     * The current module being archived. This field is updated every times that {@code FileCollector}
+     * enters in a new module directory.
+     */
+    @Nonnull
+    private Archive currentModule;
+
+    /**
+     * The module and target Java release currently being scanned. This field is updated every times that
+     * {@code FileCollector} enters in a new module directory or in a new target Java release for a given module.
+     */
+    @Nonnull
+    private Archive.FileSet currentFilesToArchive;
+
+    /**
+     * The current target Java release, or {@code null} if none.
+     */
+    @Nullable
+    private Runtime.Version currentTargetVersion;
+
+    /**
+     * Identification of the kinds of directories being traversed.
+     * The length of this list is the depth in the directory hierarchy.
+     * The last element identifies the type of the current directory.
+     */
+    private final Deque<DirectoryRole> directoryRoles;
+
+    /**
+     * Whether to check when a file is the {@code MANIFEST.MF} file.
+     * This is allowed only when scanning the content of a {@code META-INF} directory.
+     */
+    private boolean checkForManifest;
+
+    /**
+     * Creates a new file collector.
+     *
+     * @param mojo the <abbr>MOJO</abbr> from which to get the configuration
+     * @param context context (logger, configuration) in which the <abbr>JAR</abbr> file are created
+     * @param directory the base directory of the files to archive
+     */
+    FileCollector(AbstractJarMojo mojo, ToolExecutor context, Path directory, PathMatcherFactory matcherFactory) {
+        this.context = context;
+        detectMultiReleaseJar = mojo.detectMultiReleaseJar;
+        directoryRoles = new ArrayDeque<>();
+        fileMatcher = matcherFactory.createPathMatcher(directory, mojo.getIncludes(), mojo.getExcludes(), false);
+        directoryMatcher = matcherFactory.deriveDirectoryMatcher(fileMatcher);
+        addDirectories = !context.isReproducible()
+                && matcherFactory.isIncludesAll(fileMatcher)
+                && matcherFactory.isIncludesAll(directoryMatcher);
+        packageHierarchy = context.newArchive(null, null, directory);
+        moduleHierarchy = new LinkedHashMap<>();
+        resetToPackageHierarchy();
+    }
+
+    /**
+     * Resets this {@code FileCollector} to the state where a package hierarchy is presumed.
+     */
+    private void resetToPackageHierarchy() {
+        currentModule = packageHierarchy;
+        currentFilesToArchive = currentModule.baseRelease();
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a module.
+     * For an output generated by {@code javac} from a module source hierarchy,
+     * the directory name is guaranteed to be the module name.
+     *
+     * @param directory a {@code "<module>"} or {@code "META-INF/versions-modular/<module>"} directory
+     */
+    private void enterModuleDirectory(final Path directory) {
+        String moduleName = directory.getFileName().toString();
+        currentModule = moduleHierarchy.computeIfAbsent(
+                moduleName, (name) -> context.newArchive(name, currentTargetVersion, directory));
+        currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a target Java version.
+     * The {@code useDirectly} argument tells whether the content of this directory will be specified directly
+     * as the content to add in the <abbr>JAR</abbr> file. This argument should be {@code false} when there is
+     * another directory level (the module names) to process before to add content.
+     *
+     * @param directory a {@code "META-INF/versions/<n>"} or {@code "META-INF/versions-modular/<n>"} directory
+     * @param useDirectly whether the directory is {@code "META-INF/versions/<n>"}
+     * @return whether to skip the directory because of invalid version number
+     */
+    private boolean enterVersionDirectory(final Path directory, final boolean useDirectly) {
+        try {
+            currentTargetVersion = Runtime.Version.parse(directory.getFileName().toString());
+        } catch (IllegalArgumentException e) {
+            context.warnInvalidVersion(directory, e);
+            return true;
+        }
+        if (useDirectly) {
+            currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+        }
+        return false;
+    }
+
+    /**
+     * Determines if the given directory should be scanned for files to archive.
+     * This method may also update {@link #currentFilesToArchive} if it detects
+     * that we are entering in a new module or a new target Java release.
+     *
+     * @param directory the directory which will be traversed
+     * @param attributes the directory's basic attributes
+     */
+    @Override
+    @SuppressWarnings("checkstyle:MissingSwitchDefault")
+    public FileVisitResult preVisitDirectory(final Path directory, final BasicFileAttributes attributes)
+            throws IOException {
+        DirectoryRole role;
+        if (directoryRoles.isEmpty()) {
+            role = DirectoryRole.ROOT;
+        } else {
+            if (!directoryMatcher.matches(directory)) {
+                return FileVisitResult.SKIP_SUBTREE;
+            }
+            checkForManifest = false;
+            role = directoryRoles.getLast();
+            switch (role) {
+                case ROOT:
+                    /*
+                     * Entering in any subdirectory of `target/classes` (or other directory to archive).
+                     * We need to handle `META-INF` and modules in a special way, and archive the rest.
+                     */
+                    if (directory.endsWith(MetadataFiles.META_INF)) {
+                        role = DirectoryRole.META_INF;
+                        checkForManifest = true;
+                    } else if (Files.isRegularFile(directory.resolve(MODULE_DESCRIPTOR_FILE_NAME))) {
+                        role = DirectoryRole.NAMED_MODULE;
+                        enterModuleDirectory(directory);
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case META_INF:
+                    /*
+                     * Entering in a subdirectory of `META-INF` or `<module>/META-INF`. We will need to handle
+                     * `MANIFEST.MF`, `versions` and `versions-modular` in a special way, and archive the rest.
+                     */
+                    if (detectMultiReleaseJar && directory.endsWith(VERSIONS)) {
+                        role = DirectoryRole.VERSIONS;
+                    } else if (directory.endsWith(VERSIONS_MODULAR)) {
+                        if (!detectMultiReleaseJar) {
+                            // Used asked for no multi-release JAR.
+                            return FileVisitResult.SKIP_SUBTREE;
+                        }
+                        role = DirectoryRole.VERSIONS_MODULAR;
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case VERSIONS:
+                    /*
+                     * Entering in a `META-INF/versions/<n>/` directory for a specific target Java release.
+                     * May also be a `<module>/META-INF/versions/<n>/` directory, even if the latter is not
+                     * the layout generated by Maven Compiler Plugin.
+                     */
+                    if (enterVersionDirectory(directory, true)) {
+                        // An error occurred while parsing the version number.
+                        return FileVisitResult.SKIP_SUBTREE;
+                    }
+                    role = DirectoryRole.RESOURCES;
+                    break;
+
+                case VERSIONS_MODULAR:
+                    /*
+                     * Entering in a `META-INF/versions-modular/<n>/` directory for a specific target Java release.
+                     * That directory contains all modules for the version.
+                     */
+                    resetToPackageHierarchy(); // No module in particular yet.
+                    if (enterVersionDirectory(directory, false)) {
+                        // An error occurred while parsing the version number.
+                        return FileVisitResult.SKIP_SUBTREE;
+                    }
+                    role = DirectoryRole.MODULES;
+                    break;
+
+                case MODULES:
+                    /*
+                     * Entering in a `META-INF/versions-modular/<n>/<module>` directory.
+                     */
+                    enterModuleDirectory(directory);
+                    role = DirectoryRole.NAMED_MODULE;
+                    break;
+
+                case NAMED_MODULE:
+                    /*
+                     * Entering in a `<module>` or `META-INF/versions-modular/<n>/<module>` subdirectory.
+                     * A module could have its own `META-INF` subdirectory, so we need to check again.
+                     */
+                    if (directory.endsWith(MetadataFiles.META_INF)) {
+                        role = DirectoryRole.META_INF;
+                        checkForManifest = true;
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+            }
+        }
+        /*
+         * Do not move this condition inside the `switch` block because `role` may have been modified.
+         * The `role` value is now the role of `directory`, not anymore the role of parent directory.
+         */
+        if (addDirectories && role == DirectoryRole.RESOURCES) {
+            currentFilesToArchive.add(directory, attributes, true);
+            /*
+             * Since we are skipping the whole directory, `postVisitDirectory(…)` will not be invoked.
+             * We must reset `currentFilesToArchive` and `currentTargetVersion` by an explicit call.
+             * This is important mostly after we added a whole `META-INF/versions/<n>` directory,
+             * otherwise base files visited afterwards (directory iteration order is unspecified)
+             * would be added to this version's file set instead of the base release.
+             */
+            resetToParentDirectoryState();
+            return FileVisitResult.SKIP_SUBTREE;
+        } else {
+            directoryRoles.addLast(role);
+            return FileVisitResult.CONTINUE;
+        }
+    }
+
+    /**
+     * Updates the {@code FileCollector} state after we finished to scan the content of a directory.
+     * The fields to update depend on which directory has been visited (module, version, <i>etc.</i>).
+     *
+     * @param directory the directory which has been traversed
+     * @param error the error that occurred while traversing the directory, or {@code null} if none
+     */
+    @Override
+    public FileVisitResult postVisitDirectory(final Path directory, final IOException error) throws IOException {
+        if (error != null) {
+            throw error;
+        }
+        switch (directoryRoles.removeLast()) {
+            case NAMED_MODULE:
+                // Exited the directory of a single module.
+                resetToPackageHierarchy();
+                break;
+
+            case ROOT:
+                break;
+
+            default:
+                resetToParentDirectoryState();
+        }
+        return FileVisitResult.CONTINUE;
+    }
+
+    /**
+     * Updates {@code FileCollector} to a state suitable to the parent of the directory that we finished to scan.

Review Comment:
   suitable for



##########
src/main/java/org/apache/maven/plugins/jar/FileCollector.java:
##########
@@ -0,0 +1,496 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.PathMatcher;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayDeque;
+import java.util.Deque;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.services.PathMatcherFactory;
+
+/**
+ * Dispatch the files in the output directory into the <abbr>JAR</abbr> files to create.
+ * Instead of just archiving as-is the content of the output directory, this class separates
+ * the following subdirectories to the options listed below:
+ *
+ * <ul>
+ *   <li>The {@code META-INF/MANIFEST.MF} file will be given to the {@code --manifest} option.</li>
+ *   <li>Files in the following directories will be given to the {@code --release} option:
+ *     <ul>
+ *       <li>{@code META-INF/versions/}</li>
+ *       <li>{@code META-INF/versions-modular/<module>/}</li>
+ *       <li>{@code <module>/META-INF/versions/}</li>
+ *     </ul>
+ *   </li>
+ * </ul>
+ *
+ * The reason for using the options is that they allow the {@code jar} tool to perform additional verifications.
+ * For example, when using the {@code --release} option, {@code jar} verifies the <abbr>API</abbr> compatibility.
+ */
+final class FileCollector extends SimpleFileVisitor<Path> {
+    /**
+     * The file to check for deciding whether the <abbr>JAR</abbr> is modular.
+     */
+    static final String MODULE_DESCRIPTOR_FILE_NAME = "module-info.class";
+
+    /**
+     * The {@value} directory.
+     * This is part of <abbr>JAR</abbr> file specification.
+     */
+    private static final String VERSIONS = "versions";
+
+    /**
+     * The {@value} directory.
+     * This is Maven-specific.
+     */
+    private static final String VERSIONS_MODULAR = "versions-modular";
+
+    /**
+     * Context (logger, configuration) in which the <abbr>JAR</abbr> file are created.
+     */
+    private final ToolExecutor context;
+
+    /**
+     * Whether to detect multi-release <abbr>JAR</abbr> files.
+     * The default value is {@code true}.
+     *
+     * @see AbstractJarMojo#detectMultiReleaseJar
+     */
+    private final boolean detectMultiReleaseJar;
+
+    /**
+     * Combination of includes and excludes path matcher applied on files.
+     */
+    @Nonnull
+    private final PathMatcher fileMatcher;
+
+    /**
+     * Combination of includes and excludes path matcher applied on directories.
+     */
+    @Nonnull
+    private final PathMatcher directoryMatcher;
+
+    /**
+     * Whether the matchers accept all files and there is no need to sort the files.
+     * In such case, we can declare whole directories to the {@code jar} tool instead
+     * of scanning the directory tree ourselves.
+     */
+    private final boolean addDirectories;
+
+    /**
+     * Files found in the output directory when package hierarchy is used.
+     * At most one of {@code packageHierarchy} and {@link #moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Archive packageHierarchy;
+
+    /**
+     * Files found in the output directory when module hierarchy is used. Keys are module names.
+     * At most one of {@link #packageHierarchy} and {@code moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Map<String, Archive> moduleHierarchy;
+
+    /**
+     * The current module being archived. This field is updated every times that {@code FileCollector}
+     * enters in a new module directory.
+     */
+    @Nonnull
+    private Archive currentModule;
+
+    /**
+     * The module and target Java release currently being scanned. This field is updated every times that
+     * {@code FileCollector} enters in a new module directory or in a new target Java release for a given module.
+     */
+    @Nonnull
+    private Archive.FileSet currentFilesToArchive;
+
+    /**
+     * The current target Java release, or {@code null} if none.
+     */
+    @Nullable
+    private Runtime.Version currentTargetVersion;
+
+    /**
+     * Identification of the kinds of directories being traversed.
+     * The length of this list is the depth in the directory hierarchy.
+     * The last element identifies the type of the current directory.
+     */
+    private final Deque<DirectoryRole> directoryRoles;
+
+    /**
+     * Whether to check when a file is the {@code MANIFEST.MF} file.
+     * This is allowed only when scanning the content of a {@code META-INF} directory.
+     */
+    private boolean checkForManifest;
+
+    /**
+     * Creates a new file collector.
+     *
+     * @param mojo the <abbr>MOJO</abbr> from which to get the configuration
+     * @param context context (logger, configuration) in which the <abbr>JAR</abbr> file are created
+     * @param directory the base directory of the files to archive
+     */
+    FileCollector(AbstractJarMojo mojo, ToolExecutor context, Path directory, PathMatcherFactory matcherFactory) {
+        this.context = context;
+        detectMultiReleaseJar = mojo.detectMultiReleaseJar;
+        directoryRoles = new ArrayDeque<>();
+        fileMatcher = matcherFactory.createPathMatcher(directory, mojo.getIncludes(), mojo.getExcludes(), false);
+        directoryMatcher = matcherFactory.deriveDirectoryMatcher(fileMatcher);
+        addDirectories = !context.isReproducible()
+                && matcherFactory.isIncludesAll(fileMatcher)
+                && matcherFactory.isIncludesAll(directoryMatcher);
+        packageHierarchy = context.newArchive(null, null, directory);
+        moduleHierarchy = new LinkedHashMap<>();
+        resetToPackageHierarchy();
+    }
+
+    /**
+     * Resets this {@code FileCollector} to the state where a package hierarchy is presumed.
+     */
+    private void resetToPackageHierarchy() {
+        currentModule = packageHierarchy;
+        currentFilesToArchive = currentModule.baseRelease();
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a module.
+     * For an output generated by {@code javac} from a module source hierarchy,
+     * the directory name is guaranteed to be the module name.
+     *
+     * @param directory a {@code "<module>"} or {@code "META-INF/versions-modular/<module>"} directory
+     */
+    private void enterModuleDirectory(final Path directory) {
+        String moduleName = directory.getFileName().toString();
+        currentModule = moduleHierarchy.computeIfAbsent(
+                moduleName, (name) -> context.newArchive(name, currentTargetVersion, directory));
+        currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a target Java version.
+     * The {@code useDirectly} argument tells whether the content of this directory will be specified directly
+     * as the content to add in the <abbr>JAR</abbr> file. This argument should be {@code false} when there is
+     * another directory level (the module names) to process before to add content.
+     *
+     * @param directory a {@code "META-INF/versions/<n>"} or {@code "META-INF/versions-modular/<n>"} directory
+     * @param useDirectly whether the directory is {@code "META-INF/versions/<n>"}
+     * @return whether to skip the directory because of invalid version number
+     */
+    private boolean enterVersionDirectory(final Path directory, final boolean useDirectly) {
+        try {
+            currentTargetVersion = Runtime.Version.parse(directory.getFileName().toString());
+        } catch (IllegalArgumentException e) {
+            context.warnInvalidVersion(directory, e);
+            return true;
+        }
+        if (useDirectly) {
+            currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+        }
+        return false;
+    }
+
+    /**
+     * Determines if the given directory should be scanned for files to archive.
+     * This method may also update {@link #currentFilesToArchive} if it detects
+     * that we are entering in a new module or a new target Java release.
+     *
+     * @param directory the directory which will be traversed
+     * @param attributes the directory's basic attributes
+     */
+    @Override
+    @SuppressWarnings("checkstyle:MissingSwitchDefault")
+    public FileVisitResult preVisitDirectory(final Path directory, final BasicFileAttributes attributes)
+            throws IOException {
+        DirectoryRole role;
+        if (directoryRoles.isEmpty()) {
+            role = DirectoryRole.ROOT;
+        } else {
+            if (!directoryMatcher.matches(directory)) {
+                return FileVisitResult.SKIP_SUBTREE;
+            }
+            checkForManifest = false;
+            role = directoryRoles.getLast();
+            switch (role) {
+                case ROOT:
+                    /*
+                     * Entering in any subdirectory of `target/classes` (or other directory to archive).
+                     * We need to handle `META-INF` and modules in a special way, and archive the rest.
+                     */
+                    if (directory.endsWith(MetadataFiles.META_INF)) {
+                        role = DirectoryRole.META_INF;
+                        checkForManifest = true;
+                    } else if (Files.isRegularFile(directory.resolve(MODULE_DESCRIPTOR_FILE_NAME))) {
+                        role = DirectoryRole.NAMED_MODULE;
+                        enterModuleDirectory(directory);
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case META_INF:
+                    /*
+                     * Entering in a subdirectory of `META-INF` or `<module>/META-INF`. We will need to handle
+                     * `MANIFEST.MF`, `versions` and `versions-modular` in a special way, and archive the rest.
+                     */
+                    if (detectMultiReleaseJar && directory.endsWith(VERSIONS)) {
+                        role = DirectoryRole.VERSIONS;
+                    } else if (directory.endsWith(VERSIONS_MODULAR)) {
+                        if (!detectMultiReleaseJar) {
+                            // Used asked for no multi-release JAR.
+                            return FileVisitResult.SKIP_SUBTREE;
+                        }
+                        role = DirectoryRole.VERSIONS_MODULAR;
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case VERSIONS:
+                    /*
+                     * Entering in a `META-INF/versions/<n>/` directory for a specific target Java release.
+                     * May also be a `<module>/META-INF/versions/<n>/` directory, even if the latter is not
+                     * the layout generated by Maven Compiler Plugin.
+                     */
+                    if (enterVersionDirectory(directory, true)) {
+                        // An error occurred while parsing the version number.
+                        return FileVisitResult.SKIP_SUBTREE;
+                    }
+                    role = DirectoryRole.RESOURCES;
+                    break;
+
+                case VERSIONS_MODULAR:
+                    /*
+                     * Entering in a `META-INF/versions-modular/<n>/` directory for a specific target Java release.
+                     * That directory contains all modules for the version.
+                     */
+                    resetToPackageHierarchy(); // No module in particular yet.
+                    if (enterVersionDirectory(directory, false)) {
+                        // An error occurred while parsing the version number.
+                        return FileVisitResult.SKIP_SUBTREE;
+                    }
+                    role = DirectoryRole.MODULES;
+                    break;
+
+                case MODULES:
+                    /*
+                     * Entering in a `META-INF/versions-modular/<n>/<module>` directory.
+                     */
+                    enterModuleDirectory(directory);
+                    role = DirectoryRole.NAMED_MODULE;
+                    break;
+
+                case NAMED_MODULE:
+                    /*
+                     * Entering in a `<module>` or `META-INF/versions-modular/<n>/<module>` subdirectory.
+                     * A module could have its own `META-INF` subdirectory, so we need to check again.
+                     */
+                    if (directory.endsWith(MetadataFiles.META_INF)) {
+                        role = DirectoryRole.META_INF;
+                        checkForManifest = true;
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+            }
+        }
+        /*
+         * Do not move this condition inside the `switch` block because `role` may have been modified.
+         * The `role` value is now the role of `directory`, not anymore the role of parent directory.
+         */
+        if (addDirectories && role == DirectoryRole.RESOURCES) {
+            currentFilesToArchive.add(directory, attributes, true);
+            /*
+             * Since we are skipping the whole directory, `postVisitDirectory(…)` will not be invoked.
+             * We must reset `currentFilesToArchive` and `currentTargetVersion` by an explicit call.
+             * This is important mostly after we added a whole `META-INF/versions/<n>` directory,
+             * otherwise base files visited afterwards (directory iteration order is unspecified)
+             * would be added to this version's file set instead of the base release.
+             */
+            resetToParentDirectoryState();
+            return FileVisitResult.SKIP_SUBTREE;
+        } else {
+            directoryRoles.addLast(role);
+            return FileVisitResult.CONTINUE;
+        }
+    }
+
+    /**
+     * Updates the {@code FileCollector} state after we finished to scan the content of a directory.
+     * The fields to update depend on which directory has been visited (module, version, <i>etc.</i>).

Review Comment:
   don't italicize etc.



##########
src/main/java/org/apache/maven/plugins/jar/FileCollector.java:
##########
@@ -0,0 +1,496 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.PathMatcher;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayDeque;
+import java.util.Deque;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.services.PathMatcherFactory;
+
+/**
+ * Dispatch the files in the output directory into the <abbr>JAR</abbr> files to create.
+ * Instead of just archiving as-is the content of the output directory, this class separates
+ * the following subdirectories to the options listed below:
+ *
+ * <ul>
+ *   <li>The {@code META-INF/MANIFEST.MF} file will be given to the {@code --manifest} option.</li>
+ *   <li>Files in the following directories will be given to the {@code --release} option:
+ *     <ul>
+ *       <li>{@code META-INF/versions/}</li>
+ *       <li>{@code META-INF/versions-modular/<module>/}</li>
+ *       <li>{@code <module>/META-INF/versions/}</li>
+ *     </ul>
+ *   </li>
+ * </ul>
+ *
+ * The reason for using the options is that they allow the {@code jar} tool to perform additional verifications.
+ * For example, when using the {@code --release} option, {@code jar} verifies the <abbr>API</abbr> compatibility.
+ */
+final class FileCollector extends SimpleFileVisitor<Path> {
+    /**
+     * The file to check for deciding whether the <abbr>JAR</abbr> is modular.
+     */
+    static final String MODULE_DESCRIPTOR_FILE_NAME = "module-info.class";
+
+    /**
+     * The {@value} directory.
+     * This is part of <abbr>JAR</abbr> file specification.
+     */
+    private static final String VERSIONS = "versions";
+
+    /**
+     * The {@value} directory.
+     * This is Maven-specific.
+     */
+    private static final String VERSIONS_MODULAR = "versions-modular";
+
+    /**
+     * Context (logger, configuration) in which the <abbr>JAR</abbr> file are created.
+     */
+    private final ToolExecutor context;
+
+    /**
+     * Whether to detect multi-release <abbr>JAR</abbr> files.
+     * The default value is {@code true}.
+     *
+     * @see AbstractJarMojo#detectMultiReleaseJar
+     */
+    private final boolean detectMultiReleaseJar;
+
+    /**
+     * Combination of includes and excludes path matcher applied on files.
+     */
+    @Nonnull
+    private final PathMatcher fileMatcher;
+
+    /**
+     * Combination of includes and excludes path matcher applied on directories.
+     */
+    @Nonnull
+    private final PathMatcher directoryMatcher;
+
+    /**
+     * Whether the matchers accept all files and there is no need to sort the files.
+     * In such case, we can declare whole directories to the {@code jar} tool instead
+     * of scanning the directory tree ourselves.
+     */
+    private final boolean addDirectories;
+
+    /**
+     * Files found in the output directory when package hierarchy is used.
+     * At most one of {@code packageHierarchy} and {@link #moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Archive packageHierarchy;
+
+    /**
+     * Files found in the output directory when module hierarchy is used. Keys are module names.
+     * At most one of {@link #packageHierarchy} and {@code moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Map<String, Archive> moduleHierarchy;
+
+    /**
+     * The current module being archived. This field is updated every times that {@code FileCollector}
+     * enters in a new module directory.
+     */
+    @Nonnull
+    private Archive currentModule;
+
+    /**
+     * The module and target Java release currently being scanned. This field is updated every times that
+     * {@code FileCollector} enters in a new module directory or in a new target Java release for a given module.
+     */
+    @Nonnull
+    private Archive.FileSet currentFilesToArchive;
+
+    /**
+     * The current target Java release, or {@code null} if none.
+     */
+    @Nullable
+    private Runtime.Version currentTargetVersion;
+
+    /**
+     * Identification of the kinds of directories being traversed.
+     * The length of this list is the depth in the directory hierarchy.
+     * The last element identifies the type of the current directory.
+     */
+    private final Deque<DirectoryRole> directoryRoles;
+
+    /**
+     * Whether to check when a file is the {@code MANIFEST.MF} file.
+     * This is allowed only when scanning the content of a {@code META-INF} directory.
+     */
+    private boolean checkForManifest;
+
+    /**
+     * Creates a new file collector.
+     *
+     * @param mojo the <abbr>MOJO</abbr> from which to get the configuration
+     * @param context context (logger, configuration) in which the <abbr>JAR</abbr> file are created
+     * @param directory the base directory of the files to archive
+     */
+    FileCollector(AbstractJarMojo mojo, ToolExecutor context, Path directory, PathMatcherFactory matcherFactory) {
+        this.context = context;
+        detectMultiReleaseJar = mojo.detectMultiReleaseJar;
+        directoryRoles = new ArrayDeque<>();
+        fileMatcher = matcherFactory.createPathMatcher(directory, mojo.getIncludes(), mojo.getExcludes(), false);
+        directoryMatcher = matcherFactory.deriveDirectoryMatcher(fileMatcher);
+        addDirectories = !context.isReproducible()
+                && matcherFactory.isIncludesAll(fileMatcher)
+                && matcherFactory.isIncludesAll(directoryMatcher);
+        packageHierarchy = context.newArchive(null, null, directory);
+        moduleHierarchy = new LinkedHashMap<>();
+        resetToPackageHierarchy();
+    }
+
+    /**
+     * Resets this {@code FileCollector} to the state where a package hierarchy is presumed.
+     */
+    private void resetToPackageHierarchy() {
+        currentModule = packageHierarchy;
+        currentFilesToArchive = currentModule.baseRelease();
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a module.
+     * For an output generated by {@code javac} from a module source hierarchy,
+     * the directory name is guaranteed to be the module name.
+     *
+     * @param directory a {@code "<module>"} or {@code "META-INF/versions-modular/<module>"} directory
+     */
+    private void enterModuleDirectory(final Path directory) {
+        String moduleName = directory.getFileName().toString();
+        currentModule = moduleHierarchy.computeIfAbsent(
+                moduleName, (name) -> context.newArchive(name, currentTargetVersion, directory));
+        currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a target Java version.
+     * The {@code useDirectly} argument tells whether the content of this directory will be specified directly
+     * as the content to add in the <abbr>JAR</abbr> file. This argument should be {@code false} when there is
+     * another directory level (the module names) to process before to add content.
+     *
+     * @param directory a {@code "META-INF/versions/<n>"} or {@code "META-INF/versions-modular/<n>"} directory
+     * @param useDirectly whether the directory is {@code "META-INF/versions/<n>"}
+     * @return whether to skip the directory because of invalid version number
+     */
+    private boolean enterVersionDirectory(final Path directory, final boolean useDirectly) {
+        try {
+            currentTargetVersion = Runtime.Version.parse(directory.getFileName().toString());
+        } catch (IllegalArgumentException e) {
+            context.warnInvalidVersion(directory, e);
+            return true;
+        }
+        if (useDirectly) {
+            currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+        }
+        return false;
+    }
+
+    /**
+     * Determines if the given directory should be scanned for files to archive.
+     * This method may also update {@link #currentFilesToArchive} if it detects
+     * that we are entering in a new module or a new target Java release.
+     *
+     * @param directory the directory which will be traversed
+     * @param attributes the directory's basic attributes
+     */
+    @Override
+    @SuppressWarnings("checkstyle:MissingSwitchDefault")
+    public FileVisitResult preVisitDirectory(final Path directory, final BasicFileAttributes attributes)
+            throws IOException {
+        DirectoryRole role;
+        if (directoryRoles.isEmpty()) {
+            role = DirectoryRole.ROOT;
+        } else {
+            if (!directoryMatcher.matches(directory)) {
+                return FileVisitResult.SKIP_SUBTREE;
+            }
+            checkForManifest = false;
+            role = directoryRoles.getLast();
+            switch (role) {
+                case ROOT:
+                    /*
+                     * Entering in any subdirectory of `target/classes` (or other directory to archive).
+                     * We need to handle `META-INF` and modules in a special way, and archive the rest.
+                     */
+                    if (directory.endsWith(MetadataFiles.META_INF)) {
+                        role = DirectoryRole.META_INF;
+                        checkForManifest = true;
+                    } else if (Files.isRegularFile(directory.resolve(MODULE_DESCRIPTOR_FILE_NAME))) {
+                        role = DirectoryRole.NAMED_MODULE;
+                        enterModuleDirectory(directory);
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case META_INF:
+                    /*
+                     * Entering in a subdirectory of `META-INF` or `<module>/META-INF`. We will need to handle
+                     * `MANIFEST.MF`, `versions` and `versions-modular` in a special way, and archive the rest.
+                     */
+                    if (detectMultiReleaseJar && directory.endsWith(VERSIONS)) {
+                        role = DirectoryRole.VERSIONS;
+                    } else if (directory.endsWith(VERSIONS_MODULAR)) {
+                        if (!detectMultiReleaseJar) {
+                            // Used asked for no multi-release JAR.
+                            return FileVisitResult.SKIP_SUBTREE;
+                        }
+                        role = DirectoryRole.VERSIONS_MODULAR;
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case VERSIONS:
+                    /*
+                     * Entering in a `META-INF/versions/<n>/` directory for a specific target Java release.
+                     * May also be a `<module>/META-INF/versions/<n>/` directory, even if the latter is not
+                     * the layout generated by Maven Compiler Plugin.
+                     */
+                    if (enterVersionDirectory(directory, true)) {
+                        // An error occurred while parsing the version number.
+                        return FileVisitResult.SKIP_SUBTREE;
+                    }
+                    role = DirectoryRole.RESOURCES;
+                    break;
+
+                case VERSIONS_MODULAR:
+                    /*
+                     * Entering in a `META-INF/versions-modular/<n>/` directory for a specific target Java release.
+                     * That directory contains all modules for the version.
+                     */
+                    resetToPackageHierarchy(); // No module in particular yet.
+                    if (enterVersionDirectory(directory, false)) {
+                        // An error occurred while parsing the version number.
+                        return FileVisitResult.SKIP_SUBTREE;
+                    }
+                    role = DirectoryRole.MODULES;
+                    break;
+
+                case MODULES:
+                    /*
+                     * Entering in a `META-INF/versions-modular/<n>/<module>` directory.
+                     */
+                    enterModuleDirectory(directory);
+                    role = DirectoryRole.NAMED_MODULE;
+                    break;
+
+                case NAMED_MODULE:
+                    /*
+                     * Entering in a `<module>` or `META-INF/versions-modular/<n>/<module>` subdirectory.
+                     * A module could have its own `META-INF` subdirectory, so we need to check again.
+                     */
+                    if (directory.endsWith(MetadataFiles.META_INF)) {
+                        role = DirectoryRole.META_INF;
+                        checkForManifest = true;
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+            }
+        }
+        /*
+         * Do not move this condition inside the `switch` block because `role` may have been modified.
+         * The `role` value is now the role of `directory`, not anymore the role of parent directory.
+         */
+        if (addDirectories && role == DirectoryRole.RESOURCES) {
+            currentFilesToArchive.add(directory, attributes, true);
+            /*
+             * Since we are skipping the whole directory, `postVisitDirectory(…)` will not be invoked.
+             * We must reset `currentFilesToArchive` and `currentTargetVersion` by an explicit call.
+             * This is important mostly after we added a whole `META-INF/versions/<n>` directory,
+             * otherwise base files visited afterwards (directory iteration order is unspecified)
+             * would be added to this version's file set instead of the base release.
+             */
+            resetToParentDirectoryState();
+            return FileVisitResult.SKIP_SUBTREE;
+        } else {
+            directoryRoles.addLast(role);
+            return FileVisitResult.CONTINUE;
+        }
+    }
+
+    /**
+     * Updates the {@code FileCollector} state after we finished to scan the content of a directory.
+     * The fields to update depend on which directory has been visited (module, version, <i>etc.</i>).
+     *
+     * @param directory the directory which has been traversed
+     * @param error the error that occurred while traversing the directory, or {@code null} if none
+     */
+    @Override
+    public FileVisitResult postVisitDirectory(final Path directory, final IOException error) throws IOException {
+        if (error != null) {
+            throw error;
+        }
+        switch (directoryRoles.removeLast()) {
+            case NAMED_MODULE:
+                // Exited the directory of a single module.
+                resetToPackageHierarchy();
+                break;
+
+            case ROOT:
+                break;
+
+            default:
+                resetToParentDirectoryState();
+        }
+        return FileVisitResult.CONTINUE;
+    }
+
+    /**
+     * Updates {@code FileCollector} to a state suitable to the parent of the directory that we finished to scan.
+     * Contrarily to {@link #postVisitDirectory(Path, IOException)}, this method expects the last element of
+     * {@link #directoryRoles} to describe the parent directory, not the directory that we finished to visit.
+     */
+    @SuppressWarnings("checkstyle:MissingSwitchDefault")
+    private void resetToParentDirectoryState() {
+        switch (directoryRoles.getLast()) {
+            case VERSIONS:
+            case VERSIONS_MODULAR:
+                // Exited the directory for one target Java release.
+                currentFilesToArchive = currentModule.baseRelease();
+                currentTargetVersion = null;
+                break;
+
+            case META_INF:
+                checkForManifest = true;
+                break;
+        }
+    }
+
+    /**
+     * Archives a single file if accepted by the matcher.
+     *
+     * @param file the file
+     * @param attributes the file's basic attributes
+     */
+    @Override
+    public FileVisitResult visitFile(final Path file, final BasicFileAttributes attributes) {
+        if (fileMatcher.matches(file)) {
+            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.add(file, attributes, false);
+            }
+        }
+        return FileVisitResult.CONTINUE;
+    }
+
+    /**
+     * 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}, then this method ensures that at least one archive
+     * remains even if that archive is empty.
+     *
+     * @param skipIfEmpty value of {@link AbstractJarMojo#skipIfEmpty}
+     */
+    public void prune(boolean skipIfEmpty) {
+        boolean isModuleHierarchy = !moduleHierarchy.isEmpty();
+        moduleHierarchy.values().forEach((archive) -> archive.prune(skipIfEmpty));
+        moduleHierarchy.values().removeIf(Archive::isEmpty);
+        packageHierarchy.prune(isModuleHierarchy || skipIfEmpty);
+    }
+
+    /**
+     * Moves, copies or ignores orphan files.

Review Comment:
   copies,



##########
src/main/java/org/apache/maven/plugins/jar/FileCollector.java:
##########
@@ -0,0 +1,496 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.PathMatcher;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayDeque;
+import java.util.Deque;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.services.PathMatcherFactory;
+
+/**
+ * Dispatch the files in the output directory into the <abbr>JAR</abbr> files to create.
+ * Instead of just archiving as-is the content of the output directory, this class separates
+ * the following subdirectories to the options listed below:
+ *
+ * <ul>
+ *   <li>The {@code META-INF/MANIFEST.MF} file will be given to the {@code --manifest} option.</li>
+ *   <li>Files in the following directories will be given to the {@code --release} option:
+ *     <ul>
+ *       <li>{@code META-INF/versions/}</li>
+ *       <li>{@code META-INF/versions-modular/<module>/}</li>
+ *       <li>{@code <module>/META-INF/versions/}</li>
+ *     </ul>
+ *   </li>
+ * </ul>
+ *
+ * The reason for using the options is that they allow the {@code jar} tool to perform additional verifications.
+ * For example, when using the {@code --release} option, {@code jar} verifies the <abbr>API</abbr> compatibility.
+ */
+final class FileCollector extends SimpleFileVisitor<Path> {
+    /**
+     * The file to check for deciding whether the <abbr>JAR</abbr> is modular.
+     */
+    static final String MODULE_DESCRIPTOR_FILE_NAME = "module-info.class";
+
+    /**
+     * The {@value} directory.
+     * This is part of <abbr>JAR</abbr> file specification.
+     */
+    private static final String VERSIONS = "versions";
+
+    /**
+     * The {@value} directory.
+     * This is Maven-specific.
+     */
+    private static final String VERSIONS_MODULAR = "versions-modular";
+
+    /**
+     * Context (logger, configuration) in which the <abbr>JAR</abbr> file are created.
+     */
+    private final ToolExecutor context;
+
+    /**
+     * Whether to detect multi-release <abbr>JAR</abbr> files.
+     * The default value is {@code true}.
+     *
+     * @see AbstractJarMojo#detectMultiReleaseJar
+     */
+    private final boolean detectMultiReleaseJar;
+
+    /**
+     * Combination of includes and excludes path matcher applied on files.
+     */
+    @Nonnull
+    private final PathMatcher fileMatcher;
+
+    /**
+     * Combination of includes and excludes path matcher applied on directories.
+     */
+    @Nonnull
+    private final PathMatcher directoryMatcher;
+
+    /**
+     * Whether the matchers accept all files and there is no need to sort the files.
+     * In such case, we can declare whole directories to the {@code jar} tool instead
+     * of scanning the directory tree ourselves.
+     */
+    private final boolean addDirectories;
+
+    /**
+     * Files found in the output directory when package hierarchy is used.
+     * At most one of {@code packageHierarchy} and {@link #moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Archive packageHierarchy;
+
+    /**
+     * Files found in the output directory when module hierarchy is used. Keys are module names.
+     * At most one of {@link #packageHierarchy} and {@code moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Map<String, Archive> moduleHierarchy;
+
+    /**
+     * The current module being archived. This field is updated every times that {@code FileCollector}
+     * enters in a new module directory.
+     */
+    @Nonnull
+    private Archive currentModule;
+
+    /**
+     * The module and target Java release currently being scanned. This field is updated every times that
+     * {@code FileCollector} enters in a new module directory or in a new target Java release for a given module.
+     */
+    @Nonnull
+    private Archive.FileSet currentFilesToArchive;
+
+    /**
+     * The current target Java release, or {@code null} if none.
+     */
+    @Nullable
+    private Runtime.Version currentTargetVersion;
+
+    /**
+     * Identification of the kinds of directories being traversed.
+     * The length of this list is the depth in the directory hierarchy.
+     * The last element identifies the type of the current directory.
+     */
+    private final Deque<DirectoryRole> directoryRoles;
+
+    /**
+     * Whether to check when a file is the {@code MANIFEST.MF} file.
+     * This is allowed only when scanning the content of a {@code META-INF} directory.
+     */
+    private boolean checkForManifest;
+
+    /**
+     * Creates a new file collector.
+     *
+     * @param mojo the <abbr>MOJO</abbr> from which to get the configuration
+     * @param context context (logger, configuration) in which the <abbr>JAR</abbr> file are created
+     * @param directory the base directory of the files to archive
+     */
+    FileCollector(AbstractJarMojo mojo, ToolExecutor context, Path directory, PathMatcherFactory matcherFactory) {
+        this.context = context;
+        detectMultiReleaseJar = mojo.detectMultiReleaseJar;
+        directoryRoles = new ArrayDeque<>();
+        fileMatcher = matcherFactory.createPathMatcher(directory, mojo.getIncludes(), mojo.getExcludes(), false);
+        directoryMatcher = matcherFactory.deriveDirectoryMatcher(fileMatcher);
+        addDirectories = !context.isReproducible()
+                && matcherFactory.isIncludesAll(fileMatcher)
+                && matcherFactory.isIncludesAll(directoryMatcher);
+        packageHierarchy = context.newArchive(null, null, directory);
+        moduleHierarchy = new LinkedHashMap<>();
+        resetToPackageHierarchy();
+    }
+
+    /**
+     * Resets this {@code FileCollector} to the state where a package hierarchy is presumed.
+     */
+    private void resetToPackageHierarchy() {
+        currentModule = packageHierarchy;
+        currentFilesToArchive = currentModule.baseRelease();
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a module.
+     * For an output generated by {@code javac} from a module source hierarchy,
+     * the directory name is guaranteed to be the module name.
+     *
+     * @param directory a {@code "<module>"} or {@code "META-INF/versions-modular/<module>"} directory
+     */
+    private void enterModuleDirectory(final Path directory) {
+        String moduleName = directory.getFileName().toString();
+        currentModule = moduleHierarchy.computeIfAbsent(
+                moduleName, (name) -> context.newArchive(name, currentTargetVersion, directory));
+        currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a target Java version.
+     * The {@code useDirectly} argument tells whether the content of this directory will be specified directly
+     * as the content to add in the <abbr>JAR</abbr> file. This argument should be {@code false} when there is
+     * another directory level (the module names) to process before to add content.
+     *
+     * @param directory a {@code "META-INF/versions/<n>"} or {@code "META-INF/versions-modular/<n>"} directory
+     * @param useDirectly whether the directory is {@code "META-INF/versions/<n>"}
+     * @return whether to skip the directory because of invalid version number
+     */
+    private boolean enterVersionDirectory(final Path directory, final boolean useDirectly) {
+        try {
+            currentTargetVersion = Runtime.Version.parse(directory.getFileName().toString());
+        } catch (IllegalArgumentException e) {
+            context.warnInvalidVersion(directory, e);
+            return true;
+        }
+        if (useDirectly) {
+            currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+        }
+        return false;
+    }
+
+    /**
+     * Determines if the given directory should be scanned for files to archive.
+     * This method may also update {@link #currentFilesToArchive} if it detects
+     * that we are entering in a new module or a new target Java release.
+     *
+     * @param directory the directory which will be traversed
+     * @param attributes the directory's basic attributes
+     */
+    @Override
+    @SuppressWarnings("checkstyle:MissingSwitchDefault")
+    public FileVisitResult preVisitDirectory(final Path directory, final BasicFileAttributes attributes)
+            throws IOException {
+        DirectoryRole role;
+        if (directoryRoles.isEmpty()) {
+            role = DirectoryRole.ROOT;
+        } else {
+            if (!directoryMatcher.matches(directory)) {
+                return FileVisitResult.SKIP_SUBTREE;
+            }
+            checkForManifest = false;
+            role = directoryRoles.getLast();
+            switch (role) {
+                case ROOT:
+                    /*
+                     * Entering in any subdirectory of `target/classes` (or other directory to archive).
+                     * We need to handle `META-INF` and modules in a special way, and archive the rest.
+                     */
+                    if (directory.endsWith(MetadataFiles.META_INF)) {
+                        role = DirectoryRole.META_INF;
+                        checkForManifest = true;
+                    } else if (Files.isRegularFile(directory.resolve(MODULE_DESCRIPTOR_FILE_NAME))) {
+                        role = DirectoryRole.NAMED_MODULE;
+                        enterModuleDirectory(directory);
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case META_INF:
+                    /*
+                     * Entering in a subdirectory of `META-INF` or `<module>/META-INF`. We will need to handle
+                     * `MANIFEST.MF`, `versions` and `versions-modular` in a special way, and archive the rest.
+                     */
+                    if (detectMultiReleaseJar && directory.endsWith(VERSIONS)) {
+                        role = DirectoryRole.VERSIONS;
+                    } else if (directory.endsWith(VERSIONS_MODULAR)) {
+                        if (!detectMultiReleaseJar) {
+                            // Used asked for no multi-release JAR.
+                            return FileVisitResult.SKIP_SUBTREE;
+                        }
+                        role = DirectoryRole.VERSIONS_MODULAR;
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case VERSIONS:
+                    /*
+                     * Entering in a `META-INF/versions/<n>/` directory for a specific target Java release.
+                     * May also be a `<module>/META-INF/versions/<n>/` directory, even if the latter is not
+                     * the layout generated by Maven Compiler Plugin.
+                     */
+                    if (enterVersionDirectory(directory, true)) {
+                        // An error occurred while parsing the version number.
+                        return FileVisitResult.SKIP_SUBTREE;
+                    }
+                    role = DirectoryRole.RESOURCES;
+                    break;
+
+                case VERSIONS_MODULAR:
+                    /*
+                     * Entering in a `META-INF/versions-modular/<n>/` directory for a specific target Java release.
+                     * That directory contains all modules for the version.
+                     */
+                    resetToPackageHierarchy(); // No module in particular yet.
+                    if (enterVersionDirectory(directory, false)) {
+                        // An error occurred while parsing the version number.
+                        return FileVisitResult.SKIP_SUBTREE;
+                    }
+                    role = DirectoryRole.MODULES;
+                    break;
+
+                case MODULES:
+                    /*
+                     * Entering in a `META-INF/versions-modular/<n>/<module>` directory.
+                     */
+                    enterModuleDirectory(directory);
+                    role = DirectoryRole.NAMED_MODULE;
+                    break;
+
+                case NAMED_MODULE:
+                    /*
+                     * Entering in a `<module>` or `META-INF/versions-modular/<n>/<module>` subdirectory.
+                     * A module could have its own `META-INF` subdirectory, so we need to check again.
+                     */
+                    if (directory.endsWith(MetadataFiles.META_INF)) {
+                        role = DirectoryRole.META_INF;
+                        checkForManifest = true;
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+            }
+        }
+        /*
+         * Do not move this condition inside the `switch` block because `role` may have been modified.
+         * The `role` value is now the role of `directory`, not anymore the role of parent directory.
+         */
+        if (addDirectories && role == DirectoryRole.RESOURCES) {
+            currentFilesToArchive.add(directory, attributes, true);
+            /*
+             * Since we are skipping the whole directory, `postVisitDirectory(…)` will not be invoked.
+             * We must reset `currentFilesToArchive` and `currentTargetVersion` by an explicit call.
+             * This is important mostly after we added a whole `META-INF/versions/<n>` directory,
+             * otherwise base files visited afterwards (directory iteration order is unspecified)
+             * would be added to this version's file set instead of the base release.
+             */
+            resetToParentDirectoryState();
+            return FileVisitResult.SKIP_SUBTREE;
+        } else {
+            directoryRoles.addLast(role);
+            return FileVisitResult.CONTINUE;
+        }
+    }
+
+    /**
+     * Updates the {@code FileCollector} state after we finished to scan the content of a directory.
+     * The fields to update depend on which directory has been visited (module, version, <i>etc.</i>).
+     *
+     * @param directory the directory which has been traversed
+     * @param error the error that occurred while traversing the directory, or {@code null} if none
+     */
+    @Override
+    public FileVisitResult postVisitDirectory(final Path directory, final IOException error) throws IOException {
+        if (error != null) {
+            throw error;
+        }
+        switch (directoryRoles.removeLast()) {
+            case NAMED_MODULE:
+                // Exited the directory of a single module.
+                resetToPackageHierarchy();
+                break;
+
+            case ROOT:
+                break;
+
+            default:
+                resetToParentDirectoryState();
+        }
+        return FileVisitResult.CONTINUE;
+    }
+
+    /**
+     * Updates {@code FileCollector} to a state suitable to the parent of the directory that we finished to scan.
+     * Contrarily to {@link #postVisitDirectory(Path, IOException)}, this method expects the last element of
+     * {@link #directoryRoles} to describe the parent directory, not the directory that we finished to visit.
+     */
+    @SuppressWarnings("checkstyle:MissingSwitchDefault")
+    private void resetToParentDirectoryState() {
+        switch (directoryRoles.getLast()) {
+            case VERSIONS:
+            case VERSIONS_MODULAR:
+                // Exited the directory for one target Java release.
+                currentFilesToArchive = currentModule.baseRelease();
+                currentTargetVersion = null;
+                break;
+
+            case META_INF:
+                checkForManifest = true;
+                break;
+        }
+    }
+
+    /**
+     * Archives a single file if accepted by the matcher.
+     *
+     * @param file the file
+     * @param attributes the file's basic attributes
+     */
+    @Override
+    public FileVisitResult visitFile(final Path file, final BasicFileAttributes attributes) {
+        if (fileMatcher.matches(file)) {
+            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.add(file, attributes, false);
+            }
+        }
+        return FileVisitResult.CONTINUE;
+    }
+
+    /**
+     * 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}, then this method ensures that at least one archive

Review Comment:
   delete then



##########
src/main/java/org/apache/maven/plugins/jar/PomDerivation.java:
##########
@@ -0,0 +1,525 @@
+/*
+ * 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.jar;
+
+import javax.xml.stream.XMLStreamException;
+
+import java.io.BufferedInputStream;
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.UncheckedIOException;
+import java.lang.module.ModuleDescriptor;
+import java.lang.module.ModuleFinder;
+import java.lang.module.ModuleReference;
+import java.net.URI;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.DependencyCoordinates;
+import org.apache.maven.api.JavaPathType;
+import org.apache.maven.api.Session;
+import org.apache.maven.api.Type;
+import org.apache.maven.api.model.Dependency;
+import org.apache.maven.api.model.Model;
+import org.apache.maven.api.model.Parent;
+import org.apache.maven.api.plugin.MojoException;
+import org.apache.maven.api.services.DependencyCoordinatesFactory;
+import org.apache.maven.api.services.DependencyCoordinatesFactoryRequest;
+import org.apache.maven.api.services.DependencyResolver;
+import org.apache.maven.api.services.DependencyResolverRequest;
+import org.apache.maven.api.services.DependencyResolverResult;
+import org.apache.maven.api.services.ModelBuilderException;
+import org.apache.maven.model.v4.MavenStaxWriter;
+
+/**
+ * A mapper from Maven model dependencies to Java module names.
+ * A single instance of this class is created for a Maven project,
+ * then shared by all {@link ForModule} instances (one per module to archive).
+ */
+final class PomDerivation {
+    /**
+     * Whether to expand the list of transitive dependencies in the generated <abbr>POM</abbr>.
+     */
+    private static final boolean EXPAND_TRANSITIVE = false;
+
+    /**
+     * Copy of {@link AbstractJarMojo#session}.
+     */
+    private final Session session;
+
+    /**
+     * The project model, which includes dependencies of all modules.
+     */
+    private final Model projectModel;
+
+    /**
+     * The factory to use for creating temporary {@link DependencyCoordinates} instances.
+     */
+    private final DependencyCoordinatesFactory coordinateFactory;
+
+    /**
+     * Provide module descriptors from module names.
+     * May be {@code null} if no {@code module-info} was found.
+     */
+    private final ModuleFinder moduleFinder;
+
+    /**
+     * Module references from paths to the <abbr>JAR</abbr> file or root directory.
+     */
+    private final Map<URI, ModuleReference> fromURI;
+
+    /**
+     * Module names associated to Maven dependencies.

Review Comment:
   associated with



##########
src/main/java/org/apache/maven/plugins/jar/TimestampCheck.java:
##########
@@ -0,0 +1,237 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.nio.file.attribute.FileTime;
+import java.util.Collection;
+import java.util.Enumeration;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+
+import org.apache.maven.api.plugin.Log;
+
+/**
+ * Checks file timestamps in order to determine if anything changed compared to an existing <abbr>JAR</abbr> file.
+ * This class may scan directories, but only if they have not already been visited by {@link FileCollector}.
+ * Note that the latter can occur only if {@link FileCollector} has no {@code PathMatcher}.
+ * Therefore, this class uses no {@code PathMatcher} neither.

Review Comment:
   delete neither



##########
src/main/java/org/apache/maven/plugins/jar/PomDerivation.java:
##########
@@ -0,0 +1,525 @@
+/*
+ * 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.jar;
+
+import javax.xml.stream.XMLStreamException;
+
+import java.io.BufferedInputStream;
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.UncheckedIOException;
+import java.lang.module.ModuleDescriptor;
+import java.lang.module.ModuleFinder;
+import java.lang.module.ModuleReference;
+import java.net.URI;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.DependencyCoordinates;
+import org.apache.maven.api.JavaPathType;
+import org.apache.maven.api.Session;
+import org.apache.maven.api.Type;
+import org.apache.maven.api.model.Dependency;
+import org.apache.maven.api.model.Model;
+import org.apache.maven.api.model.Parent;
+import org.apache.maven.api.plugin.MojoException;
+import org.apache.maven.api.services.DependencyCoordinatesFactory;
+import org.apache.maven.api.services.DependencyCoordinatesFactoryRequest;
+import org.apache.maven.api.services.DependencyResolver;
+import org.apache.maven.api.services.DependencyResolverRequest;
+import org.apache.maven.api.services.DependencyResolverResult;
+import org.apache.maven.api.services.ModelBuilderException;
+import org.apache.maven.model.v4.MavenStaxWriter;
+
+/**
+ * A mapper from Maven model dependencies to Java module names.
+ * A single instance of this class is created for a Maven project,
+ * then shared by all {@link ForModule} instances (one per module to archive).
+ */
+final class PomDerivation {
+    /**
+     * Whether to expand the list of transitive dependencies in the generated <abbr>POM</abbr>.
+     */
+    private static final boolean EXPAND_TRANSITIVE = false;
+
+    /**
+     * Copy of {@link AbstractJarMojo#session}.
+     */
+    private final Session session;
+
+    /**
+     * The project model, which includes dependencies of all modules.
+     */
+    private final Model projectModel;
+
+    /**
+     * The factory to use for creating temporary {@link DependencyCoordinates} instances.
+     */
+    private final DependencyCoordinatesFactory coordinateFactory;
+
+    /**
+     * Provide module descriptors from module names.
+     * May be {@code null} if no {@code module-info} was found.
+     */
+    private final ModuleFinder moduleFinder;
+
+    /**
+     * Module references from paths to the <abbr>JAR</abbr> file or root directory.
+     */
+    private final Map<URI, ModuleReference> fromURI;
+
+    /**
+     * Module names associated to Maven dependencies.
+     * This map contains {@link DependencyCoordinates#getId()} as keys and module references as values.
+     * This is used for detecting which dependencies are really used according {@code module-info.class}.

Review Comment:
   for detecting --> to detect



##########
src/main/java/org/apache/maven/plugins/jar/MetadataFiles.java:
##########
@@ -0,0 +1,250 @@
+/*
+ * 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.jar;
+
+import java.io.BufferedWriter;
+import java.io.Closeable;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Properties;
+import java.util.jar.Manifest;
+import java.util.stream.Collectors;
+
+import org.apache.maven.api.ProducedArtifact;
+import org.apache.maven.api.Project;
+import org.apache.maven.shared.archiver.MavenArchiveConfiguration;
+
+/**
+ * Temporary metadata files generated by Maven before inclusion in the archive.
+ * Those files are created in a temporary {@code META-INF} directory when first needed.
+ * Those files are deleted after the build, unless the build failed or Maven was run in verbose mode.
+ */
+final class MetadataFiles implements Closeable {
+    /**
+     * The {@value} directory.
+     * This is part of <abbr>JAR</abbr> file specification.
+     */
+    static final String META_INF = "META-INF";
+
+    /**
+     * The {@value} file.
+     * This is part of <abbr>JAR</abbr> file specification.
+     */
+    static final String MANIFEST = "MANIFEST.MF";
+
+    /**
+     * The subdirectory where to add Maven-specific files.
+     */
+    static final String MAVEN_DIR = "maven";
+
+    /**
+     * The project for which to write metadata files.
+     */
+    private final Project project;
+
+    /**
+     * The output directory (usually {@code ${baseDir}/target/}).
+     */
+    private final Path buildDir;
+
+    /**
+     * All files and directories in the order that they were created.
+     * The first element of this list shall be the root temporary directory created by this class.
+     */
+    private final List<Path> filesToDelete;
+
+    /**
+     * The <abbr>POM</abbr> file to attach to the artifact. This is initially the project <abbr>POM</abbr>,
+     * but will be replaced by a new file generated by {@link ForModule} if module hierarchy is used.
+     * That file may be copied verbatim in the {@code META-INF/maven/} directory of the <abbr>JAR</abbr>.
+     */
+    private Path attachedPOM;
+
+    /**
+     * Creates an initially empty set of temporary metadata files.
+     *
+     * @param project the project for which to write metadata files
+     * @param buildDir the (usually) {@code ${baseDir}/target/} directory
+     */
+    MetadataFiles(Project project, Path buildDir) {
+        this.project = project;
+        this.buildDir = buildDir;
+        filesToDelete = new ArrayList<>();
+        attachedPOM = project.getPomPath();
+    }
+
+    /**
+     * Derives a <abbr>POM</abbr> as the intersection of the given {@code model} and {@code archive}.
+     *
+     * @param context the tool executor which is generating all archives
+     * @param archive the archive for which to generate a <abbr>POM</abbr>
+     * @param manifest manifest to use for deriving project name, or {@code null} if none
+     * @throws IOException if an error occurred while reading the {@code module-info.class} file
+     *         or while writing the <abbr>POM</abbr> file
+     */
+    void deriveModulePOM(ToolExecutor context, Archive archive, Manifest manifest) throws IOException {
+        var pom = context.pomDerivation.new ForModule(archive, manifest);
+        pom.writeModulePOM();
+        attachedPOM = pom.pomFile;
+        archive.pomFile = pom.pomFile;
+    }
+
+    /**
+     * Adds the given manifest in a temporary file.
+     * The file will be deleted when {@link #close()} is invoked.
+     *
+     * @param manifest the manifest to write
+     * @return the temporary manifest file
+     * @throws IOException if an error occurred while writing the file
+     */
+    public Path addManifest(final Manifest manifest) throws IOException {
+        Path file = baseDirectory().resolve(MANIFEST);
+        try (OutputStream out = Files.newOutputStream(file)) {
+            filesToDelete.add(file);
+            manifest.write(out);
+        }
+        return file;
+    }
+
+    /**
+     * {@return the root temporary directory for the files created by this class}
+     * The directory is created the first time that this method is invoked.
+     *
+     * @throws IOException if an error occurred while creating the temporary directory
+     */
+    private Path baseDirectory() throws IOException {
+        if (filesToDelete.isEmpty()) {
+            filesToDelete.add(Files.createTempDirectory(buildDir, "classes-"));
+        }
+        return filesToDelete.get(0);
+    }
+
+    /**
+     * Creates a new directory and adds it to the list of files to delete after the build.
+     *
+     * @param dir the existing directory where to create a sub-directory
+     * @param path path to the subdirectory to create
+     * @return the new directory
+     * @throws IOException if an error occurred while creating the subdirectory
+     */
+    private Path createDirectories(Path dir, String... path) throws IOException {
+        for (String subdir : path) {
+            dir = Files.createDirectory(dir.resolve(subdir));
+            filesToDelete.add(dir);
+        }
+        return dir;
+    }
+
+    /**
+     * Writes the {@code pom.xml} and {@code pom.properties} files.
+     * This method returns the base temporary directory followed by files that the "jar" tool will need to add
+     *
+     * @param archive archive configuration
+     * @param reproducible whether to enforce reproducible build
+     * @return arguments for the "jar" tool
+     * @throws IOException if an error occurred while writing the files
+     */
+    public List<Path> addPOM(final MavenArchiveConfiguration archive, final boolean reproducible) throws IOException {
+        final String groupId = project.getGroupId();
+        final String artifactId = project.getArtifactId();
+        final String version;
+        final ProducedArtifact pom = project.getPomArtifact();
+        if (pom.isSnapshot()) {
+            version = pom.getVersion().toString();
+        } else {
+            version = project.getVersion();
+        }
+        final Path baseDir = baseDirectory();
+        final Path mavenDir = createDirectories(baseDir, META_INF, MAVEN_DIR, groupId, artifactId);
+        final Path pomFile = linkOrCopy(attachedPOM, mavenDir.resolve("pom.xml"));
+        filesToDelete.add(pomFile); // Add soon for deleting this file even if an exception is thrown below.

Review Comment:
   "Add soon for deleting this file even if an exception is thrown below." is unclear



##########
src/main/java/org/apache/maven/plugins/jar/PomDerivation.java:
##########
@@ -0,0 +1,525 @@
+/*
+ * 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.jar;
+
+import javax.xml.stream.XMLStreamException;
+
+import java.io.BufferedInputStream;
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.UncheckedIOException;
+import java.lang.module.ModuleDescriptor;
+import java.lang.module.ModuleFinder;
+import java.lang.module.ModuleReference;
+import java.net.URI;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.DependencyCoordinates;
+import org.apache.maven.api.JavaPathType;
+import org.apache.maven.api.Session;
+import org.apache.maven.api.Type;
+import org.apache.maven.api.model.Dependency;
+import org.apache.maven.api.model.Model;
+import org.apache.maven.api.model.Parent;
+import org.apache.maven.api.plugin.MojoException;
+import org.apache.maven.api.services.DependencyCoordinatesFactory;
+import org.apache.maven.api.services.DependencyCoordinatesFactoryRequest;
+import org.apache.maven.api.services.DependencyResolver;
+import org.apache.maven.api.services.DependencyResolverRequest;
+import org.apache.maven.api.services.DependencyResolverResult;
+import org.apache.maven.api.services.ModelBuilderException;
+import org.apache.maven.model.v4.MavenStaxWriter;
+
+/**
+ * A mapper from Maven model dependencies to Java module names.
+ * A single instance of this class is created for a Maven project,
+ * then shared by all {@link ForModule} instances (one per module to archive).
+ */
+final class PomDerivation {
+    /**
+     * Whether to expand the list of transitive dependencies in the generated <abbr>POM</abbr>.
+     */
+    private static final boolean EXPAND_TRANSITIVE = false;
+
+    /**
+     * Copy of {@link AbstractJarMojo#session}.
+     */
+    private final Session session;
+
+    /**
+     * The project model, which includes dependencies of all modules.
+     */
+    private final Model projectModel;
+
+    /**
+     * The factory to use for creating temporary {@link DependencyCoordinates} instances.
+     */
+    private final DependencyCoordinatesFactory coordinateFactory;
+
+    /**
+     * Provide module descriptors from module names.
+     * May be {@code null} if no {@code module-info} was found.
+     */
+    private final ModuleFinder moduleFinder;
+
+    /**
+     * Module references from paths to the <abbr>JAR</abbr> file or root directory.
+     */
+    private final Map<URI, ModuleReference> fromURI;
+
+    /**
+     * Module names associated to Maven dependencies.
+     * This map contains {@link DependencyCoordinates#getId()} as keys and module references as values.
+     * This is used for detecting which dependencies are really used according {@code module-info.class}.
+     *
+     * @todo The keys should be instances of {@link DependencyCoordinates}. Unfortunately, as of Maven 4.0.0-rc-5
+     *       that interface does not define the {@code equals} and {@code hashCode} contracts.
+     */
+    private final Map<String, ModuleReference> fromDependency;
+
+    /**
+     * Modules that are built by the project. Keys are module names.
+     */
+    private final Map<String, Dependency> builtModules;
+
+    /**
+     * Creates a new mapper from Maven dependency to module name.
+     *
+     * @param mojo the enclosing <abbr>MOJO</abbr>
+     * @param moduleRoots paths to root directories of each module to archive in a module hierarchy
+     * @throws IOException if an I/O error occurred while fetching dependencies
+     * @throws MavenException if an error occurred while fetching dependencies for a reason other than I/O.
+     */
+    PomDerivation(final AbstractJarMojo mojo, final List<Path> moduleRoots) throws IOException {
+        this.session = mojo.session;
+        projectModel = mojo.project.getModel();
+        coordinateFactory = session.getService(DependencyCoordinatesFactory.class);
+        DependencyResolver resolver = session.getService(DependencyResolver.class);
+        DependencyResolverResult result = resolver.resolve(DependencyResolverRequest.builder()
+                .session(session)
+                .project(mojo.project)
+                .requestType(DependencyResolverRequest.RequestType.RESOLVE)
+                .pathScope(mojo.getDependencyScope())
+                .pathTypeFilter(Set.of(JavaPathType.MODULES, JavaPathType.CLASSES))
+                .build());
+
+        rethrow(result);
+        final Map<org.apache.maven.api.Dependency, Path> dependencies = result.getDependencies();
+        final Path[] allModulePaths = toRealPaths(moduleRoots, dependencies.values());
+        fromURI = new HashMap<>(allModulePaths.length); // TODO: use newHashMap with JDK19.
+        moduleFinder = ModuleFinder.of(allModulePaths);
+        if (moduleFinder != null) {
+            for (ModuleReference reference : moduleFinder.findAll()) {
+                reference.location().ifPresent((location) -> fromURI.put(location, reference));
+            }
+        }
+        fromDependency = new HashMap<>(dependencies.size()); // TODO: use newHashMap with JDK19.
+        for (Map.Entry<org.apache.maven.api.Dependency, Path> entry : dependencies.entrySet()) {
+            Path modulePath = entry.getValue().toRealPath();
+            ModuleReference reference = fromURI.get(modulePath.toUri());
+            if (reference != null) {
+                DependencyCoordinates coordinates = entry.getKey().toCoordinates();
+                String id = coordinates.getId();
+                ModuleReference old = fromDependency.putIfAbsent(id, reference);
+                if (old == null) {
+                    coordinates = withoutVersion(coordinates);
+                    id = coordinates.getId();
+                    old = fromDependency.putIfAbsent(id, reference);
+                }
+                if (old != null && !old.equals(reference)) {
+                    mojo.log.warn("The \"" + id + "\" dependency is declared twice with different module names: \""
+                            + old.descriptor().name() + "\" and \""
+                            + reference.descriptor().name() + "\".");
+                }
+            }
+        }
+        builtModules = new HashMap<>(moduleRoots.size()); // TODO: use newHashMap with JDK19.
+        for (Path root : moduleRoots) {
+            ModuleDescriptor descriptor = fromURI.get(root.toUri()).descriptor();
+            builtModules.put(
+                    descriptor.name(),
+                    Dependency.newBuilder()
+                            .groupId(projectModel.getGroupId())
+                            .artifactId(descriptor.name())
+                            .version(projectModel.getVersion())
+                            .type(Type.MODULAR_JAR)
+                            .build());
+        }
+    }
+
+    /**
+     * Rebuilds the given dependency coordinates without version.
+     *
+     * Note: I'm not sure if it is necessary. This is done in case version numbers are not resolved
+     * in the dependencies of the model returned by {@code Project.getModel()}, or are not resolved
+     * in the same way as what we get from {@link DependencyResolver}.
+     */
+    private DependencyCoordinates withoutVersion(DependencyCoordinates coordinates) {
+        return coordinateFactory.create(DependencyCoordinatesFactoryRequest.builder()
+                .session(session)
+                .groupId(coordinates.getGroupId())
+                .artifactId(coordinates.getArtifactId())
+                .extension(coordinates.getExtension())
+                .classifier(coordinates.getClassifier())
+                .build());
+    }
+
+    /**
+     * If the resolver failed, propagates its exception.
+     *
+     * @param result the resolver result
+     * @throws IOException if the result contains an I/O error
+     */
+    private static void rethrow(DependencyResolverResult result) throws IOException {
+        Exception exception = null;
+        for (Exception cause : result.getExceptions()) {
+            if (cause instanceof UncheckedIOException e) {
+                cause = e.getCause();
+            }
+            if (exception != null) {
+                exception.addSuppressed(cause);
+            } else if (cause instanceof RuntimeException || cause instanceof IOException) {
+                exception = cause;
+            } else {
+                exception = new MojoException("Cannot collect the runtime dependencies.", cause);
+            }
+        }
+        if (exception != null) {
+            if (exception instanceof IOException e) {
+                throw e;
+            } else {
+                throw (RuntimeException) exception; // A ClassCastException here would be a bug in above loop.
+            }
+        }
+    }
+
+    /**
+     * Returns the real paths of the given collections, in iteration order and without duplicated values.
+     */
+    private static Path[] toRealPaths(Collection<Path> moduleRoots, Collection<Path> dependencies) throws IOException {
+        // TODO: use newLinkedHashSet(int) after we are allowed to compile for JDK19.
+        final var paths = new LinkedHashSet<Path>(moduleRoots.size() + dependencies.size());
+        for (Path path : moduleRoots) {
+            paths.add(path.toRealPath());
+        }
+        for (Path path : dependencies) {
+            paths.add(path.toRealPath());
+        }
+        return paths.toArray(Path[]::new);
+    }
+
+    /**
+     * Returns the module descriptor for the {@code module-info.class} at the given path.
+     *
+     * @param moduleInfo path to a {@code module-info.class} file
+     * @return module descriptor for the specified file
+     * @throws IOException if an error occurred while reading the file
+     */
+    private ModuleDescriptor findModuleDescriptor(Path moduleInfo) throws IOException {
+        Path directory = moduleInfo.toRealPath().getParent();
+        ModuleReference reference = fromURI.get(directory.toUri());
+        if (reference != null) {
+            return reference.descriptor();
+        }
+        try (InputStream in = new BufferedInputStream(Files.newInputStream(moduleInfo))) {
+            return ModuleDescriptor.read(in);
+        }
+    }
+
+    /**
+     * Returns the module descriptor for the specified Maven dependency.
+     *
+     * @param dependency dependency for which to get the module descriptor
+     * @return Java module descriptor for the given Maven dependency
+     */
+    private Optional<ModuleDescriptor> findModuleDescriptor(Dependency dependency) {
+        DependencyCoordinates coordinates = coordinateFactory.create(session, dependency);
+        ModuleReference reference = fromDependency.get(coordinates.getId());
+        if (reference == null) {
+            coordinates = withoutVersion(coordinates);
+            reference = fromDependency.get(coordinates.getId());
+            if (reference == null) {
+                return Optional.empty();
+            }
+        }
+        return Optional.of(reference.descriptor());
+    }
+
+    /**
+     * Returns the module descriptor for the specified module name.
+     *
+     * @param moduleName name of the module for which to get the descriptor
+     * @return module descriptor for the specified module name
+     */
+    private Optional<ModuleDescriptor> findModuleDescriptor(String moduleName) {
+        if (moduleFinder == null) {
+            return Optional.empty();
+        }
+        return moduleFinder.find(moduleName).map(ModuleReference::descriptor);
+    }
+
+    /**
+     * Derives a <abbr>POM</abbr> as the intersection of the consumer <abbr>POM</abbr>
+     * and the dependencies required by {@code module-info}.
+     */
+    final class ForModule {
+        /**
+         * Value of the {@code <name>} element in the derived <abbr>POM</abbr>, or {@code null} if none.
+         */
+        private String name;
+
+        /**
+         * Name of the module for which to derive a <abbr>POM</abbr> file.
+         */
+        private final String moduleName;
+
+        /**
+         * Whether a dependency is optional or required only at runtime.
+         */
+        private enum Modifier {
+            OPTIONAL,
+            RUNTIME
+        }
+
+        /**
+         * The required dependencies as Java module names, including transitive dependencies.
+         * Values tell whether the dependency is optional or should have runtime scope.
+         */
+        private final Map<String, EnumSet<Modifier>> requires;
+
+        /**
+         * Path to the <abbr>POM</abbr> file written by this class.
+         */
+        final Path pomFile;
+
+        /**
+         * Creates a new <abbr>POM</abbr> generator for the given archive.
+         *
+         * @param archive the archive for which to generate a <abbr>POM</abbr>
+         * @param manifest manifest to use for deriving project name, or {@code null} if none
+         * @throws IOException if an error occurred while reading the {@code module-info.class} file
+         */
+        ForModule(final Archive archive, final Manifest manifest) throws IOException {
+            moduleName = archive.moduleName;
+            pomFile = derivePathToPOM(archive.jarFile);
+            requires = new LinkedHashMap<>();
+            for (Path file : archive.moduleInfoFiles()) {
+                addDependencies(findModuleDescriptor(file), EnumSet.noneOf(Modifier.class));
+            }
+            if (manifest != null) {
+                name = (String) manifest.getMainAttributes().get(Attributes.Name.IMPLEMENTATION_TITLE);
+                if (name == null) {
+                    name = (String) manifest.getMainAttributes().get(Attributes.Name.SPECIFICATION_TITLE);
+                }
+            }
+        }
+
+        /**
+         * Add the dependencies of the given module, including transitive dependencies.
+         * If the same dependency is added twice with different optional flags,
+         * the {@code false} value (i.e., mandatory dependency) has precedence.
+         *
+         * @param descriptor description of the module for which to add dependencies
+         * @param parentModifiers modifiers of the parent module for which this method adds dependencies
+         */
+        private void addDependencies(final ModuleDescriptor descriptor, final EnumSet<Modifier> parentModifiers) {
+            for (ModuleDescriptor.Requires r : descriptor.requires()) {
+                final EnumSet<Modifier> modifiers = parentModifiers.clone();
+                if (r.modifiers().contains(ModuleDescriptor.Requires.Modifier.STATIC)) {
+                    modifiers.add(Modifier.OPTIONAL);
+                }
+                if (!r.modifiers().contains(ModuleDescriptor.Requires.Modifier.TRANSITIVE)) {
+                    modifiers.add(Modifier.RUNTIME);
+                }
+                EnumSet<Modifier> current = requires.computeIfAbsent(r.name(), (key) -> modifiers);
+                if (EXPAND_TRANSITIVE && (current == modifiers || current.retainAll(modifiers))) {
+                    // Transitive dependencies if not already added or if it needs to update modifiers.
+                    findModuleDescriptor(r.name()).ifPresent((td) -> addDependencies(td, modifiers));
+                }
+            }
+        }
+
+        /**
+         * Derives a <abbr>POM</abbr> file for the archive specified ad construction time.
+         *
+         * @throws IOException if an error occurred while writing the <abbr>POM</abbr> file
+         *
+         * @see #writeParentPOM(Archive)
+         */
+        void writeModulePOM() throws IOException {
+            try {
+                writePOM(deriveModulePOM(), pomFile);
+            } catch (ModelBuilderException | XMLStreamException e) {
+                throw new MojoException("Cannot derive a POM file for the \"" + moduleName + "\" module.", e);
+            }
+        }
+
+        /**
+         * Derives the module <abbr>POM</abbr> file as the intersection of the project <abbr>POM</abbr> and the archive.
+         *
+         * @return intersection of {@link #projectModel} and {@code module-info.class}
+         * @throws ModelBuilderException if an error occurred while building the model
+         */
+        private Model deriveModulePOM() throws ModelBuilderException {
+            Model.Builder builder = Model.newBuilder()
+                    .modelVersion("4.0.0")
+                    .groupId(projectModel.getGroupId())
+                    .artifactId(moduleName)
+                    .version(projectModel.getVersion())
+                    .parent(Parent.newBuilder()
+                            .groupId(projectModel.getGroupId())
+                            .artifactId(projectModel.getArtifactId())
+                            .version(projectModel.getVersion())
+                            .build());
+            if (name != null) {
+                builder = builder.name(name);
+            }
+            /*
+             * Filter the dependencies by keeping only the one declared in a `requires` statement of the
+             * `module-info.class` of the module that we are archiving. Also adjust the `<optional>` and
+             * `<scope>` values. The dependencies that we found are removed from the `requires` map as a
+             * way to make sure that we do not add them twice. In principle, the map should become empty
+             * at the end of this loop.
+             */
+            final List<Dependency> dependencies = projectModel.getDependencies();
+            if (dependencies != null) {
+                final var filteredDependencies = new ArrayList<Dependency>(dependencies.size());
+                for (var iterator = requires.entrySet().iterator(); iterator.hasNext(); ) {
+                    Map.Entry<String, EnumSet<Modifier>> entry = iterator.next();
+                    Dependency dependency = builtModules.get(entry.getKey());
+                    if (dependency != null) {
+                        filteredDependencies.add(amend(dependency, entry.getValue()));
+                        iterator.remove();
+                    }
+                }
+                for (Dependency dependency : dependencies) {
+                    String dependencyModuleName = findModuleDescriptor(dependency)
+                            .map(ModuleDescriptor::name)
+                            .orElse(null);
+                    /*
+                     * If `dependencyModuleName` is null, then the dependency scope is "test" or some other scope
+                     * that resolver has chosen to exclude. Note that this is true even for JAR on the classpath,
+                     * because we stored the automatic module name in `PomDerivation`. Next, if `modifiers` is null,
+                     * then the dependency has compile or runtime scope but is not used by the module to archive.
+                     */
+                    if (dependencyModuleName != null) {
+                        EnumSet<Modifier> modifiers = requires.remove(dependencyModuleName);
+                        if (modifiers != null) {
+                            filteredDependencies.add(amend(dependency, modifiers));
+                        }
+                    }
+                }
+                builder.dependencies(filteredDependencies);
+            }
+            /*
+             * Replace the `<name>` element by the equivalent value defined in MANIFEST.MF.
+             * We do this replacement because the `<name>` of the project model applies to all modules,
+             * while the MANIFEST.MF has more chances to be specific to the module that we are archiving.
+             */
+            return builder.build();
+        }
+
+        /**
+         * Modifies the optional and scope elements of the given dependency according the given modifiers.
+         *
+         * @param dependency the dependency to amend
+         * @param modifiers the modifiers to apply
+         * @return the amended dependency
+         */
+        private static Dependency amend(Dependency dependency, EnumSet<Modifier> modifiers) {
+            String scope = modifiers.contains(Modifier.RUNTIME) ? "runtime" : null;
+            if (!Objects.equals(scope, dependency.getScope())) {
+                dependency = dependency.withScope(scope);
+            }
+            boolean optional = modifiers.contains(Modifier.OPTIONAL);
+            if (Boolean.parseBoolean(dependency.getOptional()) != optional) {
+                dependency = dependency.withOptional(Boolean.toString(optional));
+            }
+            return dependency;
+        }
+    }
+
+    /**
+     * Writes the parent <abbr>POM</abbr> file as the project file but without the dependencies.
+     * The dependencies are removed because they will declared on a module-by-module basis.
+     *
+     * @param packageHierarchy value of {@link FileCollector#packageHierarchy}
+     * @return path to the file that has been written
+     * @throws IOException if an I/O error occurred while writing the model
+     *
+     * @see ForModule#writeModulePOM()
+     */
+    Path writeParentPOM(final Archive packageHierarchy) throws IOException {
+        Path pomFile = derivePathToPOM(packageHierarchy.jarFile);
+        Model.Builder builder = Model.newBuilder(projectModel, true);
+        builder = builder.root(false).modules(null).subprojects(null);
+        builder = builder.dependencies(null).build(null).reporting(null).distributionManagement(null);

Review Comment:
   deprecation



##########
src/test/java/org/apache/maven/plugins/jar/ArchiveTest.java:
##########
@@ -0,0 +1,264 @@
+/*
+ * 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.jar;
+
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Unit tests for {@link Archive}, focused on the two behaviours that are otherwise only
+ * exercised by integration tests whose outcome depends on the (unspecified) filesystem
+ * directory-iteration order, and therefore pass on some platforms while failing on others.
+ */
+class ArchiveTest {
+
+    /**
+     * Creates an {@code Archive} suitable for a unit test. {@code forceCreation = true} skips the
+     * existing-JAR timestamp check, so the (here {@code null}) logger is never dereferenced.
+     */
+    private static Archive archive(String moduleName, Runtime.Version version, Path directory, boolean isReproducible) {
+        return new Archive(directory.resolve("out.jar"), moduleName, version, directory, true, isReproducible, null);
+    }
+
+    /**
+     * Creates a manifest with the main class attribute set to the given value.
+     *
+     * @param value value of the main class attribute
+     * @return a new manifest with the given attribute value
+     */
+    private static Manifest manifestWithMainClass(String value) {
+        Manifest m = new Manifest();
+        Attributes attributes = m.getMainAttributes();
+        attributes.put(Attributes.Name.MANIFEST_VERSION, "1.0");
+        attributes.put(Attributes.Name.MAIN_CLASS, value);
+        return m;
+    }
+
+    /**
+     * Returns the value of the main class attribute.
+     *
+     * @param m the manifest from which to get the value
+     * @return the main class attribute value, or {@code null} if none
+     */
+    private static Object mainClassOf(Manifest m) {
+        return m.getMainAttributes().get(Attributes.Name.MAIN_CLASS);
+    }
+
+    /**
+     * Verifies that {@link Archive#setMainClass(Manifest)} takes ownership for a module-qualified
+     * {@code "module/Class"} main class.
+     *
+     * Note that the {@code "foo.bar/"} prefix in this test (the module name) is a Maven extension.
+     * The standard <abbr>JAR</abbr> specification accepts only the {@code "foo.MainFile"} class name.
+     */
+    @Test
+    void owningModuleClaimsMainClassAndRemovesItFromManifest() {
+        Archive owner = archive("foo.bar", null, Path.of("."), false);
+        Manifest m = manifestWithMainClass("foo.bar/foo.MainFile");
+        // The owner keeps the main class (emitted via --main-class) ...
+        assertTrue(owner.setMainClass(m));
+        // ... and the raw `module/Class` value is removed from the written manifest.
+        assertNull(mainClassOf(m));
+    }
+
+    /**
+     * Verifies that {@link Archive#setMainClass(Manifest)} does <em>not</em> take ownership fo
+     * a module-qualified {@code "module/Class"} main class when the module name does not match.
+     * Note that the {@code "foo.bar/"} prefix in this test (the module name) is a Maven extension.
+     * The standard <abbr>JAR</abbr> specification accepts only the {@code "foo.MainFile"} class name.
+     */
+    @Test
+    void nonOwningModuleRejectsMainClass() {
+        Archive nonOwner = archive("foo.bar.more", null, Path.of("."), false);
+        Manifest m = manifestWithMainClass("foo.bar/foo.MainFile");
+        assertFalse(nonOwner.setMainClass(m));
+        assertNull(mainClassOf(m));
+    }
+
+    /**
+     * Tests that which module keeps the main class must not depend on processing order.

Review Comment:
   must not --> does not



##########
src/test/java/org/apache/maven/plugins/jar/ArchiveTest.java:
##########
@@ -0,0 +1,264 @@
+/*
+ * 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.jar;
+
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Unit tests for {@link Archive}, focused on the two behaviours that are otherwise only
+ * exercised by integration tests whose outcome depends on the (unspecified) filesystem
+ * directory-iteration order, and therefore pass on some platforms while failing on others.
+ */
+class ArchiveTest {
+
+    /**
+     * Creates an {@code Archive} suitable for a unit test. {@code forceCreation = true} skips the
+     * existing-JAR timestamp check, so the (here {@code null}) logger is never dereferenced.
+     */
+    private static Archive archive(String moduleName, Runtime.Version version, Path directory, boolean isReproducible) {
+        return new Archive(directory.resolve("out.jar"), moduleName, version, directory, true, isReproducible, null);
+    }
+
+    /**
+     * Creates a manifest with the main class attribute set to the given value.
+     *
+     * @param value value of the main class attribute
+     * @return a new manifest with the given attribute value
+     */
+    private static Manifest manifestWithMainClass(String value) {
+        Manifest m = new Manifest();
+        Attributes attributes = m.getMainAttributes();
+        attributes.put(Attributes.Name.MANIFEST_VERSION, "1.0");
+        attributes.put(Attributes.Name.MAIN_CLASS, value);
+        return m;
+    }
+
+    /**
+     * Returns the value of the main class attribute.
+     *
+     * @param m the manifest from which to get the value
+     * @return the main class attribute value, or {@code null} if none
+     */
+    private static Object mainClassOf(Manifest m) {
+        return m.getMainAttributes().get(Attributes.Name.MAIN_CLASS);
+    }
+
+    /**
+     * Verifies that {@link Archive#setMainClass(Manifest)} takes ownership for a module-qualified
+     * {@code "module/Class"} main class.
+     *
+     * Note that the {@code "foo.bar/"} prefix in this test (the module name) is a Maven extension.
+     * The standard <abbr>JAR</abbr> specification accepts only the {@code "foo.MainFile"} class name.
+     */
+    @Test
+    void owningModuleClaimsMainClassAndRemovesItFromManifest() {
+        Archive owner = archive("foo.bar", null, Path.of("."), false);
+        Manifest m = manifestWithMainClass("foo.bar/foo.MainFile");
+        // The owner keeps the main class (emitted via --main-class) ...
+        assertTrue(owner.setMainClass(m));
+        // ... and the raw `module/Class` value is removed from the written manifest.
+        assertNull(mainClassOf(m));
+    }
+
+    /**
+     * Verifies that {@link Archive#setMainClass(Manifest)} does <em>not</em> take ownership fo
+     * a module-qualified {@code "module/Class"} main class when the module name does not match.
+     * Note that the {@code "foo.bar/"} prefix in this test (the module name) is a Maven extension.

Review Comment:
   delete "Note that"



##########
src/test/java/org/apache/maven/plugins/jar/ArchiveTest.java:
##########
@@ -0,0 +1,264 @@
+/*
+ * 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.jar;
+
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Unit tests for {@link Archive}, focused on the two behaviours that are otherwise only
+ * exercised by integration tests whose outcome depends on the (unspecified) filesystem
+ * directory-iteration order, and therefore pass on some platforms while failing on others.
+ */
+class ArchiveTest {
+
+    /**
+     * Creates an {@code Archive} suitable for a unit test. {@code forceCreation = true} skips the
+     * existing-JAR timestamp check, so the (here {@code null}) logger is never dereferenced.
+     */
+    private static Archive archive(String moduleName, Runtime.Version version, Path directory, boolean isReproducible) {
+        return new Archive(directory.resolve("out.jar"), moduleName, version, directory, true, isReproducible, null);
+    }
+
+    /**
+     * Creates a manifest with the main class attribute set to the given value.
+     *
+     * @param value value of the main class attribute
+     * @return a new manifest with the given attribute value
+     */
+    private static Manifest manifestWithMainClass(String value) {
+        Manifest m = new Manifest();
+        Attributes attributes = m.getMainAttributes();
+        attributes.put(Attributes.Name.MANIFEST_VERSION, "1.0");
+        attributes.put(Attributes.Name.MAIN_CLASS, value);
+        return m;
+    }
+
+    /**
+     * Returns the value of the main class attribute.
+     *
+     * @param m the manifest from which to get the value
+     * @return the main class attribute value, or {@code null} if none
+     */
+    private static Object mainClassOf(Manifest m) {
+        return m.getMainAttributes().get(Attributes.Name.MAIN_CLASS);
+    }
+
+    /**
+     * Verifies that {@link Archive#setMainClass(Manifest)} takes ownership for a module-qualified
+     * {@code "module/Class"} main class.
+     *
+     * Note that the {@code "foo.bar/"} prefix in this test (the module name) is a Maven extension.
+     * The standard <abbr>JAR</abbr> specification accepts only the {@code "foo.MainFile"} class name.
+     */
+    @Test
+    void owningModuleClaimsMainClassAndRemovesItFromManifest() {
+        Archive owner = archive("foo.bar", null, Path.of("."), false);
+        Manifest m = manifestWithMainClass("foo.bar/foo.MainFile");
+        // The owner keeps the main class (emitted via --main-class) ...
+        assertTrue(owner.setMainClass(m));
+        // ... and the raw `module/Class` value is removed from the written manifest.
+        assertNull(mainClassOf(m));
+    }
+
+    /**
+     * Verifies that {@link Archive#setMainClass(Manifest)} does <em>not</em> take ownership fo

Review Comment:
   fo --> of



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3844194335


##########
src/main/java/org/apache/maven/plugins/jar/MetadataFiles.java:
##########
@@ -0,0 +1,250 @@
+/*
+ * 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.jar;
+
+import java.io.BufferedWriter;
+import java.io.Closeable;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Properties;
+import java.util.jar.Manifest;
+import java.util.stream.Collectors;
+
+import org.apache.maven.api.ProducedArtifact;
+import org.apache.maven.api.Project;
+import org.apache.maven.shared.archiver.MavenArchiveConfiguration;
+
+/**
+ * Temporary metadata files generated by Maven before inclusion in the archive.
+ * Those files are created in a temporary {@code META-INF} directory when first needed.
+ * Those files are deleted after the build, unless the build failed or Maven was run in verbose mode.
+ */
+final class MetadataFiles implements Closeable {
+    /**
+     * The {@value} directory.
+     * This is part of <abbr>JAR</abbr> file specification.
+     */
+    static final String META_INF = "META-INF";
+
+    /**
+     * The {@value} file.
+     * This is part of <abbr>JAR</abbr> file specification.
+     */
+    static final String MANIFEST = "MANIFEST.MF";
+
+    /**
+     * The subdirectory where to add Maven-specific files.
+     */
+    static final String MAVEN_DIR = "maven";
+
+    /**
+     * The project for which to write metadata files.
+     */
+    private final Project project;
+
+    /**
+     * The output directory (usually {@code ${baseDir}/target/}).
+     */
+    private final Path buildDir;
+
+    /**
+     * All files and directories in the order that they were created.
+     * The first element of this list shall be the root temporary directory created by this class.
+     */
+    private final List<Path> filesToDelete;
+
+    /**
+     * The <abbr>POM</abbr> file to attach to the artifact. This is initially the project <abbr>POM</abbr>,
+     * but will be replaced by a new file generated by {@link ForModule} if module hierarchy is used.
+     * That file may be copied verbatim in the {@code META-INF/maven/} directory of the <abbr>JAR</abbr>.
+     */
+    private Path attachedPOM;
+
+    /**
+     * Creates an initially empty set of temporary metadata files.
+     *
+     * @param project the project for which to write metadata files
+     * @param buildDir the (usually) {@code ${baseDir}/target/} directory
+     */
+    MetadataFiles(Project project, Path buildDir) {
+        this.project = project;
+        this.buildDir = buildDir;
+        filesToDelete = new ArrayList<>();
+        attachedPOM = project.getPomPath();
+    }
+
+    /**
+     * Derives a <abbr>POM</abbr> as the intersection of the given {@code model} and {@code archive}.
+     *
+     * @param context the tool executor which is generating all archives
+     * @param archive the archive for which to generate a <abbr>POM</abbr>
+     * @param manifest manifest to use for deriving project name, or {@code null} if none
+     * @throws IOException if an error occurred while reading the {@code module-info.class} file
+     *         or while writing the <abbr>POM</abbr> file
+     */
+    void deriveModulePOM(ToolExecutor context, Archive archive, Manifest manifest) throws IOException {
+        var pom = context.pomDerivation.new ForModule(archive, manifest);
+        pom.writeModulePOM();
+        attachedPOM = pom.pomFile;
+        archive.pomFile = pom.pomFile;
+    }
+
+    /**
+     * Adds the given manifest in a temporary file.
+     * The file will be deleted when {@link #close()} is invoked.
+     *
+     * @param manifest the manifest to write
+     * @return the temporary manifest file
+     * @throws IOException if an error occurred while writing the file
+     */
+    public Path addManifest(final Manifest manifest) throws IOException {
+        Path file = baseDirectory().resolve(MANIFEST);
+        try (OutputStream out = Files.newOutputStream(file)) {
+            filesToDelete.add(file);
+            manifest.write(out);
+        }
+        return file;
+    }
+
+    /**
+     * {@return the root temporary directory for the files created by this class}
+     * The directory is created the first time that this method is invoked.
+     *
+     * @throws IOException if an error occurred while creating the temporary directory
+     */
+    private Path baseDirectory() throws IOException {
+        if (filesToDelete.isEmpty()) {
+            filesToDelete.add(Files.createTempDirectory(buildDir, "classes-"));
+        }
+        return filesToDelete.get(0);
+    }
+
+    /**
+     * Creates a new directory and adds it to the list of files to delete after the build.
+     *
+     * @param dir the existing directory where to create a sub-directory
+     * @param path path to the subdirectory to create
+     * @return the new directory
+     * @throws IOException if an error occurred while creating the subdirectory
+     */
+    private Path createDirectories(Path dir, String... path) throws IOException {
+        for (String subdir : path) {
+            dir = Files.createDirectory(dir.resolve(subdir));
+            filesToDelete.add(dir);
+        }
+        return dir;
+    }
+
+    /**
+     * Writes the {@code pom.xml} and {@code pom.properties} files.
+     * This method returns the base temporary directory followed by files that the "jar" tool will need to add
+     *
+     * @param archive archive configuration
+     * @param reproducible whether to enforce reproducible build
+     * @return arguments for the "jar" tool
+     * @throws IOException if an error occurred while writing the files
+     */
+    public List<Path> addPOM(final MavenArchiveConfiguration archive, final boolean reproducible) throws IOException {
+        final String groupId = project.getGroupId();
+        final String artifactId = project.getArtifactId();
+        final String version;
+        final ProducedArtifact pom = project.getPomArtifact();
+        if (pom.isSnapshot()) {
+            version = pom.getVersion().toString();
+        } else {
+            version = project.getVersion();
+        }
+        final Path baseDir = baseDirectory();
+        final Path mavenDir = createDirectories(baseDir, META_INF, MAVEN_DIR, groupId, artifactId);
+        final Path pomFile = linkOrCopy(attachedPOM, mavenDir.resolve("pom.xml"));
+        filesToDelete.add(pomFile); // Add soon for deleting this file even if an exception is thrown below.
+        /*
+         * Subset of above "pom.xml" file but written as a properties file.
+         * If reproducible build is enabled, we will need to reformat after
+         * writing for ensuring a deterministic order of entries.
+         */
+        final var properties = new Properties();
+        Path propertiesFile = archive.getPomPropertiesFile();
+        if (propertiesFile != null) {
+            try (InputStream in = Files.newInputStream(propertiesFile)) {
+                properties.load(in);
+            }
+        }
+        properties.setProperty("groupId", groupId);
+        properties.setProperty("artifactId", artifactId);
+        properties.setProperty("version", version);
+        propertiesFile = mavenDir.resolve("pom.properties");
+        try (BufferedWriter out = Files.newBufferedWriter(propertiesFile)) {
+            filesToDelete.add(propertiesFile); // Add soon for deleting this file even if an exception is thrown below.
+            properties.store(out, "Subset of pom.xml");
+        }
+        if (reproducible) {
+            // The encoding can be either UTF-8 or ISO-8859-1, as any non ASCII character
+            // is transformed into a \\uxxxx sequence anyway.
+            Files.writeString(
+                    propertiesFile,
+                    Files.lines(propertiesFile)
+                            .filter(line -> !line.startsWith("#"))
+                            .sorted()
+                            .collect(Collectors.joining("\n", "", "\n"))); // system independent new line.
+        }
+        return List.of(baseDir, Path.of(META_INF, MAVEN_DIR));
+    }
+
+    /**
+     * Creates a link to the given source if supported, or copies the file otherwise.
+     *
+     * @param source the source file to link or copy
+     * @param target the file to create
+     * @return the target file which should be deleted after the build
+     */
+    private static Path linkOrCopy(final Path source, final Path target) throws IOException {
+        try {
+            return Files.createLink(target, source);
+        } catch (UnsupportedOperationException e) {

Review Comment:
   Applied.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3858055456


##########
src/main/java/org/apache/maven/plugins/jar/ExcludedFiles.java:
##########
@@ -0,0 +1,129 @@
+/*
+ * 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.jar;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardCopyOption;
+import java.util.List;
+
+/**
+ * A list of files to temporarily move outside the directory to package in a <abbr>JAR</abbr> archive.
+ * This is used for excluding files from the <abbr>JAR</abbr> archive according include/exclude filters.
+ * We move these files for making possible to specify the whole directory to the {@code jar} tool.
+ * This approach is used instead of enumerating files in arguments given to the {@code jar} tool because
+ * such enumeration can not contain directory entries (otherwise the whole directory would be included).
+ * Some software such as Spring applications component scan relies on the presence of directory entries.
+ */
+final class ExcludedFiles implements Closeable {
+    /**
+     * The paths of files or directories to temporarily move in another directory.
+     */
+    private final Path[] original;
+
+    /**
+     * The paths where files or directories were moved.
+     * For each index <var>i</var>, the original path of {@code moved[i]} was {@code original[i]}.
+     */
+    private final Path[] moved;
+
+    /**
+     * Temporary directory which will contain the {@code moved} files.
+     * It should be a parent directory of {@link #original} files for
+     * increasing the chances that it is on the same file system.
+     */
+    private final Path temporaryDirectory;
+
+    /**
+     * Creates a new list of files to move in a temporary directory.
+     *
+     * @param directory the directory which was scanned for files to include in the <abbr>JAR</abbr>
+     * @param files paths of files or directories to temporarily move in another directory
+     * @throws IOException if an error occurred while creating the temporary directory.
+     */
+    ExcludedFiles(final Path directory, final List<Path> files) throws IOException {
+        original = files.toArray(Path[]::new);
+        moved = new Path[original.length];
+        temporaryDirectory = Files.createTempDirectory(directory, "excluded-");
+    }
+
+    /**
+     * Moves the files now. This method should be invoked inside the "try with resource" block.
+     *
+     * @throws IOException if an error occurred while moving a file.
+     */
+    public void move() throws IOException {
+        for (int i = 0; i < original.length; i++) {
+            final Path source = original[i];
+            String prefix = source.getFileName().toString();
+            String suffix = null;
+            int s = prefix.lastIndexOf('.');
+            if (s > 0) {
+                suffix = prefix.substring(s);
+                prefix = prefix.substring(0, s);
+            }
+            Path target = Files.createTempFile(temporaryDirectory, prefix, suffix);
+            try {
+                moved[i] = Files.move(source, target, StandardCopyOption.REPLACE_EXISTING);

Review Comment:
   Fixed by storing files and directories in two separated lists, so we can know whether to use `createTempFile` or `createTempDirectory` without the need to invoke `Files.isDirectory`.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3855150568


##########
src/main/java/org/apache/maven/plugins/jar/AbstractJarMojo.java:
##########
@@ -207,167 +206,209 @@ protected final Log getLog() {
     protected abstract String getType();
 
     /**
-     * Returns the JAR file to generate, based on an optional classifier.
+     * {@return the scope of dependencies}
+     * It should be {@link PathScope#MAIN_COMPILE} or {@link PathScope#TEST_COMPILE}.
+     * Note that we use compile scope rather than runtime scope because dependencies
+     * cannot appear in {@code requires} statement if they didn't had compile scope.
+     */
+    protected abstract PathScope getDependencyScope();
+
+    /**
+     * {@return the JAR tool to use for archiving the code}
      *
-     * @param basedir the output directory
-     * @param resultFinalName the name of the JAR file
-     * @param classifier an optional classifier
-     * @return the file to generate
+     * @throws MojoException if no JAR tool was found
+     *
+     * @since 4.0.0-beta-2
      */
-    protected Path getJarFile(Path basedir, String resultFinalName, String classifier) {
-        Objects.requireNonNull(basedir, "basedir is not allowed to be null");
-        Objects.requireNonNull(resultFinalName, "finalName is not allowed to be null");
-        String fileName = resultFinalName + (hasClassifier(classifier) ? '-' + classifier : "") + ".jar";
-        return basedir.resolve(fileName);
+    protected ToolProvider getJarTool() throws MojoException {
+        return ToolProvider.findFirst(toolId).orElseThrow(() -> new MojoException("No such \"" + toolId + "\" tool."));
     }
 
     /**
-     * Generates the JAR.
+     * Returns the output time stamp or, as a fallback, the {@code SOURCE_DATE_EPOCH} environment variable.
+     * If the time stamp is expressed in seconds, it is converted to ISO 8601 format. Otherwise it is returned as-is.
      *
-     * @return the path to the created archive file
-     * @throws MojoException in case of an error
+     * @return the time stamp in presumed ISO 8601 format, or {@code null} if none
+     * @throws MojoException if the timestamp looks like a number of seconds but cannot be parsed as such
+     *
+     * @since 4.0.0-beta-2
      */
-    public Path createArchive() throws MojoException {
-        Path basedir = outputDirectory != null
-                ? outputDirectory
-                : Path.of(project.getBuild().getDirectory());
-        String resultFinalName =
-                finalName != null ? finalName : project.getBuild().getFinalName();
-        Path jarFile = getJarFile(basedir, resultFinalName, getClassifier());
-
-        FileSetManager fileSetManager = new FileSetManager();
-        FileSet jarContentFileSet = new FileSet();
-        jarContentFileSet.setDirectory(getClassesDirectory().toAbsolutePath().toString());
-        jarContentFileSet.setIncludes(Arrays.asList(getIncludes()));
-        jarContentFileSet.setExcludes(Arrays.asList(getExcludes()));
-
-        String[] includedFiles = fileSetManager.getIncludedFiles(jarContentFileSet);
-
-        if (detectMultiReleaseJar
-                && Arrays.stream(includedFiles)
-                        .anyMatch(
-                                p -> p.startsWith("META-INF" + File.separatorChar + "versions" + File.separatorChar))) {
-            getLog().debug("Adding 'Multi-Release: true' manifest entry.");
-            archive.addManifestEntry(Attributes.Name.MULTI_RELEASE.toString(), "true");
+    protected String getOutputTimestamp() {

Review Comment:
   Because it returns a `String` instead of an `Instant`. The `String` is the type of argument expected by the `jar` tool. By passing the string without going through a round of "parsing as an `Instant` then reformat as a `String`" (except for the case of number of seconds), we let the `jar` tool decide which syntax it accepts.
   
   Another reason is that building the `MANIFEST.MF` content is the only `MavenArchiver` service that the plugin is still using, and that service could be take in charge by the plugin itself in a future commit. In such case, the dependency to Maven Archiver could be removed.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3858087127


##########
src/main/java/org/apache/maven/plugins/jar/PomDerivation.java:
##########
@@ -0,0 +1,528 @@
+/*
+ * 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.jar;
+
+import javax.xml.stream.XMLStreamException;
+
+import java.io.BufferedInputStream;
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.UncheckedIOException;
+import java.lang.module.ModuleDescriptor;
+import java.lang.module.ModuleFinder;
+import java.lang.module.ModuleReference;
+import java.net.URI;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.DependencyCoordinates;
+import org.apache.maven.api.JavaPathType;
+import org.apache.maven.api.Session;
+import org.apache.maven.api.Type;
+import org.apache.maven.api.model.Dependency;
+import org.apache.maven.api.model.Model;
+import org.apache.maven.api.model.Parent;
+import org.apache.maven.api.plugin.MojoException;
+import org.apache.maven.api.services.DependencyCoordinatesFactory;
+import org.apache.maven.api.services.DependencyCoordinatesFactoryRequest;
+import org.apache.maven.api.services.DependencyResolver;
+import org.apache.maven.api.services.DependencyResolverRequest;
+import org.apache.maven.api.services.DependencyResolverResult;
+import org.apache.maven.api.services.ModelBuilderException;
+import org.apache.maven.model.v4.MavenStaxWriter;
+
+/**
+ * A mapper from Maven model dependencies to Java module names.
+ * A single instance of this class is created for a Maven project,
+ * then shared by all {@link ForModule} instances (one per module to archive).
+ */
+final class PomDerivation {
+    /**
+     * Whether to expand the list of transitive dependencies in the generated <abbr>POM</abbr>.
+     */
+    private static final boolean EXPAND_TRANSITIVE = false;
+
+    /**
+     * Copy of {@link AbstractJarMojo#session}.
+     */
+    private final Session session;
+
+    /**
+     * The project model, which includes dependencies of all modules.
+     */
+    private final Model projectModel;
+
+    /**
+     * The factory to use for creating temporary {@link DependencyCoordinates} instances.
+     */
+    private final DependencyCoordinatesFactory coordinateFactory;
+
+    /**
+     * Provide module descriptors from module names.
+     * May be {@code null} if no {@code module-info} was found.
+     */
+    private final ModuleFinder moduleFinder;
+
+    /**
+     * Module references from paths to the <abbr>JAR</abbr> file or root directory.
+     */
+    private final Map<URI, ModuleReference> fromURI;
+
+    /**
+     * Module names associated to Maven dependencies.
+     * This map contains {@link DependencyCoordinates#getId()} as keys and module references as values.
+     * This is used for detecting which dependencies are really used according {@code module-info.class}.
+     *
+     * @todo The keys should be instances of {@link DependencyCoordinates}. Unfortunately, as of Maven 4.0.0-rc-5
+     *       that interface does not define the {@code equals} and {@code hashCode} contracts.
+     */
+    private final Map<String, ModuleReference> fromDependency;
+
+    /**
+     * Modules that are built by the project. Keys are module names.
+     */
+    private final Map<String, Dependency> builtModules;
+
+    /**
+     * Creates a new mapper from Maven dependency to module name.
+     *
+     * @param mojo the enclosing <abbr>MOJO</abbr>
+     * @param moduleRoots paths to root directories of each module to archive in a module hierarchy
+     * @throws IOException if an I/O error occurred while fetching dependencies
+     * @throws MavenException if an error occurred while fetching dependencies for a reason other than I/O.
+     */
+    PomDerivation(final AbstractJarMojo mojo, final List<Path> moduleRoots) throws IOException {
+        this.session = mojo.session;
+        projectModel = mojo.project.getModel();
+        coordinateFactory = session.getService(DependencyCoordinatesFactory.class);
+        DependencyResolver resolver = session.getService(DependencyResolver.class);
+        DependencyResolverResult result = resolver.resolve(DependencyResolverRequest.builder()
+                .session(session)
+                .project(mojo.project)
+                .requestType(DependencyResolverRequest.RequestType.RESOLVE)
+                .pathScope(mojo.getDependencyScope())
+                .pathTypeFilter(Set.of(JavaPathType.MODULES, JavaPathType.CLASSES))
+                .build());
+
+        rethrow(result);
+        final Map<org.apache.maven.api.Dependency, Path> dependencies = result.getDependencies();
+        final Path[] allModulePaths = toRealPaths(moduleRoots, dependencies.values());
+        fromURI = new HashMap<>(allModulePaths.length); // TODO: use newHashMap with JDK19.
+        moduleFinder = ModuleFinder.of(allModulePaths);
+        if (moduleFinder != null) {
+            for (ModuleReference reference : moduleFinder.findAll()) {
+                reference.location().ifPresent((location) -> fromURI.put(location, reference));
+            }
+        }
+        fromDependency = new HashMap<>(dependencies.size()); // TODO: use newHashMap with JDK19.
+        for (Map.Entry<org.apache.maven.api.Dependency, Path> entry : dependencies.entrySet()) {
+            Path modulePath = entry.getValue().toRealPath();
+            ModuleReference reference = fromURI.get(modulePath.toUri());
+            if (reference != null) {
+                DependencyCoordinates coordinates = entry.getKey().toCoordinates();
+                String id = coordinates.getId();
+                ModuleReference old = fromDependency.putIfAbsent(id, reference);
+                if (old == null) {
+                    coordinates = withoutVersion(coordinates);
+                    id = coordinates.getId();
+                    old = fromDependency.putIfAbsent(id, reference);
+                }
+                if (old != null && !old.equals(reference)) {
+                    mojo.log.warn("The \"" + id + "\" dependency is declared twice with different module names: \""
+                            + old.descriptor().name() + "\" and \""
+                            + reference.descriptor().name() + "\".");
+                }
+            }
+        }
+        builtModules = new HashMap<>(moduleRoots.size()); // TODO: use newHashMap with JDK19.
+        for (Path root : moduleRoots) {
+            root = root.toRealPath();
+            ModuleDescriptor descriptor = fromURI.get(root.toUri()).descriptor();

Review Comment:
   Actually the `descriptor != null` check was a mistake. The descriptor can never be null. The intent was only to check `ref != null`. Fixed.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "elharo (via GitHub)" <gi...@apache.org>.
elharo commented on PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#issuecomment-5332102682

   > We may not be able to enable reproducible build at all with the `jar` tool at it stands today because the `jar` tool does not seem to be designed for an explicit enumeration of files to include. It seems to be designed for working on directories only, in which case the entry order may depend on the tool or the platform. Reference:
   > 
   
   If that proves to be true and we can't find a workaround, that's a blocker. Reproducible builds are the more important feature. 
   
   I also tend to think that Java 17 is the absolute maximum version we should require at this time, and that might still be too high.


-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3891935818


##########
src/main/java/org/apache/maven/plugins/jar/Archive.java:
##########
@@ -0,0 +1,692 @@
+/*
+ * 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.jar;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.TreeMap;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.Type;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.MojoException;
+
+/**
+ * Files or root directories to archive for a single module.
+ * A single instance of {@code Archive} may contain many directories for different target Java releases.
+ * Many instances of {@code Archive} may exist when archiving a multi-modules project.
+ */
+final class Archive {
+    /**
+     * Whether to repeat the {@code -C} option before each file.
+     * Doing so makes the command-line very verbose while the documentation of
+     * <a href="https://docs.oracle.com/en/java/javase/25/docs/specs/man/jar.html">The jar Command</a>
+     * gives the impression that this option can be provided only once.
+     * However, our tests suggest that the first file after the directory specified by the {@code -C} option
+     * must be relative to that directory and all files after the first one must be prefixed by the directory
+     * which was specified in the {@code -C} option. This behavior is not documented, but we couldn't get the
+     * {@code jar} tool to work otherwise (except by repeating {@code -C} before each file).
+     * Furthermore, it seems that the relativized file needs to be the shortest one,
+     * otherwise the {@code jar} tool rejects files after the first one with "names do not match".
+     * Which file is first depends on the unspecified directory-iteration order.
+     *
+     * <p>If this flag is {@code true}, the plugin repeats {@code -C} before each file.
+     * This flag should be set to {@code false} if a future version of the {@code jar}
+     * tool allows to specify {@code -C} only once.</p>
+     *
+     * <p><b>Historical note:</b> we also tried to relativize only the first file after {@code -C}
+     * and keep all subsequent files as absolute. It works, but because we have to repeat the directory
+     * in the file name, it saves only 3 or 4 characters per file compared to repeating {@code -C}.</p>
+     */
+    private static final boolean REPEAT_C = true;
+
+    /**
+     * Path to the <abbr>POM</abbr> file generated for this archive, or {@code null} if none.
+     * This is non-null only if module source hierarchy is used, in which case the dependencies
+     * declared in this file are the intersection of the project dependencies and the content of
+     * the {@code module-info.class} file.
+     */
+    @Nullable
+    Path pomFile;
+
+    /**
+     * The <var>JAR</var> file to create. May be an existing file,
+     * in which case the file creation may be skipped if the file is still up-to-date.
+     */
+    @Nonnull
+    final Path jarFile;
+
+    /**
+     * A helper class for checking whether an existing <abbr>JAR</abbr> file is still up-to-date.
+     * This is null if there is no existing JAR file, or if we determined that the file is outdated.
+     */
+    private TimestampCheck existingJAR;
+
+    /**
+     * Name of the module being archived when the project is using module hierarchy.
+     * This is {@code null} if the project is using package hierarchy, either because it is a classical
+     * class-path project or because it is a single module compiled without using the module hierarchy.
+     * When using module source hierarchy, {@code javac} guarantees that the module name in the output
+     * directory is the name of the parent directory of {@code module-info.class}.
+     */
+    @Nullable
+    final String moduleName;
+
+    /**
+     * Path to {@code META-INF/MANIFEST.MF}, or {@code null} if none.
+     * If non-null, this value will be given to the {@code --manifest} option.
+     * The use of this option is preferable to adding {@code MANIFEST.MF} as an ordinary file.
+     *
+     * @see #setManifest(Path, boolean)
+     * @see #mergeManifest(Path, Manifest)
+     */
+    @Nullable
+    private Path manifest;
+
+    /**
+     * The Maven generated {@code pom.xml} and {@code pom.properties} files, or {@code null} if none.
+     * This first item shall be the base directory where the files are located.
+     */
+    @Nullable
+    List<Path> mavenFiles;
+
+    /**
+     * Fully-qualified name of the main class, or {@code null} if none.
+     * This is the value to provide to the {@code --main-class} option.
+     */
+    private String mainClass;
+
+    /**
+     * Files or root directories to store in the <abbr>JAR</abbr> file for each target Java release
+     * other than the base release. Keys are the target Java release with {@code null} for the base
+     * release.
+     */
+    @Nonnull
+    private final NavigableMap<Runtime.Version, FileSet> filesetForRelease;
+
+    /**
+     * Files or root directories to archive for a single target Java release of a single module.
+     * The {@link Archive} enclosing shall contain at least one instance of {@code FileSet} for
+     * the base release, and an arbitrary amount of other instances for other target releases.
+     */
+    final class FileSet {
+        /**
+         * A comparator for sorting paths in a reproducible order.
+         * This comparator assumes that all paths are relative to the same base directory (this is not verified).
+         * Note: we do not use {@link Path#compareTo(Path)} because the Javadoc said that it is platform dependent.
+         */
+        private static final Comparator<Path> REPRODUCIBLE_ORDER = (p1, p2) -> {
+            final int c1 = p1.getNameCount();
+            final int c2 = p2.getNameCount();
+            final int c = Math.min(c1, c2);
+            for (int i = 0; i < c; i++) {
+                String n1 = p1.getName(i).toString();
+                String n2 = p2.getName(i).toString();
+                int r = n1.compareTo(n2); // Case-sensitive comparison on all platforms.
+                if (r != 0) {
+                    return r;
+                }
+            }
+            return c1 - c2;
+        };
+
+        /**
+         * The root directory of all files or directories to archive.
+         * This is the value to pass to the {@code -C} tool option.
+         */
+        @Nonnull
+        final Path directory;
+
+        /**
+         * The files or directories to include in the <var>JAR</var> file.
+         * May be absolute paths or paths relative to {@link #directory}.
+         */
+        @Nonnull
+        final List<Path> files;
+
+        /**
+         * Creates an initially empty set of files or directories for a specific target Java release.
+         *
+         * @param directory the base directory of the files or directories to archive
+         */
+        private FileSet(Path directory) {
+            this.directory = directory;
+            this.files = new ArrayList<>();
+        }
+
+        /**
+         * 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.
+         * The caller should use that common directory for logging a warning message.
+         *
+         * @param base base directory found by previous invocations of this method, or {@code null} if none
+         * @return common directory of discarded files
+         */
+        private Path discardAllFiles(Path base) {
+            for (Path file : files) {
+                file = directory.resolve(file);
+                if (base == null) {
+                    base = file.getParent();
+                } else {
+                    while (!file.startsWith(base)) {
+                        base = base.getParent();
+                        if (base == null) {
+                            break;
+                        }
+                    }
+                }
+            }
+            files.clear();
+            return base;
+        }
+
+        /**
+         * Adds the given path to the list of files or directories to archive.
+         * This method may store a relative path instead of the absolute path.
+         *
+         * @param item a file or directory to archive
+         * @param attributes the file's basic attributes
+         * @param isDirectory whether the file is a directory
+         * @throws IllegalArgumentException if the given path cannot be made relative to the base directory
+         */
+        void add(Path item, BasicFileAttributes attributes, boolean isDirectory) {
+            TimestampCheck tc = existingJAR;
+            if (tc != null && tc.isUpdated(item, attributes, isDirectory)) {
+                existingJAR = null; // Signal that the existing file is outdated.
+            }
+            item = directory.relativize(item);
+            if (item.getNameCount() <= 1 && item.toString().isEmpty()) {
+                /*
+                 * The item is the `-C` directory itself (e.g. a `META-INF/versions/<n>` directory
+                 * added as a whole). An empty file argument is invalid for the `jar` tool
+                 * (some implementations reject it, others silently misbehave),
+                 * so archive the whole directory content with ".".
+                 */
+                item = Path.of(".");
+            }
+            files.add(item);
+        }
+
+        /**
+         * Adds to the given list the arguments to provide to the "jar" tool for this version.
+         * Elements added to the list shall be instances of {@link String} or {@link Path}.
+         *
+         * @param addTo the list where to add the arguments as {@link String} or {@link Path} instances
+         * @param version the target Java release, or {@code null} for the base version of the <abbr>JAR</abbr> file
+         */
+        private void arguments(List<Object> addTo, Runtime.Version version) {
+            if (!files.isEmpty()) {
+                if (version != null) {
+                    addTo.add("--release");
+                    addTo.add(version);
+                }
+                if (isReproducible) {
+                    files.sort(REPRODUCIBLE_ORDER);
+                }
+                if (REPEAT_C) {
+                    for (Path file : files) {
+                        addTo.add("-C");
+                        addTo.add(directory);
+                        addTo.add(file);
+                    }
+                } else {
+                    addTo.add("-C");
+                    addTo.add(directory);
+                    addTo.addAll(files);
+                }
+            }
+        }
+
+        /**
+         * {@return a string representation for debugging purposes}
+         */
+        @Override
+        public String toString() {
+            return getClass().getSimpleName() + '[' + directory.getFileName() + ": " + files.size() + " files]";
+        }
+    }
+
+    /**
+     * Whether reproducible build was requested.
+     */
+    private final boolean isReproducible;
+
+    /**
+     * Creates an initially empty set of files or directories.
+     *
+     * @param jarFile path to the <abbr>JAR</abbr> file to create
+     * @param moduleName the module name if using module hierarchy, or {@code null} if using package hierarchy
+     * @param version the target Java release, or {@code null} for the base version
+     * @param directory the directory of the classes targeting the base Java release
+     * @param forceCreation whether to force a new <abbr>JAR</abbr> file even if the content seems unchanged
+     * @param isReproducible whether reproducible build was requested
+     * @param logger where to send a warning if an error occurred while checking an existing <abbr>JAR</abbr> file
+     */
+    @SuppressWarnings("checkstyle:NeedBraces")
+    Archive(
+            final Path jarFile,
+            final String moduleName,
+            final Runtime.Version version,
+            final Path directory,
+            final boolean forceCreation,
+            final boolean isReproducible,
+            final Log logger) {
+        this.jarFile = jarFile;
+        this.moduleName = moduleName;
+        this.isReproducible = isReproducible;
+        filesetForRelease = new TreeMap<>((v1, v2) -> {
+            if (v1 == v2) return 0;
+            if (v1 == null) return -1;
+            if (v2 == null) return +1;
+            return v1.compareTo(v2);
+        });
+        filesetForRelease.put(version, new FileSet(directory));
+        if (!forceCreation && Files.isRegularFile(jarFile)) {
+            try {
+                existingJAR = new TimestampCheck(jarFile, directory, logger);
+            } catch (IOException e) {
+                // Ignore, we will regenerate the JAR file.
+                logger.warn(e);
+            }
+        }
+    }
+
+    /**
+     * {@return the files or directories to store in the <abbr>JAR</abbr> file for targeting the base Java release}
+     *
+     * @throws NoSuchElementException should not happen unless {@link #prune(boolean)} has been invoked
+     */
+    FileSet baseRelease() {
+        Map.Entry<Runtime.Version, FileSet> entry = filesetForRelease.firstEntry();
+        String message = null;
+        if (entry != null) {
+            Runtime.Version version = entry.getKey();
+            if (version == null) {
+                return entry.getValue();
+            }
+            message = "Expected base version but found version " + version;
+        }
+        throw new NoSuchElementException(message);
+    }
+
+    /**
+     * Returns the {@code module-info.class} files. Conceptually, there is at most once such file per module.
+     * However, more than one file may exist if additional files are provided for additional Java releases.
+     * This method returns only the files that exist.
+     *
+     * @return all {@code module-info.class} files found for all target Java releases
+     */
+    public List<Path> moduleInfoFiles() {
+        var files = new ArrayList<Path>();
+        filesetForRelease.values().forEach((release) -> {
+            Path file = release.directory.resolve(FileCollector.MODULE_DESCRIPTOR_FILE_NAME);
+            if (Files.isRegularFile(file)) {
+                files.add(file);
+            }
+        });
+        return files;
+    }
+
+    /**
+     * Discards all files in this archive, normally because those files are not in any module.
+     * This method returns a common parent directory for all the files that were discarded.
+     * The caller should use that common directory for logging a warning message.
+     *
+     * @return common directory of discarded files, or {@code null} if none
+     */
+    Path discardAllFiles() {
+        Path base = null;
+        for (FileSet release : filesetForRelease.values()) {
+            base = release.discardAllFiles(base);
+        }
+        filesetForRelease.clear();
+        return base;
+    }
+
+    /**
+     * Removes all empty file sets 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}, then this method ensures that at least one file set
+     * remains even if that file set is empty.
+     *
+     * @param skipIfEmpty value of {@link AbstractJarMojo#skipIfEmpty}
+     */
+    public void prune(final boolean skipIfEmpty) {
+        FileSet keep = (skipIfEmpty || isEmpty())
+                ? null
+                : filesetForRelease.firstEntry().getValue();
+        filesetForRelease.values().removeIf((fs) -> fs.files.isEmpty());
+        Iterator<Map.Entry<Runtime.Version, FileSet>> it =
+                filesetForRelease.entrySet().iterator();
+        if (it.hasNext()) {
+            Map.Entry<Runtime.Version, FileSet> first = it.next();
+            if (first.getKey() == null) {
+                return; // Already contains an entry for the base version, nothing to do.
+            }
+            keep = first.getValue();
+            it.remove();
+        }
+        if (keep != null) {
+            filesetForRelease.put(null, keep);
+        }
+    }
+
+    /**
+     * {@return whether this archive has nothing to archive}
+     * Note that this method may return {@code false} even when there is zero file to archive.
+     * It may happen if {@link AbstractJarMojo#skipIfEmpty} is {@code false}. In such case, the
+     * "empty" <abbr>JAR</abbr> file will still contain at {@code META-INF/MANIFEST.MF} file.
+     *
+     * <h4>Prerequisites</h4>
+     * The {@link #prune(boolean)} method should be invoked before this method for accurate result.
+     */
+    public boolean isEmpty() {
+        return filesetForRelease.isEmpty();
+    }
+
+    /**
+     * Checks whether the <abbr>JAR</abbr> file already exists and can be reused.
+     * This method verifies that the <abbr>JAR</abbr> file contains all the files to archive,
+     * contains no extra file, and no file to archive is newer than the <abbr>JAR</abbr> file.
+     *
+     * <p>This method can be invoked only once.
+     * If invoked more often, it returns {@code false} on all subsequent invocations.</p>
+     *
+     * @return whether the <abbr>JAR</abbr> file already exists and can be reused
+     */
+    public boolean isUpToDateJAR() {
+        final TimestampCheck tc = existingJAR;
+        if (tc == null) {
+            return false;
+        }
+        existingJAR = null; // Let GC do its job.
+        return tc.isUpToDateJAR(filesetForRelease.values());
+    }
+
+    /**
+     * Returns an initially empty set of files or directories for the specified target Java release.
+     *
+     * @param directory the base directory of the files to archive
+     * @param version the target Java release, or {@code null} for the base version
+     * @return container where to declare files and directories to archive
+     */
+    FileSet newTargetRelease(Path directory, Runtime.Version version) {
+        return filesetForRelease.computeIfAbsent(version, (key) -> new FileSet(directory));
+    }
+
+    /**
+     * Sets the {@code --main-class} option to the value of the {@code Main-Class} entry of the given manifest.
+     * As an extension, this method accepts the {@code module/classname} syntax (a syntax already used in some
+     * Java tools). If a module is specified, the main class is kept only if the module match. The intent is to
+     * allow users to specify on which module the main class applies when they use plugin configuration.
+     *
+     * <p>This method may modify the {@code content} manifest. Caller shall ensure that the given manifest
+     * is not a shared instance. This method returns whether a change has actually been done.</p>
+     *
+     * @param content combination of existing {@code MANIFEST.MF} and manifest inferred from configuration, or null
+     * @return whether the given manifest has been modified by this method
+     */
+    boolean setMainClass(Manifest content) {
+        if (content == null || mainClass != null) {
+            return false;
+        }
+        // We need to remove the attribute, otherwise it will conflict with `--main-class`.
+        mainClass = (String) content.getMainAttributes().remove(Attributes.Name.MAIN_CLASS);
+        if (mainClass != null) {
+            int s = mainClass.indexOf('/');
+            if (s >= 0) {
+                if (mainClass.substring(0, s).strip().equals(moduleName)) {
+                    mainClass = mainClass.substring(s + 1).strip();
+                } else {
+                    mainClass = null; // Main class is defined for another module.
+                }
+            }
+        }
+        return mainClass != null;
+    }
+
+    /**
+     * Sets the {@code --manifest} option to the given value if that option was not already set.
+     *
+     * @param file path to the manifest file
+     * @param force whether to set the manifest even if already set
+     * @return whether the manifest has been set
+     */
+    boolean setManifest(Path file, boolean force) {
+        if (manifest == null || force) {
+            manifest = file;
+            return true;
+        }
+        return false;
+    }
+
+    /**
+     * Merges the manifest of this module with the manifest specified in plugin configuration.
+     * If both {@code file} and {@code content} are non-null, then {@code content} must be the
+     * result of reading {@code file}.
+     *
+     * <p>This method never modifies the given {@code content} object. If manifest are merged,
+     * a new {@link Manifest} instance is created. Therefore, caller can check whether this
+     * method returned a new instance as a way to recognize that a merge occurred.</p>
+     *
+     * <p>If a merge occurs, the content specified to {@link #setManifest(Path)} has precedence.
+     * It should be the {@code target/classes/META-INF/MANIFEST.MF} file (or modular equivalent).</p>
+     *
+     * @param  file     an additional manifest file, or {@code null}
+     * @param  content  the content of {@code file}, or a standalone manifest produced at runtime
+     * @return the merged manifest as a new instance if some changes were necessary
+     * @throws IOException if an error occurred while reading a manifest file
+     */
+    Manifest mergeManifest(Path file, Manifest content) throws IOException {
+        if (manifest == null) {
+            manifest = file;
+        } else if (file != null && Files.isSameFile(file, manifest)) {
+            // Nothing to merge because of the constraint that `content` must be the content of `file`.
+        } else {
+            try (InputStream in = Files.newInputStream(manifest)) {
+                // No need to wrap in `BufferedInputStream`.
+                if (content != null) {
+                    content = new Manifest(content);
+                    content.read(in);
+                } else {
+                    content = new Manifest(in);
+                }
+            }
+        }
+        return content;
+    }
+
+    /**
+     * Adds to the given list the arguments to provide to the "jar" tool for each version.
+     * Elements added to the list shall be instances of {@link String} or {@link Path}.
+     * Callers should have added the following options (if applicable) before to invoke this method:

Review Comment:
   Removed that sentence.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3891931783


##########
src/main/java/org/apache/maven/plugins/jar/Archive.java:
##########
@@ -0,0 +1,692 @@
+/*
+ * 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.jar;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.TreeMap;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.Type;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.MojoException;
+
+/**
+ * Files or root directories to archive for a single module.
+ * A single instance of {@code Archive} may contain many directories for different target Java releases.
+ * Many instances of {@code Archive} may exist when archiving a multi-modules project.
+ */
+final class Archive {
+    /**
+     * Whether to repeat the {@code -C} option before each file.
+     * Doing so makes the command-line very verbose while the documentation of
+     * <a href="https://docs.oracle.com/en/java/javase/25/docs/specs/man/jar.html">The jar Command</a>
+     * gives the impression that this option can be provided only once.
+     * However, our tests suggest that the first file after the directory specified by the {@code -C} option
+     * must be relative to that directory and all files after the first one must be prefixed by the directory
+     * which was specified in the {@code -C} option. This behavior is not documented, but we couldn't get the
+     * {@code jar} tool to work otherwise (except by repeating {@code -C} before each file).
+     * Furthermore, it seems that the relativized file needs to be the shortest one,
+     * otherwise the {@code jar} tool rejects files after the first one with "names do not match".
+     * Which file is first depends on the unspecified directory-iteration order.
+     *
+     * <p>If this flag is {@code true}, the plugin repeats {@code -C} before each file.
+     * This flag should be set to {@code false} if a future version of the {@code jar}
+     * tool allows to specify {@code -C} only once.</p>
+     *
+     * <p><b>Historical note:</b> we also tried to relativize only the first file after {@code -C}
+     * and keep all subsequent files as absolute. It works, but because we have to repeat the directory
+     * in the file name, it saves only 3 or 4 characters per file compared to repeating {@code -C}.</p>
+     */
+    private static final boolean REPEAT_C = true;
+
+    /**
+     * Path to the <abbr>POM</abbr> file generated for this archive, or {@code null} if none.
+     * This is non-null only if module source hierarchy is used, in which case the dependencies
+     * declared in this file are the intersection of the project dependencies and the content of
+     * the {@code module-info.class} file.
+     */
+    @Nullable
+    Path pomFile;
+
+    /**
+     * The <var>JAR</var> file to create. May be an existing file,
+     * in which case the file creation may be skipped if the file is still up-to-date.
+     */
+    @Nonnull
+    final Path jarFile;
+
+    /**
+     * A helper class for checking whether an existing <abbr>JAR</abbr> file is still up-to-date.
+     * This is null if there is no existing JAR file, or if we determined that the file is outdated.
+     */
+    private TimestampCheck existingJAR;
+
+    /**
+     * Name of the module being archived when the project is using module hierarchy.
+     * This is {@code null} if the project is using package hierarchy, either because it is a classical
+     * class-path project or because it is a single module compiled without using the module hierarchy.
+     * When using module source hierarchy, {@code javac} guarantees that the module name in the output
+     * directory is the name of the parent directory of {@code module-info.class}.
+     */
+    @Nullable
+    final String moduleName;
+
+    /**
+     * Path to {@code META-INF/MANIFEST.MF}, or {@code null} if none.
+     * If non-null, this value will be given to the {@code --manifest} option.
+     * The use of this option is preferable to adding {@code MANIFEST.MF} as an ordinary file.
+     *
+     * @see #setManifest(Path, boolean)
+     * @see #mergeManifest(Path, Manifest)
+     */
+    @Nullable
+    private Path manifest;
+
+    /**
+     * The Maven generated {@code pom.xml} and {@code pom.properties} files, or {@code null} if none.
+     * This first item shall be the base directory where the files are located.
+     */
+    @Nullable
+    List<Path> mavenFiles;
+
+    /**
+     * Fully-qualified name of the main class, or {@code null} if none.
+     * This is the value to provide to the {@code --main-class} option.
+     */
+    private String mainClass;
+
+    /**
+     * Files or root directories to store in the <abbr>JAR</abbr> file for each target Java release
+     * other than the base release. Keys are the target Java release with {@code null} for the base
+     * release.
+     */
+    @Nonnull
+    private final NavigableMap<Runtime.Version, FileSet> filesetForRelease;
+
+    /**
+     * Files or root directories to archive for a single target Java release of a single module.
+     * The {@link Archive} enclosing shall contain at least one instance of {@code FileSet} for
+     * the base release, and an arbitrary amount of other instances for other target releases.
+     */
+    final class FileSet {
+        /**
+         * A comparator for sorting paths in a reproducible order.
+         * This comparator assumes that all paths are relative to the same base directory (this is not verified).
+         * Note: we do not use {@link Path#compareTo(Path)} because the Javadoc said that it is platform dependent.
+         */
+        private static final Comparator<Path> REPRODUCIBLE_ORDER = (p1, p2) -> {
+            final int c1 = p1.getNameCount();
+            final int c2 = p2.getNameCount();
+            final int c = Math.min(c1, c2);
+            for (int i = 0; i < c; i++) {
+                String n1 = p1.getName(i).toString();
+                String n2 = p2.getName(i).toString();
+                int r = n1.compareTo(n2); // Case-sensitive comparison on all platforms.
+                if (r != 0) {
+                    return r;
+                }
+            }
+            return c1 - c2;
+        };
+
+        /**
+         * The root directory of all files or directories to archive.
+         * This is the value to pass to the {@code -C} tool option.
+         */
+        @Nonnull
+        final Path directory;
+
+        /**
+         * The files or directories to include in the <var>JAR</var> file.
+         * May be absolute paths or paths relative to {@link #directory}.
+         */
+        @Nonnull
+        final List<Path> files;
+
+        /**
+         * Creates an initially empty set of files or directories for a specific target Java release.
+         *
+         * @param directory the base directory of the files or directories to archive
+         */
+        private FileSet(Path directory) {
+            this.directory = directory;
+            this.files = new ArrayList<>();
+        }
+
+        /**
+         * 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.
+         * The caller should use that common directory for logging a warning message.
+         *
+         * @param base base directory found by previous invocations of this method, or {@code null} if none
+         * @return common directory of discarded files
+         */
+        private Path discardAllFiles(Path base) {
+            for (Path file : files) {
+                file = directory.resolve(file);
+                if (base == null) {
+                    base = file.getParent();
+                } else {
+                    while (!file.startsWith(base)) {
+                        base = base.getParent();
+                        if (base == null) {
+                            break;
+                        }
+                    }
+                }
+            }
+            files.clear();
+            return base;
+        }
+
+        /**
+         * Adds the given path to the list of files or directories to archive.
+         * This method may store a relative path instead of the absolute path.
+         *
+         * @param item a file or directory to archive
+         * @param attributes the file's basic attributes
+         * @param isDirectory whether the file is a directory
+         * @throws IllegalArgumentException if the given path cannot be made relative to the base directory
+         */
+        void add(Path item, BasicFileAttributes attributes, boolean isDirectory) {
+            TimestampCheck tc = existingJAR;
+            if (tc != null && tc.isUpdated(item, attributes, isDirectory)) {
+                existingJAR = null; // Signal that the existing file is outdated.
+            }
+            item = directory.relativize(item);
+            if (item.getNameCount() <= 1 && item.toString().isEmpty()) {
+                /*
+                 * The item is the `-C` directory itself (e.g. a `META-INF/versions/<n>` directory
+                 * added as a whole). An empty file argument is invalid for the `jar` tool
+                 * (some implementations reject it, others silently misbehave),
+                 * so archive the whole directory content with ".".
+                 */
+                item = Path.of(".");
+            }
+            files.add(item);
+        }
+
+        /**
+         * Adds to the given list the arguments to provide to the "jar" tool for this version.
+         * Elements added to the list shall be instances of {@link String} or {@link Path}.
+         *
+         * @param addTo the list where to add the arguments as {@link String} or {@link Path} instances
+         * @param version the target Java release, or {@code null} for the base version of the <abbr>JAR</abbr> file
+         */
+        private void arguments(List<Object> addTo, Runtime.Version version) {
+            if (!files.isEmpty()) {
+                if (version != null) {
+                    addTo.add("--release");
+                    addTo.add(version);
+                }
+                if (isReproducible) {
+                    files.sort(REPRODUCIBLE_ORDER);
+                }
+                if (REPEAT_C) {
+                    for (Path file : files) {
+                        addTo.add("-C");
+                        addTo.add(directory);
+                        addTo.add(file);
+                    }
+                } else {
+                    addTo.add("-C");
+                    addTo.add(directory);
+                    addTo.addAll(files);
+                }
+            }
+        }
+
+        /**
+         * {@return a string representation for debugging purposes}
+         */
+        @Override
+        public String toString() {
+            return getClass().getSimpleName() + '[' + directory.getFileName() + ": " + files.size() + " files]";
+        }
+    }
+
+    /**
+     * Whether reproducible build was requested.
+     */
+    private final boolean isReproducible;
+
+    /**
+     * Creates an initially empty set of files or directories.
+     *
+     * @param jarFile path to the <abbr>JAR</abbr> file to create
+     * @param moduleName the module name if using module hierarchy, or {@code null} if using package hierarchy
+     * @param version the target Java release, or {@code null} for the base version
+     * @param directory the directory of the classes targeting the base Java release
+     * @param forceCreation whether to force a new <abbr>JAR</abbr> file even if the content seems unchanged
+     * @param isReproducible whether reproducible build was requested
+     * @param logger where to send a warning if an error occurred while checking an existing <abbr>JAR</abbr> file
+     */
+    @SuppressWarnings("checkstyle:NeedBraces")
+    Archive(
+            final Path jarFile,
+            final String moduleName,
+            final Runtime.Version version,
+            final Path directory,
+            final boolean forceCreation,
+            final boolean isReproducible,
+            final Log logger) {
+        this.jarFile = jarFile;
+        this.moduleName = moduleName;
+        this.isReproducible = isReproducible;
+        filesetForRelease = new TreeMap<>((v1, v2) -> {
+            if (v1 == v2) return 0;
+            if (v1 == null) return -1;
+            if (v2 == null) return +1;
+            return v1.compareTo(v2);
+        });
+        filesetForRelease.put(version, new FileSet(directory));
+        if (!forceCreation && Files.isRegularFile(jarFile)) {
+            try {
+                existingJAR = new TimestampCheck(jarFile, directory, logger);
+            } catch (IOException e) {
+                // Ignore, we will regenerate the JAR file.
+                logger.warn(e);
+            }
+        }
+    }
+
+    /**
+     * {@return the files or directories to store in the <abbr>JAR</abbr> file for targeting the base Java release}
+     *
+     * @throws NoSuchElementException should not happen unless {@link #prune(boolean)} has been invoked
+     */
+    FileSet baseRelease() {
+        Map.Entry<Runtime.Version, FileSet> entry = filesetForRelease.firstEntry();
+        String message = null;
+        if (entry != null) {
+            Runtime.Version version = entry.getKey();
+            if (version == null) {
+                return entry.getValue();
+            }
+            message = "Expected base version but found version " + version;
+        }
+        throw new NoSuchElementException(message);
+    }
+
+    /**
+     * Returns the {@code module-info.class} files. Conceptually, there is at most once such file per module.
+     * However, more than one file may exist if additional files are provided for additional Java releases.
+     * This method returns only the files that exist.
+     *
+     * @return all {@code module-info.class} files found for all target Java releases
+     */
+    public List<Path> moduleInfoFiles() {
+        var files = new ArrayList<Path>();
+        filesetForRelease.values().forEach((release) -> {
+            Path file = release.directory.resolve(FileCollector.MODULE_DESCRIPTOR_FILE_NAME);
+            if (Files.isRegularFile(file)) {
+                files.add(file);
+            }
+        });
+        return files;
+    }
+
+    /**
+     * Discards all files in this archive, normally because those files are not in any module.
+     * This method returns a common parent directory for all the files that were discarded.
+     * The caller should use that common directory for logging a warning message.
+     *
+     * @return common directory of discarded files, or {@code null} if none
+     */
+    Path discardAllFiles() {
+        Path base = null;
+        for (FileSet release : filesetForRelease.values()) {
+            base = release.discardAllFiles(base);
+        }
+        filesetForRelease.clear();
+        return base;
+    }
+
+    /**
+     * Removes all empty file sets 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}, then this method ensures that at least one file set
+     * remains even if that file set is empty.
+     *
+     * @param skipIfEmpty value of {@link AbstractJarMojo#skipIfEmpty}
+     */
+    public void prune(final boolean skipIfEmpty) {
+        FileSet keep = (skipIfEmpty || isEmpty())
+                ? null
+                : filesetForRelease.firstEntry().getValue();
+        filesetForRelease.values().removeIf((fs) -> fs.files.isEmpty());
+        Iterator<Map.Entry<Runtime.Version, FileSet>> it =
+                filesetForRelease.entrySet().iterator();
+        if (it.hasNext()) {
+            Map.Entry<Runtime.Version, FileSet> first = it.next();
+            if (first.getKey() == null) {
+                return; // Already contains an entry for the base version, nothing to do.
+            }
+            keep = first.getValue();
+            it.remove();
+        }
+        if (keep != null) {
+            filesetForRelease.put(null, keep);
+        }
+    }
+
+    /**
+     * {@return whether this archive has nothing to archive}
+     * Note that this method may return {@code false} even when there is zero file to archive.
+     * It may happen if {@link AbstractJarMojo#skipIfEmpty} is {@code false}. In such case, the
+     * "empty" <abbr>JAR</abbr> file will still contain at {@code META-INF/MANIFEST.MF} file.
+     *
+     * <h4>Prerequisites</h4>
+     * The {@link #prune(boolean)} method should be invoked before this method for accurate result.
+     */
+    public boolean isEmpty() {
+        return filesetForRelease.isEmpty();
+    }
+
+    /**
+     * Checks whether the <abbr>JAR</abbr> file already exists and can be reused.
+     * This method verifies that the <abbr>JAR</abbr> file contains all the files to archive,
+     * contains no extra file, and no file to archive is newer than the <abbr>JAR</abbr> file.
+     *
+     * <p>This method can be invoked only once.
+     * If invoked more often, it returns {@code false} on all subsequent invocations.</p>
+     *
+     * @return whether the <abbr>JAR</abbr> file already exists and can be reused
+     */
+    public boolean isUpToDateJAR() {
+        final TimestampCheck tc = existingJAR;
+        if (tc == null) {
+            return false;
+        }
+        existingJAR = null; // Let GC do its job.
+        return tc.isUpToDateJAR(filesetForRelease.values());
+    }
+
+    /**
+     * Returns an initially empty set of files or directories for the specified target Java release.
+     *
+     * @param directory the base directory of the files to archive
+     * @param version the target Java release, or {@code null} for the base version
+     * @return container where to declare files and directories to archive
+     */
+    FileSet newTargetRelease(Path directory, Runtime.Version version) {
+        return filesetForRelease.computeIfAbsent(version, (key) -> new FileSet(directory));
+    }
+
+    /**
+     * Sets the {@code --main-class} option to the value of the {@code Main-Class} entry of the given manifest.
+     * As an extension, this method accepts the {@code module/classname} syntax (a syntax already used in some
+     * Java tools). If a module is specified, the main class is kept only if the module match. The intent is to
+     * allow users to specify on which module the main class applies when they use plugin configuration.
+     *
+     * <p>This method may modify the {@code content} manifest. Caller shall ensure that the given manifest
+     * is not a shared instance. This method returns whether a change has actually been done.</p>
+     *
+     * @param content combination of existing {@code MANIFEST.MF} and manifest inferred from configuration, or null
+     * @return whether the given manifest has been modified by this method
+     */
+    boolean setMainClass(Manifest content) {
+        if (content == null || mainClass != null) {
+            return false;
+        }
+        // We need to remove the attribute, otherwise it will conflict with `--main-class`.
+        mainClass = (String) content.getMainAttributes().remove(Attributes.Name.MAIN_CLASS);
+        if (mainClass != null) {
+            int s = mainClass.indexOf('/');
+            if (s >= 0) {
+                if (mainClass.substring(0, s).strip().equals(moduleName)) {
+                    mainClass = mainClass.substring(s + 1).strip();
+                } else {
+                    mainClass = null; // Main class is defined for another module.
+                }
+            }
+        }
+        return mainClass != null;
+    }
+
+    /**
+     * Sets the {@code --manifest} option to the given value if that option was not already set.
+     *
+     * @param file path to the manifest file
+     * @param force whether to set the manifest even if already set
+     * @return whether the manifest has been set
+     */
+    boolean setManifest(Path file, boolean force) {
+        if (manifest == null || force) {
+            manifest = file;
+            return true;
+        }
+        return false;
+    }
+
+    /**
+     * Merges the manifest of this module with the manifest specified in plugin configuration.
+     * If both {@code file} and {@code content} are non-null, then {@code content} must be the
+     * result of reading {@code file}.
+     *
+     * <p>This method never modifies the given {@code content} object. If manifest are merged,
+     * a new {@link Manifest} instance is created. Therefore, caller can check whether this
+     * method returned a new instance as a way to recognize that a merge occurred.</p>
+     *
+     * <p>If a merge occurs, the content specified to {@link #setManifest(Path)} has precedence.
+     * It should be the {@code target/classes/META-INF/MANIFEST.MF} file (or modular equivalent).</p>
+     *
+     * @param  file     an additional manifest file, or {@code null}
+     * @param  content  the content of {@code file}, or a standalone manifest produced at runtime
+     * @return the merged manifest as a new instance if some changes were necessary
+     * @throws IOException if an error occurred while reading a manifest file
+     */
+    Manifest mergeManifest(Path file, Manifest content) throws IOException {
+        if (manifest == null) {
+            manifest = file;
+        } else if (file != null && Files.isSameFile(file, manifest)) {
+            // Nothing to merge because of the constraint that `content` must be the content of `file`.
+        } else {
+            try (InputStream in = Files.newInputStream(manifest)) {
+                // No need to wrap in `BufferedInputStream`.
+                if (content != null) {
+                    content = new Manifest(content);
+                    content.read(in);
+                } else {
+                    content = new Manifest(in);
+                }
+            }
+        }
+        return content;
+    }
+
+    /**
+     * Adds to the given list the arguments to provide to the "jar" tool for each version.
+     * Elements added to the list shall be instances of {@link String} or {@link Path}.

Review Comment:
   Replaced "shall" by "will".



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3891953979


##########
src/main/java/org/apache/maven/plugins/jar/DirectoryRole.java:
##########
@@ -0,0 +1,73 @@
+/*
+ * 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.jar;
+
+/**
+ * Directories that the archiver needs to handle in a special way.
+ */
+enum DirectoryRole {
+    /**
+     * The root directory. This is usually {@code "target/classes"}.
+     * The next locations can be {@link #META_INF}, {@link #NAMED_MODULE} or {@link #RESOURCES}.
+     */
+    ROOT,
+
+    /**
+     * The {@code "META-INF"} or {@code "<module>/META-INF"} directory.
+     * This is part of the <abbr>JAR</abbr> specification.
+     * The next locations can be {@link #VERSIONS} or {@link #VERSIONS_MODULAR}.
+     */
+    META_INF,
+
+    /**
+     * The {@code "META-INF/versions"} or {@code "<module>/META-INF/versions"} directory.
+     * This is part of the <abbr>JAR</abbr> specification, except the {@code <module>} prefix.
+     * The sub-directories are named according Java releases such as "21".
+     * The next location can only be {@link #RESOURCES}.
+     */
+    VERSIONS,
+
+    /**
+     * The Maven-specific {@code "META-INF/versions-modular"} directory.
+     * Note that {@code "<module>/META-INF/versions-modular"} is not forbidden, but does not make sense.

Review Comment:
   Done



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3892047768


##########
src/main/java/org/apache/maven/plugins/jar/MetadataFiles.java:
##########
@@ -0,0 +1,250 @@
+/*
+ * 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.jar;
+
+import java.io.BufferedWriter;
+import java.io.Closeable;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Properties;
+import java.util.jar.Manifest;
+import java.util.stream.Collectors;
+
+import org.apache.maven.api.ProducedArtifact;
+import org.apache.maven.api.Project;
+import org.apache.maven.shared.archiver.MavenArchiveConfiguration;
+
+/**
+ * Temporary metadata files generated by Maven before inclusion in the archive.
+ * Those files are created in a temporary {@code META-INF} directory when first needed.
+ * Those files are deleted after the build, unless the build failed or Maven was run in verbose mode.
+ */
+final class MetadataFiles implements Closeable {
+    /**
+     * The {@value} directory.
+     * This is part of <abbr>JAR</abbr> file specification.
+     */
+    static final String META_INF = "META-INF";
+
+    /**
+     * The {@value} file.
+     * This is part of <abbr>JAR</abbr> file specification.
+     */
+    static final String MANIFEST = "MANIFEST.MF";
+
+    /**
+     * The subdirectory where to add Maven-specific files.
+     */
+    static final String MAVEN_DIR = "maven";
+
+    /**
+     * The project for which to write metadata files.
+     */
+    private final Project project;
+
+    /**
+     * The output directory (usually {@code ${baseDir}/target/}).
+     */
+    private final Path buildDir;
+
+    /**
+     * All files and directories in the order that they were created.
+     * The first element of this list shall be the root temporary directory created by this class.
+     */
+    private final List<Path> filesToDelete;
+
+    /**
+     * The <abbr>POM</abbr> file to attach to the artifact. This is initially the project <abbr>POM</abbr>,
+     * but will be replaced by a new file generated by {@link ForModule} if module hierarchy is used.
+     * That file may be copied verbatim in the {@code META-INF/maven/} directory of the <abbr>JAR</abbr>.
+     */
+    private Path attachedPOM;
+
+    /**
+     * Creates an initially empty set of temporary metadata files.
+     *
+     * @param project the project for which to write metadata files
+     * @param buildDir the (usually) {@code ${baseDir}/target/} directory
+     */
+    MetadataFiles(Project project, Path buildDir) {
+        this.project = project;
+        this.buildDir = buildDir;
+        filesToDelete = new ArrayList<>();
+        attachedPOM = project.getPomPath();
+    }
+
+    /**
+     * Derives a <abbr>POM</abbr> as the intersection of the given {@code model} and {@code archive}.
+     *
+     * @param context the tool executor which is generating all archives
+     * @param archive the archive for which to generate a <abbr>POM</abbr>
+     * @param manifest manifest to use for deriving project name, or {@code null} if none
+     * @throws IOException if an error occurred while reading the {@code module-info.class} file
+     *         or while writing the <abbr>POM</abbr> file
+     */
+    void deriveModulePOM(ToolExecutor context, Archive archive, Manifest manifest) throws IOException {
+        var pom = context.pomDerivation.new ForModule(archive, manifest);
+        pom.writeModulePOM();
+        attachedPOM = pom.pomFile;
+        archive.pomFile = pom.pomFile;
+    }
+
+    /**
+     * Adds the given manifest in a temporary file.
+     * The file will be deleted when {@link #close()} is invoked.
+     *
+     * @param manifest the manifest to write
+     * @return the temporary manifest file
+     * @throws IOException if an error occurred while writing the file
+     */
+    public Path addManifest(final Manifest manifest) throws IOException {
+        Path file = baseDirectory().resolve(MANIFEST);
+        try (OutputStream out = Files.newOutputStream(file)) {
+            filesToDelete.add(file);
+            manifest.write(out);
+        }
+        return file;
+    }
+
+    /**
+     * {@return the root temporary directory for the files created by this class}
+     * The directory is created the first time that this method is invoked.
+     *
+     * @throws IOException if an error occurred while creating the temporary directory
+     */
+    private Path baseDirectory() throws IOException {
+        if (filesToDelete.isEmpty()) {
+            filesToDelete.add(Files.createTempDirectory(buildDir, "classes-"));
+        }
+        return filesToDelete.get(0);
+    }
+
+    /**
+     * Creates a new directory and adds it to the list of files to delete after the build.
+     *
+     * @param dir the existing directory where to create a sub-directory
+     * @param path path to the subdirectory to create
+     * @return the new directory
+     * @throws IOException if an error occurred while creating the subdirectory
+     */
+    private Path createDirectories(Path dir, String... path) throws IOException {
+        for (String subdir : path) {
+            dir = Files.createDirectory(dir.resolve(subdir));
+            filesToDelete.add(dir);
+        }
+        return dir;
+    }
+
+    /**
+     * Writes the {@code pom.xml} and {@code pom.properties} files.
+     * This method returns the base temporary directory followed by files that the "jar" tool will need to add
+     *
+     * @param archive archive configuration
+     * @param reproducible whether to enforce reproducible build
+     * @return arguments for the "jar" tool
+     * @throws IOException if an error occurred while writing the files
+     */
+    public List<Path> addPOM(final MavenArchiveConfiguration archive, final boolean reproducible) throws IOException {
+        final String groupId = project.getGroupId();
+        final String artifactId = project.getArtifactId();
+        final String version;
+        final ProducedArtifact pom = project.getPomArtifact();
+        if (pom.isSnapshot()) {
+            version = pom.getVersion().toString();
+        } else {
+            version = project.getVersion();
+        }
+        final Path baseDir = baseDirectory();
+        final Path mavenDir = createDirectories(baseDir, META_INF, MAVEN_DIR, groupId, artifactId);
+        final Path pomFile = linkOrCopy(attachedPOM, mavenDir.resolve("pom.xml"));
+        filesToDelete.add(pomFile); // Add soon for deleting this file even if an exception is thrown below.
+        /*
+         * Subset of above "pom.xml" file but written as a properties file.
+         * If reproducible build is enabled, we will need to reformat after
+         * writing for ensuring a deterministic order of entries.

Review Comment:
   Done.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3892053349


##########
src/main/java/org/apache/maven/plugins/jar/PomDerivation.java:
##########
@@ -0,0 +1,525 @@
+/*
+ * 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.jar;
+
+import javax.xml.stream.XMLStreamException;
+
+import java.io.BufferedInputStream;
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.UncheckedIOException;
+import java.lang.module.ModuleDescriptor;
+import java.lang.module.ModuleFinder;
+import java.lang.module.ModuleReference;
+import java.net.URI;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.DependencyCoordinates;
+import org.apache.maven.api.JavaPathType;
+import org.apache.maven.api.Session;
+import org.apache.maven.api.Type;
+import org.apache.maven.api.model.Dependency;
+import org.apache.maven.api.model.Model;
+import org.apache.maven.api.model.Parent;
+import org.apache.maven.api.plugin.MojoException;
+import org.apache.maven.api.services.DependencyCoordinatesFactory;
+import org.apache.maven.api.services.DependencyCoordinatesFactoryRequest;
+import org.apache.maven.api.services.DependencyResolver;
+import org.apache.maven.api.services.DependencyResolverRequest;
+import org.apache.maven.api.services.DependencyResolverResult;
+import org.apache.maven.api.services.ModelBuilderException;
+import org.apache.maven.model.v4.MavenStaxWriter;
+
+/**
+ * A mapper from Maven model dependencies to Java module names.
+ * A single instance of this class is created for a Maven project,
+ * then shared by all {@link ForModule} instances (one per module to archive).
+ */
+final class PomDerivation {
+    /**
+     * Whether to expand the list of transitive dependencies in the generated <abbr>POM</abbr>.
+     */
+    private static final boolean EXPAND_TRANSITIVE = false;
+
+    /**
+     * Copy of {@link AbstractJarMojo#session}.
+     */
+    private final Session session;
+
+    /**
+     * The project model, which includes dependencies of all modules.
+     */
+    private final Model projectModel;
+
+    /**
+     * The factory to use for creating temporary {@link DependencyCoordinates} instances.
+     */
+    private final DependencyCoordinatesFactory coordinateFactory;
+
+    /**
+     * Provide module descriptors from module names.
+     * May be {@code null} if no {@code module-info} was found.
+     */
+    private final ModuleFinder moduleFinder;
+
+    /**
+     * Module references from paths to the <abbr>JAR</abbr> file or root directory.
+     */
+    private final Map<URI, ModuleReference> fromURI;
+
+    /**
+     * Module names associated to Maven dependencies.
+     * This map contains {@link DependencyCoordinates#getId()} as keys and module references as values.
+     * This is used for detecting which dependencies are really used according {@code module-info.class}.

Review Comment:
   Done.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3891863964


##########
src/main/java/org/apache/maven/plugins/jar/AbstractJarMojo.java:
##########
@@ -207,167 +205,208 @@ protected final Log getLog() {
     protected abstract String getType();
 
     /**
-     * Returns the JAR file to generate, based on an optional classifier.
+     * {@return the scope of dependencies}
+     * It should be {@link PathScope#MAIN_COMPILE} or {@link PathScope#TEST_COMPILE}.
+     * Note that we use compile scope rather than runtime scope because dependencies
+     * cannot appear in {@code requires} statement if they didn't had compile scope.
+     */
+    protected abstract PathScope getDependencyScope();
+
+    /**
+     * {@return the JAR tool to use for archiving the code}
      *
-     * @param basedir the output directory
-     * @param resultFinalName the name of the JAR file
-     * @param classifier an optional classifier
-     * @return the file to generate
+     * @throws MojoException if no JAR tool was found
+     *
+     * @since 4.0.0-beta-2
      */
-    protected Path getJarFile(Path basedir, String resultFinalName, String classifier) {
-        Objects.requireNonNull(basedir, "basedir is not allowed to be null");
-        Objects.requireNonNull(resultFinalName, "finalName is not allowed to be null");
-        String fileName = resultFinalName + (hasClassifier(classifier) ? '-' + classifier : "") + ".jar";
-        return basedir.resolve(fileName);
+    protected ToolProvider getJarTool() throws MojoException {
+        return ToolProvider.findFirst(toolId).orElseThrow(() -> new MojoException("No such \"" + toolId + "\" tool."));
     }
 
     /**
-     * Generates the JAR.
+     * Returns the output time stamp or, as a fallback, the {@code SOURCE_DATE_EPOCH} environment variable.
+     * If the time stamp is expressed in seconds, it is converted to ISO 8601 format. Otherwise it is returned as-is.
      *
-     * @return the path to the created archive file
-     * @throws MojoException in case of an error
+     * @return the time stamp in presumed ISO 8601 format, or {@code null} if none
+     *
+     * @since 4.0.0-beta-2
      */
-    public Path createArchive() throws MojoException {
-        Path basedir = outputDirectory != null
-                ? outputDirectory
-                : Path.of(project.getBuild().getDirectory());
-        String resultFinalName =
-                finalName != null ? finalName : project.getBuild().getFinalName();
-        Path jarFile = getJarFile(basedir, resultFinalName, getClassifier());
-
-        FileSetManager fileSetManager = new FileSetManager();
-        FileSet jarContentFileSet = new FileSet();
-        jarContentFileSet.setDirectory(getClassesDirectory().toAbsolutePath().toString());
-        jarContentFileSet.setIncludes(Arrays.asList(getIncludes()));
-        jarContentFileSet.setExcludes(Arrays.asList(getExcludes()));
-
-        String[] includedFiles = fileSetManager.getIncludedFiles(jarContentFileSet);
-
-        if (detectMultiReleaseJar
-                && Arrays.stream(includedFiles)
-                        .anyMatch(
-                                p -> p.startsWith("META-INF" + File.separatorChar + "versions" + File.separatorChar))) {
-            getLog().debug("Adding 'Multi-Release: true' manifest entry.");
-            archive.addManifestEntry(Attributes.Name.MULTI_RELEASE.toString(), "true");
+    protected String getOutputTimestamp() {
+        String time = nullIfAbsent(outputTimestamp);
+        if (time == null) {
+            time = nullIfAbsent(System.getenv("SOURCE_DATE_EPOCH"));
+            if (time == null) {
+                return null;
+            }
         }
+        if (Runtime.version().feature() < ToolExecutor.JDK_SUPPORT_DATE) {
+            log.warn("Reproducible build requires Java " + ToolExecutor.JDK_SUPPORT_DATE + " or later.");
+            return null;
+        }
+        for (int i = time.length(); --i >= 0; ) {
+            char c = time.charAt(i);
+            if ((c < '0' || c > '9') && (i != 0 || c != '-')) {
+                return time;
+            }
+        }
+        return Instant.ofEpochSecond(Long.parseLong(time)).toString();
+    }
 
-        // May give false positives if the files is named as module descriptor
-        // but is not in the root of the archive or in the versioned area
-        // (and hence not actually a module descriptor).
-        // That is fine since the modular Jar archiver will gracefully
-        // handle such case.
-        // And also such case is unlikely to happen as file ending
-        // with "module-info.class" is unlikely to be included in Jar file
-        // unless it is a module descriptor.
-        boolean containsModuleDescriptor =
-                Arrays.stream(includedFiles).anyMatch(p -> p.endsWith(MODULE_DESCRIPTOR_FILE_NAME));
-
-        String archiverName = containsModuleDescriptor ? "mjar" : "jar";
+    /**
+     * {@return the patterns of files to include, or an empty list if no include pattern was specified}
+     */
+    protected List<String> getIncludes() {
+        return asList(includes);
+    }
 
-        MavenArchiver archiver = new MavenArchiver();
-        archiver.setCreatedBy("Maven JAR Plugin", "org.apache.maven.plugins", "maven-jar-plugin");
-        archiver.setBuildJdkSpecDefaultEntry(archive.getManifest().isAddBuildEnvironmentEntries());
-        archiver.setArchiver((JarArchiver) archivers.get(archiverName));
-        archiver.setOutputFile(jarFile.toFile());
+    /**
+     * {@return the patterns of files to exclude, or an empty list if no exclude pattern was specified}
+     */
+    protected List<String> getExcludes() {
+        return asList(excludes);
+    }
 
-        // configure for Reproducible Builds based on outputTimestamp value
-        archiver.configureReproducibleBuild(outputTimestamp);
+    /**
+     * Returns the output directory and ensures that the directory exists.
+     * The returned directory will be either {@link #outputDirectory} if non-null,
+     * or {@link org.apache.maven.api.model.Build#getDirectory()} otherwise.
+     *
+     * <p>The directory is usually {@code target} and should always exist since it is usually the output
+     * of the compiler plugin. If nevertheless the directory does not exist, then this method creates it.
+     * However, this method does not try to create the parent directory, which should be the Maven sub-project.</p>
+     *
+     * @return the directory containing the generated <abbr>JAR</abbr> files.
+     * @throws IOException if the output directory did not existed and could not be created
+     */
+    protected Path getOutputDirectory() throws IOException {
+        Path dir = outputDirectory;
+        if (dir == null) {
+            dir = Path.of(project.getBuild().getDirectory());
+        }
+        if (Files.notExists(dir)) {
+            dir = Files.createDirectory(dir);
+        }
+        return dir;
+    }
 
-        archive.setForced(forceCreation);
+    /**
+     * Returns the given elements as a list if non-null.
+     *
+     * @param elements the elements, or {@code null}
+     * @return the elements as a list, or {@code null} if the given array was null
+     */
+    private static List<String> asList(String[] elements) {
+        return (elements == null) ? List.of() : Arrays.asList(elements);
+    }
 
-        try {
-            Path contentDirectory = getClassesDirectory();
-            if (!Files.exists(contentDirectory)) {
-                if (!forceCreation) {
-                    getLog().warn("JAR will be empty - no content was marked for inclusion!");
-                }
-            } else {
-                archiver.getArchiver().addDirectory(contentDirectory.toFile(), getIncludes(), getExcludes());
+    /**
+     * Generates the <abbr>JAR</abbr> files.
+     * Map keys are module names or {@code null} if the project does not use module hierarchy.
+     * Values are (<var>type</var>, <var>path</var>) pairs associated with each module where
+     * <var>type</var> is {@code "pom"}, {@code "jar"} or {@code "test-jar"} and <var>path</var>
+     * is the path to the <abbr>POM</abbr> or <abbr>JAR</abbr> file.
+     *
+     * <p>Note that a null key does not necessarily means that the <abbr>JAR</abbr> is not modular.

Review Comment:
   done



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3891855720


##########
src/main/java/org/apache/maven/plugins/jar/AbstractJarMojo.java:
##########
@@ -207,167 +205,208 @@ protected final Log getLog() {
     protected abstract String getType();
 
     /**
-     * Returns the JAR file to generate, based on an optional classifier.
+     * {@return the scope of dependencies}
+     * It should be {@link PathScope#MAIN_COMPILE} or {@link PathScope#TEST_COMPILE}.
+     * Note that we use compile scope rather than runtime scope because dependencies
+     * cannot appear in {@code requires} statement if they didn't had compile scope.
+     */
+    protected abstract PathScope getDependencyScope();
+
+    /**
+     * {@return the JAR tool to use for archiving the code}
      *
-     * @param basedir the output directory
-     * @param resultFinalName the name of the JAR file
-     * @param classifier an optional classifier
-     * @return the file to generate
+     * @throws MojoException if no JAR tool was found
+     *
+     * @since 4.0.0-beta-2
      */
-    protected Path getJarFile(Path basedir, String resultFinalName, String classifier) {
-        Objects.requireNonNull(basedir, "basedir is not allowed to be null");
-        Objects.requireNonNull(resultFinalName, "finalName is not allowed to be null");
-        String fileName = resultFinalName + (hasClassifier(classifier) ? '-' + classifier : "") + ".jar";
-        return basedir.resolve(fileName);
+    protected ToolProvider getJarTool() throws MojoException {
+        return ToolProvider.findFirst(toolId).orElseThrow(() -> new MojoException("No such \"" + toolId + "\" tool."));
     }
 
     /**
-     * Generates the JAR.
+     * Returns the output time stamp or, as a fallback, the {@code SOURCE_DATE_EPOCH} environment variable.
+     * If the time stamp is expressed in seconds, it is converted to ISO 8601 format. Otherwise it is returned as-is.
      *
-     * @return the path to the created archive file
-     * @throws MojoException in case of an error
+     * @return the time stamp in presumed ISO 8601 format, or {@code null} if none
+     *
+     * @since 4.0.0-beta-2
      */
-    public Path createArchive() throws MojoException {
-        Path basedir = outputDirectory != null
-                ? outputDirectory
-                : Path.of(project.getBuild().getDirectory());
-        String resultFinalName =
-                finalName != null ? finalName : project.getBuild().getFinalName();
-        Path jarFile = getJarFile(basedir, resultFinalName, getClassifier());
-
-        FileSetManager fileSetManager = new FileSetManager();
-        FileSet jarContentFileSet = new FileSet();
-        jarContentFileSet.setDirectory(getClassesDirectory().toAbsolutePath().toString());
-        jarContentFileSet.setIncludes(Arrays.asList(getIncludes()));
-        jarContentFileSet.setExcludes(Arrays.asList(getExcludes()));
-
-        String[] includedFiles = fileSetManager.getIncludedFiles(jarContentFileSet);
-
-        if (detectMultiReleaseJar
-                && Arrays.stream(includedFiles)
-                        .anyMatch(
-                                p -> p.startsWith("META-INF" + File.separatorChar + "versions" + File.separatorChar))) {
-            getLog().debug("Adding 'Multi-Release: true' manifest entry.");
-            archive.addManifestEntry(Attributes.Name.MULTI_RELEASE.toString(), "true");
+    protected String getOutputTimestamp() {
+        String time = nullIfAbsent(outputTimestamp);
+        if (time == null) {
+            time = nullIfAbsent(System.getenv("SOURCE_DATE_EPOCH"));
+            if (time == null) {
+                return null;
+            }
         }
+        if (Runtime.version().feature() < ToolExecutor.JDK_SUPPORT_DATE) {
+            log.warn("Reproducible build requires Java " + ToolExecutor.JDK_SUPPORT_DATE + " or later.");
+            return null;
+        }
+        for (int i = time.length(); --i >= 0; ) {
+            char c = time.charAt(i);
+            if ((c < '0' || c > '9') && (i != 0 || c != '-')) {
+                return time;
+            }
+        }
+        return Instant.ofEpochSecond(Long.parseLong(time)).toString();
+    }
 
-        // May give false positives if the files is named as module descriptor
-        // but is not in the root of the archive or in the versioned area
-        // (and hence not actually a module descriptor).
-        // That is fine since the modular Jar archiver will gracefully
-        // handle such case.
-        // And also such case is unlikely to happen as file ending
-        // with "module-info.class" is unlikely to be included in Jar file
-        // unless it is a module descriptor.
-        boolean containsModuleDescriptor =
-                Arrays.stream(includedFiles).anyMatch(p -> p.endsWith(MODULE_DESCRIPTOR_FILE_NAME));
-
-        String archiverName = containsModuleDescriptor ? "mjar" : "jar";
+    /**
+     * {@return the patterns of files to include, or an empty list if no include pattern was specified}
+     */
+    protected List<String> getIncludes() {

Review Comment:
   I agree, done (package access).



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3891836317


##########
src/main/java/org/apache/maven/plugins/jar/AbstractJarMojo.java:
##########
@@ -207,167 +205,208 @@ protected final Log getLog() {
     protected abstract String getType();
 
     /**
-     * Returns the JAR file to generate, based on an optional classifier.
+     * {@return the scope of dependencies}
+     * It should be {@link PathScope#MAIN_COMPILE} or {@link PathScope#TEST_COMPILE}.
+     * Note that we use compile scope rather than runtime scope because dependencies
+     * cannot appear in {@code requires} statement if they didn't had compile scope.
+     */
+    protected abstract PathScope getDependencyScope();
+
+    /**
+     * {@return the JAR tool to use for archiving the code}
      *
-     * @param basedir the output directory
-     * @param resultFinalName the name of the JAR file
-     * @param classifier an optional classifier
-     * @return the file to generate
+     * @throws MojoException if no JAR tool was found
+     *
+     * @since 4.0.0-beta-2
      */
-    protected Path getJarFile(Path basedir, String resultFinalName, String classifier) {
-        Objects.requireNonNull(basedir, "basedir is not allowed to be null");
-        Objects.requireNonNull(resultFinalName, "finalName is not allowed to be null");
-        String fileName = resultFinalName + (hasClassifier(classifier) ? '-' + classifier : "") + ".jar";
-        return basedir.resolve(fileName);
+    protected ToolProvider getJarTool() throws MojoException {
+        return ToolProvider.findFirst(toolId).orElseThrow(() -> new MojoException("No such \"" + toolId + "\" tool."));
     }
 
     /**
-     * Generates the JAR.
+     * Returns the output time stamp or, as a fallback, the {@code SOURCE_DATE_EPOCH} environment variable.
+     * If the time stamp is expressed in seconds, it is converted to ISO 8601 format. Otherwise it is returned as-is.
      *
-     * @return the path to the created archive file
-     * @throws MojoException in case of an error
+     * @return the time stamp in presumed ISO 8601 format, or {@code null} if none
+     *
+     * @since 4.0.0-beta-2
      */
-    public Path createArchive() throws MojoException {
-        Path basedir = outputDirectory != null
-                ? outputDirectory
-                : Path.of(project.getBuild().getDirectory());
-        String resultFinalName =
-                finalName != null ? finalName : project.getBuild().getFinalName();
-        Path jarFile = getJarFile(basedir, resultFinalName, getClassifier());
-
-        FileSetManager fileSetManager = new FileSetManager();
-        FileSet jarContentFileSet = new FileSet();
-        jarContentFileSet.setDirectory(getClassesDirectory().toAbsolutePath().toString());
-        jarContentFileSet.setIncludes(Arrays.asList(getIncludes()));
-        jarContentFileSet.setExcludes(Arrays.asList(getExcludes()));
-
-        String[] includedFiles = fileSetManager.getIncludedFiles(jarContentFileSet);
-
-        if (detectMultiReleaseJar
-                && Arrays.stream(includedFiles)
-                        .anyMatch(
-                                p -> p.startsWith("META-INF" + File.separatorChar + "versions" + File.separatorChar))) {
-            getLog().debug("Adding 'Multi-Release: true' manifest entry.");
-            archive.addManifestEntry(Attributes.Name.MULTI_RELEASE.toString(), "true");
+    protected String getOutputTimestamp() {
+        String time = nullIfAbsent(outputTimestamp);
+        if (time == null) {
+            time = nullIfAbsent(System.getenv("SOURCE_DATE_EPOCH"));
+            if (time == null) {
+                return null;
+            }
         }
+        if (Runtime.version().feature() < ToolExecutor.JDK_SUPPORT_DATE) {

Review Comment:
   We tried, the consequence is massive. The problem is that it has been decided that a default timestamp should be provided in the super POM (I don't think that we should have done that, but it is done now). Consequently, almost all integration tests fail on Java 17 for example. The opt-out are not so easy, as they cause for example `IndexOutOfBoundsException` in old versions of the Maven compiler plugin.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3892025774


##########
src/main/java/org/apache/maven/plugins/jar/FileCollector.java:
##########
@@ -0,0 +1,496 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.PathMatcher;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayDeque;
+import java.util.Deque;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.services.PathMatcherFactory;
+
+/**
+ * Dispatch the files in the output directory into the <abbr>JAR</abbr> files to create.
+ * Instead of just archiving as-is the content of the output directory, this class separates
+ * the following subdirectories to the options listed below:
+ *
+ * <ul>
+ *   <li>The {@code META-INF/MANIFEST.MF} file will be given to the {@code --manifest} option.</li>
+ *   <li>Files in the following directories will be given to the {@code --release} option:
+ *     <ul>
+ *       <li>{@code META-INF/versions/}</li>
+ *       <li>{@code META-INF/versions-modular/<module>/}</li>
+ *       <li>{@code <module>/META-INF/versions/}</li>
+ *     </ul>
+ *   </li>
+ * </ul>
+ *
+ * The reason for using the options is that they allow the {@code jar} tool to perform additional verifications.
+ * For example, when using the {@code --release} option, {@code jar} verifies the <abbr>API</abbr> compatibility.
+ */
+final class FileCollector extends SimpleFileVisitor<Path> {
+    /**
+     * The file to check for deciding whether the <abbr>JAR</abbr> is modular.
+     */
+    static final String MODULE_DESCRIPTOR_FILE_NAME = "module-info.class";
+
+    /**
+     * The {@value} directory.
+     * This is part of <abbr>JAR</abbr> file specification.
+     */
+    private static final String VERSIONS = "versions";
+
+    /**
+     * The {@value} directory.
+     * This is Maven-specific.
+     */
+    private static final String VERSIONS_MODULAR = "versions-modular";
+
+    /**
+     * Context (logger, configuration) in which the <abbr>JAR</abbr> file are created.
+     */
+    private final ToolExecutor context;
+
+    /**
+     * Whether to detect multi-release <abbr>JAR</abbr> files.
+     * The default value is {@code true}.
+     *
+     * @see AbstractJarMojo#detectMultiReleaseJar
+     */
+    private final boolean detectMultiReleaseJar;
+
+    /**
+     * Combination of includes and excludes path matcher applied on files.
+     */
+    @Nonnull
+    private final PathMatcher fileMatcher;
+
+    /**
+     * Combination of includes and excludes path matcher applied on directories.
+     */
+    @Nonnull
+    private final PathMatcher directoryMatcher;
+
+    /**
+     * Whether the matchers accept all files and there is no need to sort the files.
+     * In such case, we can declare whole directories to the {@code jar} tool instead
+     * of scanning the directory tree ourselves.
+     */
+    private final boolean addDirectories;
+
+    /**
+     * Files found in the output directory when package hierarchy is used.
+     * At most one of {@code packageHierarchy} and {@link #moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Archive packageHierarchy;
+
+    /**
+     * Files found in the output directory when module hierarchy is used. Keys are module names.
+     * At most one of {@link #packageHierarchy} and {@code moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Map<String, Archive> moduleHierarchy;
+
+    /**
+     * The current module being archived. This field is updated every times that {@code FileCollector}
+     * enters in a new module directory.
+     */
+    @Nonnull
+    private Archive currentModule;
+
+    /**
+     * The module and target Java release currently being scanned. This field is updated every times that
+     * {@code FileCollector} enters in a new module directory or in a new target Java release for a given module.
+     */
+    @Nonnull
+    private Archive.FileSet currentFilesToArchive;
+
+    /**
+     * The current target Java release, or {@code null} if none.
+     */
+    @Nullable
+    private Runtime.Version currentTargetVersion;
+
+    /**
+     * Identification of the kinds of directories being traversed.
+     * The length of this list is the depth in the directory hierarchy.
+     * The last element identifies the type of the current directory.
+     */
+    private final Deque<DirectoryRole> directoryRoles;
+
+    /**
+     * Whether to check when a file is the {@code MANIFEST.MF} file.
+     * This is allowed only when scanning the content of a {@code META-INF} directory.
+     */
+    private boolean checkForManifest;
+
+    /**
+     * Creates a new file collector.
+     *
+     * @param mojo the <abbr>MOJO</abbr> from which to get the configuration
+     * @param context context (logger, configuration) in which the <abbr>JAR</abbr> file are created
+     * @param directory the base directory of the files to archive
+     */
+    FileCollector(AbstractJarMojo mojo, ToolExecutor context, Path directory, PathMatcherFactory matcherFactory) {
+        this.context = context;
+        detectMultiReleaseJar = mojo.detectMultiReleaseJar;
+        directoryRoles = new ArrayDeque<>();
+        fileMatcher = matcherFactory.createPathMatcher(directory, mojo.getIncludes(), mojo.getExcludes(), false);
+        directoryMatcher = matcherFactory.deriveDirectoryMatcher(fileMatcher);
+        addDirectories = !context.isReproducible()
+                && matcherFactory.isIncludesAll(fileMatcher)
+                && matcherFactory.isIncludesAll(directoryMatcher);
+        packageHierarchy = context.newArchive(null, null, directory);
+        moduleHierarchy = new LinkedHashMap<>();
+        resetToPackageHierarchy();
+    }
+
+    /**
+     * Resets this {@code FileCollector} to the state where a package hierarchy is presumed.
+     */
+    private void resetToPackageHierarchy() {
+        currentModule = packageHierarchy;
+        currentFilesToArchive = currentModule.baseRelease();
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a module.
+     * For an output generated by {@code javac} from a module source hierarchy,
+     * the directory name is guaranteed to be the module name.
+     *
+     * @param directory a {@code "<module>"} or {@code "META-INF/versions-modular/<module>"} directory
+     */
+    private void enterModuleDirectory(final Path directory) {
+        String moduleName = directory.getFileName().toString();
+        currentModule = moduleHierarchy.computeIfAbsent(
+                moduleName, (name) -> context.newArchive(name, currentTargetVersion, directory));
+        currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a target Java version.
+     * The {@code useDirectly} argument tells whether the content of this directory will be specified directly
+     * as the content to add in the <abbr>JAR</abbr> file. This argument should be {@code false} when there is
+     * another directory level (the module names) to process before to add content.
+     *
+     * @param directory a {@code "META-INF/versions/<n>"} or {@code "META-INF/versions-modular/<n>"} directory
+     * @param useDirectly whether the directory is {@code "META-INF/versions/<n>"}
+     * @return whether to skip the directory because of invalid version number
+     */
+    private boolean enterVersionDirectory(final Path directory, final boolean useDirectly) {
+        try {
+            currentTargetVersion = Runtime.Version.parse(directory.getFileName().toString());
+        } catch (IllegalArgumentException e) {
+            context.warnInvalidVersion(directory, e);
+            return true;
+        }
+        if (useDirectly) {
+            currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+        }
+        return false;
+    }
+
+    /**
+     * Determines if the given directory should be scanned for files to archive.
+     * This method may also update {@link #currentFilesToArchive} if it detects
+     * that we are entering in a new module or a new target Java release.
+     *
+     * @param directory the directory which will be traversed
+     * @param attributes the directory's basic attributes
+     */
+    @Override
+    @SuppressWarnings("checkstyle:MissingSwitchDefault")
+    public FileVisitResult preVisitDirectory(final Path directory, final BasicFileAttributes attributes)
+            throws IOException {
+        DirectoryRole role;
+        if (directoryRoles.isEmpty()) {
+            role = DirectoryRole.ROOT;
+        } else {
+            if (!directoryMatcher.matches(directory)) {
+                return FileVisitResult.SKIP_SUBTREE;
+            }
+            checkForManifest = false;
+            role = directoryRoles.getLast();
+            switch (role) {
+                case ROOT:
+                    /*
+                     * Entering in any subdirectory of `target/classes` (or other directory to archive).
+                     * We need to handle `META-INF` and modules in a special way, and archive the rest.
+                     */
+                    if (directory.endsWith(MetadataFiles.META_INF)) {
+                        role = DirectoryRole.META_INF;
+                        checkForManifest = true;
+                    } else if (Files.isRegularFile(directory.resolve(MODULE_DESCRIPTOR_FILE_NAME))) {
+                        role = DirectoryRole.NAMED_MODULE;
+                        enterModuleDirectory(directory);
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case META_INF:
+                    /*
+                     * Entering in a subdirectory of `META-INF` or `<module>/META-INF`. We will need to handle
+                     * `MANIFEST.MF`, `versions` and `versions-modular` in a special way, and archive the rest.
+                     */
+                    if (detectMultiReleaseJar && directory.endsWith(VERSIONS)) {
+                        role = DirectoryRole.VERSIONS;
+                    } else if (directory.endsWith(VERSIONS_MODULAR)) {
+                        if (!detectMultiReleaseJar) {
+                            // Used asked for no multi-release JAR.
+                            return FileVisitResult.SKIP_SUBTREE;
+                        }
+                        role = DirectoryRole.VERSIONS_MODULAR;
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case VERSIONS:
+                    /*
+                     * Entering in a `META-INF/versions/<n>/` directory for a specific target Java release.
+                     * May also be a `<module>/META-INF/versions/<n>/` directory, even if the latter is not
+                     * the layout generated by Maven Compiler Plugin.
+                     */
+                    if (enterVersionDirectory(directory, true)) {
+                        // An error occurred while parsing the version number.
+                        return FileVisitResult.SKIP_SUBTREE;
+                    }
+                    role = DirectoryRole.RESOURCES;
+                    break;
+
+                case VERSIONS_MODULAR:
+                    /*
+                     * Entering in a `META-INF/versions-modular/<n>/` directory for a specific target Java release.
+                     * That directory contains all modules for the version.
+                     */
+                    resetToPackageHierarchy(); // No module in particular yet.
+                    if (enterVersionDirectory(directory, false)) {
+                        // An error occurred while parsing the version number.
+                        return FileVisitResult.SKIP_SUBTREE;
+                    }
+                    role = DirectoryRole.MODULES;
+                    break;
+
+                case MODULES:
+                    /*
+                     * Entering in a `META-INF/versions-modular/<n>/<module>` directory.
+                     */
+                    enterModuleDirectory(directory);
+                    role = DirectoryRole.NAMED_MODULE;
+                    break;
+
+                case NAMED_MODULE:
+                    /*
+                     * Entering in a `<module>` or `META-INF/versions-modular/<n>/<module>` subdirectory.
+                     * A module could have its own `META-INF` subdirectory, so we need to check again.
+                     */
+                    if (directory.endsWith(MetadataFiles.META_INF)) {
+                        role = DirectoryRole.META_INF;
+                        checkForManifest = true;
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+            }
+        }
+        /*
+         * Do not move this condition inside the `switch` block because `role` may have been modified.
+         * The `role` value is now the role of `directory`, not anymore the role of parent directory.
+         */
+        if (addDirectories && role == DirectoryRole.RESOURCES) {
+            currentFilesToArchive.add(directory, attributes, true);
+            /*
+             * Since we are skipping the whole directory, `postVisitDirectory(…)` will not be invoked.
+             * We must reset `currentFilesToArchive` and `currentTargetVersion` by an explicit call.
+             * This is important mostly after we added a whole `META-INF/versions/<n>` directory,
+             * otherwise base files visited afterwards (directory iteration order is unspecified)
+             * would be added to this version's file set instead of the base release.
+             */
+            resetToParentDirectoryState();
+            return FileVisitResult.SKIP_SUBTREE;
+        } else {
+            directoryRoles.addLast(role);
+            return FileVisitResult.CONTINUE;
+        }
+    }
+
+    /**
+     * Updates the {@code FileCollector} state after we finished to scan the content of a directory.
+     * The fields to update depend on which directory has been visited (module, version, <i>etc.</i>).
+     *
+     * @param directory the directory which has been traversed
+     * @param error the error that occurred while traversing the directory, or {@code null} if none
+     */
+    @Override
+    public FileVisitResult postVisitDirectory(final Path directory, final IOException error) throws IOException {
+        if (error != null) {
+            throw error;
+        }
+        switch (directoryRoles.removeLast()) {
+            case NAMED_MODULE:
+                // Exited the directory of a single module.
+                resetToPackageHierarchy();
+                break;
+
+            case ROOT:
+                break;
+
+            default:
+                resetToParentDirectoryState();
+        }
+        return FileVisitResult.CONTINUE;
+    }
+
+    /**
+     * Updates {@code FileCollector} to a state suitable to the parent of the directory that we finished to scan.
+     * Contrarily to {@link #postVisitDirectory(Path, IOException)}, this method expects the last element of
+     * {@link #directoryRoles} to describe the parent directory, not the directory that we finished to visit.
+     */
+    @SuppressWarnings("checkstyle:MissingSwitchDefault")
+    private void resetToParentDirectoryState() {
+        switch (directoryRoles.getLast()) {
+            case VERSIONS:
+            case VERSIONS_MODULAR:
+                // Exited the directory for one target Java release.
+                currentFilesToArchive = currentModule.baseRelease();
+                currentTargetVersion = null;
+                break;
+
+            case META_INF:
+                checkForManifest = true;
+                break;
+        }
+    }
+
+    /**
+     * Archives a single file if accepted by the matcher.
+     *
+     * @param file the file
+     * @param attributes the file's basic attributes
+     */
+    @Override
+    public FileVisitResult visitFile(final Path file, final BasicFileAttributes attributes) {
+        if (fileMatcher.matches(file)) {
+            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.add(file, attributes, false);
+            }
+        }
+        return FileVisitResult.CONTINUE;
+    }
+
+    /**
+     * 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}, then this method ensures that at least one archive
+     * remains even if that archive is empty.
+     *
+     * @param skipIfEmpty value of {@link AbstractJarMojo#skipIfEmpty}
+     */
+    public void prune(boolean skipIfEmpty) {
+        boolean isModuleHierarchy = !moduleHierarchy.isEmpty();
+        moduleHierarchy.values().forEach((archive) -> archive.prune(skipIfEmpty));
+        moduleHierarchy.values().removeIf(Archive::isEmpty);
+        packageHierarchy.prune(isModuleHierarchy || skipIfEmpty);
+    }
+
+    /**
+     * Moves, copies or ignores orphan files.

Review Comment:
   Done



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3891999647


##########
src/main/java/org/apache/maven/plugins/jar/FileCollector.java:
##########
@@ -0,0 +1,496 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.PathMatcher;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayDeque;
+import java.util.Deque;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.services.PathMatcherFactory;
+
+/**
+ * Dispatch the files in the output directory into the <abbr>JAR</abbr> files to create.
+ * Instead of just archiving as-is the content of the output directory, this class separates
+ * the following subdirectories to the options listed below:
+ *
+ * <ul>
+ *   <li>The {@code META-INF/MANIFEST.MF} file will be given to the {@code --manifest} option.</li>
+ *   <li>Files in the following directories will be given to the {@code --release} option:
+ *     <ul>
+ *       <li>{@code META-INF/versions/}</li>
+ *       <li>{@code META-INF/versions-modular/<module>/}</li>
+ *       <li>{@code <module>/META-INF/versions/}</li>
+ *     </ul>
+ *   </li>
+ * </ul>
+ *
+ * The reason for using the options is that they allow the {@code jar} tool to perform additional verifications.
+ * For example, when using the {@code --release} option, {@code jar} verifies the <abbr>API</abbr> compatibility.
+ */
+final class FileCollector extends SimpleFileVisitor<Path> {
+    /**
+     * The file to check for deciding whether the <abbr>JAR</abbr> is modular.
+     */
+    static final String MODULE_DESCRIPTOR_FILE_NAME = "module-info.class";
+
+    /**
+     * The {@value} directory.
+     * This is part of <abbr>JAR</abbr> file specification.
+     */
+    private static final String VERSIONS = "versions";
+
+    /**
+     * The {@value} directory.
+     * This is Maven-specific.
+     */
+    private static final String VERSIONS_MODULAR = "versions-modular";
+
+    /**
+     * Context (logger, configuration) in which the <abbr>JAR</abbr> file are created.
+     */
+    private final ToolExecutor context;
+
+    /**
+     * Whether to detect multi-release <abbr>JAR</abbr> files.
+     * The default value is {@code true}.
+     *
+     * @see AbstractJarMojo#detectMultiReleaseJar
+     */
+    private final boolean detectMultiReleaseJar;
+
+    /**
+     * Combination of includes and excludes path matcher applied on files.
+     */
+    @Nonnull
+    private final PathMatcher fileMatcher;
+
+    /**
+     * Combination of includes and excludes path matcher applied on directories.
+     */
+    @Nonnull
+    private final PathMatcher directoryMatcher;
+
+    /**
+     * Whether the matchers accept all files and there is no need to sort the files.
+     * In such case, we can declare whole directories to the {@code jar} tool instead
+     * of scanning the directory tree ourselves.
+     */
+    private final boolean addDirectories;
+
+    /**
+     * Files found in the output directory when package hierarchy is used.
+     * At most one of {@code packageHierarchy} and {@link #moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Archive packageHierarchy;
+
+    /**
+     * Files found in the output directory when module hierarchy is used. Keys are module names.
+     * At most one of {@link #packageHierarchy} and {@code moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Map<String, Archive> moduleHierarchy;
+
+    /**
+     * The current module being archived. This field is updated every times that {@code FileCollector}
+     * enters in a new module directory.
+     */
+    @Nonnull
+    private Archive currentModule;
+
+    /**
+     * The module and target Java release currently being scanned. This field is updated every times that
+     * {@code FileCollector} enters in a new module directory or in a new target Java release for a given module.
+     */
+    @Nonnull
+    private Archive.FileSet currentFilesToArchive;
+
+    /**
+     * The current target Java release, or {@code null} if none.
+     */
+    @Nullable
+    private Runtime.Version currentTargetVersion;
+
+    /**
+     * Identification of the kinds of directories being traversed.
+     * The length of this list is the depth in the directory hierarchy.
+     * The last element identifies the type of the current directory.
+     */
+    private final Deque<DirectoryRole> directoryRoles;
+
+    /**
+     * Whether to check when a file is the {@code MANIFEST.MF} file.
+     * This is allowed only when scanning the content of a {@code META-INF} directory.
+     */
+    private boolean checkForManifest;
+
+    /**
+     * Creates a new file collector.
+     *
+     * @param mojo the <abbr>MOJO</abbr> from which to get the configuration
+     * @param context context (logger, configuration) in which the <abbr>JAR</abbr> file are created
+     * @param directory the base directory of the files to archive
+     */
+    FileCollector(AbstractJarMojo mojo, ToolExecutor context, Path directory, PathMatcherFactory matcherFactory) {
+        this.context = context;
+        detectMultiReleaseJar = mojo.detectMultiReleaseJar;
+        directoryRoles = new ArrayDeque<>();
+        fileMatcher = matcherFactory.createPathMatcher(directory, mojo.getIncludes(), mojo.getExcludes(), false);
+        directoryMatcher = matcherFactory.deriveDirectoryMatcher(fileMatcher);
+        addDirectories = !context.isReproducible()
+                && matcherFactory.isIncludesAll(fileMatcher)
+                && matcherFactory.isIncludesAll(directoryMatcher);
+        packageHierarchy = context.newArchive(null, null, directory);
+        moduleHierarchy = new LinkedHashMap<>();
+        resetToPackageHierarchy();
+    }
+
+    /**
+     * Resets this {@code FileCollector} to the state where a package hierarchy is presumed.
+     */
+    private void resetToPackageHierarchy() {
+        currentModule = packageHierarchy;
+        currentFilesToArchive = currentModule.baseRelease();
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a module.
+     * For an output generated by {@code javac} from a module source hierarchy,
+     * the directory name is guaranteed to be the module name.
+     *
+     * @param directory a {@code "<module>"} or {@code "META-INF/versions-modular/<module>"} directory
+     */
+    private void enterModuleDirectory(final Path directory) {
+        String moduleName = directory.getFileName().toString();
+        currentModule = moduleHierarchy.computeIfAbsent(
+                moduleName, (name) -> context.newArchive(name, currentTargetVersion, directory));
+        currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a target Java version.
+     * The {@code useDirectly} argument tells whether the content of this directory will be specified directly
+     * as the content to add in the <abbr>JAR</abbr> file. This argument should be {@code false} when there is
+     * another directory level (the module names) to process before to add content.
+     *
+     * @param directory a {@code "META-INF/versions/<n>"} or {@code "META-INF/versions-modular/<n>"} directory
+     * @param useDirectly whether the directory is {@code "META-INF/versions/<n>"}
+     * @return whether to skip the directory because of invalid version number
+     */
+    private boolean enterVersionDirectory(final Path directory, final boolean useDirectly) {
+        try {
+            currentTargetVersion = Runtime.Version.parse(directory.getFileName().toString());
+        } catch (IllegalArgumentException e) {
+            context.warnInvalidVersion(directory, e);
+            return true;
+        }
+        if (useDirectly) {
+            currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+        }
+        return false;
+    }
+
+    /**
+     * Determines if the given directory should be scanned for files to archive.
+     * This method may also update {@link #currentFilesToArchive} if it detects
+     * that we are entering in a new module or a new target Java release.
+     *
+     * @param directory the directory which will be traversed
+     * @param attributes the directory's basic attributes
+     */
+    @Override
+    @SuppressWarnings("checkstyle:MissingSwitchDefault")
+    public FileVisitResult preVisitDirectory(final Path directory, final BasicFileAttributes attributes)
+            throws IOException {
+        DirectoryRole role;
+        if (directoryRoles.isEmpty()) {
+            role = DirectoryRole.ROOT;
+        } else {
+            if (!directoryMatcher.matches(directory)) {
+                return FileVisitResult.SKIP_SUBTREE;
+            }
+            checkForManifest = false;
+            role = directoryRoles.getLast();
+            switch (role) {
+                case ROOT:
+                    /*
+                     * Entering in any subdirectory of `target/classes` (or other directory to archive).
+                     * We need to handle `META-INF` and modules in a special way, and archive the rest.
+                     */
+                    if (directory.endsWith(MetadataFiles.META_INF)) {
+                        role = DirectoryRole.META_INF;
+                        checkForManifest = true;
+                    } else if (Files.isRegularFile(directory.resolve(MODULE_DESCRIPTOR_FILE_NAME))) {
+                        role = DirectoryRole.NAMED_MODULE;
+                        enterModuleDirectory(directory);
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case META_INF:
+                    /*
+                     * Entering in a subdirectory of `META-INF` or `<module>/META-INF`. We will need to handle
+                     * `MANIFEST.MF`, `versions` and `versions-modular` in a special way, and archive the rest.
+                     */
+                    if (detectMultiReleaseJar && directory.endsWith(VERSIONS)) {
+                        role = DirectoryRole.VERSIONS;
+                    } else if (directory.endsWith(VERSIONS_MODULAR)) {
+                        if (!detectMultiReleaseJar) {
+                            // Used asked for no multi-release JAR.
+                            return FileVisitResult.SKIP_SUBTREE;
+                        }
+                        role = DirectoryRole.VERSIONS_MODULAR;
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case VERSIONS:
+                    /*
+                     * Entering in a `META-INF/versions/<n>/` directory for a specific target Java release.
+                     * May also be a `<module>/META-INF/versions/<n>/` directory, even if the latter is not
+                     * the layout generated by Maven Compiler Plugin.
+                     */
+                    if (enterVersionDirectory(directory, true)) {
+                        // An error occurred while parsing the version number.
+                        return FileVisitResult.SKIP_SUBTREE;
+                    }
+                    role = DirectoryRole.RESOURCES;
+                    break;
+
+                case VERSIONS_MODULAR:
+                    /*
+                     * Entering in a `META-INF/versions-modular/<n>/` directory for a specific target Java release.
+                     * That directory contains all modules for the version.
+                     */
+                    resetToPackageHierarchy(); // No module in particular yet.
+                    if (enterVersionDirectory(directory, false)) {
+                        // An error occurred while parsing the version number.
+                        return FileVisitResult.SKIP_SUBTREE;
+                    }
+                    role = DirectoryRole.MODULES;
+                    break;
+
+                case MODULES:
+                    /*
+                     * Entering in a `META-INF/versions-modular/<n>/<module>` directory.
+                     */
+                    enterModuleDirectory(directory);
+                    role = DirectoryRole.NAMED_MODULE;
+                    break;
+
+                case NAMED_MODULE:
+                    /*
+                     * Entering in a `<module>` or `META-INF/versions-modular/<n>/<module>` subdirectory.
+                     * A module could have its own `META-INF` subdirectory, so we need to check again.
+                     */
+                    if (directory.endsWith(MetadataFiles.META_INF)) {
+                        role = DirectoryRole.META_INF;
+                        checkForManifest = true;
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+            }
+        }
+        /*
+         * Do not move this condition inside the `switch` block because `role` may have been modified.
+         * The `role` value is now the role of `directory`, not anymore the role of parent directory.

Review Comment:
   Done



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3891996839


##########
src/main/java/org/apache/maven/plugins/jar/FileCollector.java:
##########
@@ -0,0 +1,496 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.PathMatcher;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayDeque;
+import java.util.Deque;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.services.PathMatcherFactory;
+
+/**
+ * Dispatch the files in the output directory into the <abbr>JAR</abbr> files to create.
+ * Instead of just archiving as-is the content of the output directory, this class separates
+ * the following subdirectories to the options listed below:
+ *
+ * <ul>
+ *   <li>The {@code META-INF/MANIFEST.MF} file will be given to the {@code --manifest} option.</li>
+ *   <li>Files in the following directories will be given to the {@code --release} option:
+ *     <ul>
+ *       <li>{@code META-INF/versions/}</li>
+ *       <li>{@code META-INF/versions-modular/<module>/}</li>
+ *       <li>{@code <module>/META-INF/versions/}</li>
+ *     </ul>
+ *   </li>
+ * </ul>
+ *
+ * The reason for using the options is that they allow the {@code jar} tool to perform additional verifications.
+ * For example, when using the {@code --release} option, {@code jar} verifies the <abbr>API</abbr> compatibility.
+ */
+final class FileCollector extends SimpleFileVisitor<Path> {
+    /**
+     * The file to check for deciding whether the <abbr>JAR</abbr> is modular.
+     */
+    static final String MODULE_DESCRIPTOR_FILE_NAME = "module-info.class";
+
+    /**
+     * The {@value} directory.
+     * This is part of <abbr>JAR</abbr> file specification.
+     */
+    private static final String VERSIONS = "versions";
+
+    /**
+     * The {@value} directory.
+     * This is Maven-specific.
+     */
+    private static final String VERSIONS_MODULAR = "versions-modular";
+
+    /**
+     * Context (logger, configuration) in which the <abbr>JAR</abbr> file are created.
+     */
+    private final ToolExecutor context;
+
+    /**
+     * Whether to detect multi-release <abbr>JAR</abbr> files.
+     * The default value is {@code true}.
+     *
+     * @see AbstractJarMojo#detectMultiReleaseJar
+     */
+    private final boolean detectMultiReleaseJar;
+
+    /**
+     * Combination of includes and excludes path matcher applied on files.
+     */
+    @Nonnull
+    private final PathMatcher fileMatcher;
+
+    /**
+     * Combination of includes and excludes path matcher applied on directories.
+     */
+    @Nonnull
+    private final PathMatcher directoryMatcher;
+
+    /**
+     * Whether the matchers accept all files and there is no need to sort the files.
+     * In such case, we can declare whole directories to the {@code jar} tool instead
+     * of scanning the directory tree ourselves.
+     */
+    private final boolean addDirectories;
+
+    /**
+     * Files found in the output directory when package hierarchy is used.
+     * At most one of {@code packageHierarchy} and {@link #moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Archive packageHierarchy;
+
+    /**
+     * Files found in the output directory when module hierarchy is used. Keys are module names.
+     * At most one of {@link #packageHierarchy} and {@code moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Map<String, Archive> moduleHierarchy;
+
+    /**
+     * The current module being archived. This field is updated every times that {@code FileCollector}
+     * enters in a new module directory.
+     */
+    @Nonnull
+    private Archive currentModule;
+
+    /**
+     * The module and target Java release currently being scanned. This field is updated every times that
+     * {@code FileCollector} enters in a new module directory or in a new target Java release for a given module.
+     */
+    @Nonnull
+    private Archive.FileSet currentFilesToArchive;
+
+    /**
+     * The current target Java release, or {@code null} if none.
+     */
+    @Nullable
+    private Runtime.Version currentTargetVersion;
+
+    /**
+     * Identification of the kinds of directories being traversed.
+     * The length of this list is the depth in the directory hierarchy.
+     * The last element identifies the type of the current directory.
+     */
+    private final Deque<DirectoryRole> directoryRoles;
+
+    /**
+     * Whether to check when a file is the {@code MANIFEST.MF} file.
+     * This is allowed only when scanning the content of a {@code META-INF} directory.
+     */
+    private boolean checkForManifest;
+
+    /**
+     * Creates a new file collector.
+     *
+     * @param mojo the <abbr>MOJO</abbr> from which to get the configuration
+     * @param context context (logger, configuration) in which the <abbr>JAR</abbr> file are created
+     * @param directory the base directory of the files to archive
+     */
+    FileCollector(AbstractJarMojo mojo, ToolExecutor context, Path directory, PathMatcherFactory matcherFactory) {
+        this.context = context;
+        detectMultiReleaseJar = mojo.detectMultiReleaseJar;
+        directoryRoles = new ArrayDeque<>();
+        fileMatcher = matcherFactory.createPathMatcher(directory, mojo.getIncludes(), mojo.getExcludes(), false);
+        directoryMatcher = matcherFactory.deriveDirectoryMatcher(fileMatcher);
+        addDirectories = !context.isReproducible()
+                && matcherFactory.isIncludesAll(fileMatcher)
+                && matcherFactory.isIncludesAll(directoryMatcher);
+        packageHierarchy = context.newArchive(null, null, directory);
+        moduleHierarchy = new LinkedHashMap<>();
+        resetToPackageHierarchy();
+    }
+
+    /**
+     * Resets this {@code FileCollector} to the state where a package hierarchy is presumed.
+     */
+    private void resetToPackageHierarchy() {
+        currentModule = packageHierarchy;
+        currentFilesToArchive = currentModule.baseRelease();
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a module.
+     * For an output generated by {@code javac} from a module source hierarchy,
+     * the directory name is guaranteed to be the module name.
+     *
+     * @param directory a {@code "<module>"} or {@code "META-INF/versions-modular/<module>"} directory
+     */
+    private void enterModuleDirectory(final Path directory) {
+        String moduleName = directory.getFileName().toString();
+        currentModule = moduleHierarchy.computeIfAbsent(
+                moduleName, (name) -> context.newArchive(name, currentTargetVersion, directory));
+        currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a target Java version.
+     * The {@code useDirectly} argument tells whether the content of this directory will be specified directly
+     * as the content to add in the <abbr>JAR</abbr> file. This argument should be {@code false} when there is
+     * another directory level (the module names) to process before to add content.
+     *
+     * @param directory a {@code "META-INF/versions/<n>"} or {@code "META-INF/versions-modular/<n>"} directory
+     * @param useDirectly whether the directory is {@code "META-INF/versions/<n>"}
+     * @return whether to skip the directory because of invalid version number
+     */
+    private boolean enterVersionDirectory(final Path directory, final boolean useDirectly) {
+        try {
+            currentTargetVersion = Runtime.Version.parse(directory.getFileName().toString());
+        } catch (IllegalArgumentException e) {
+            context.warnInvalidVersion(directory, e);
+            return true;
+        }
+        if (useDirectly) {
+            currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+        }
+        return false;
+    }
+
+    /**
+     * Determines if the given directory should be scanned for files to archive.
+     * This method may also update {@link #currentFilesToArchive} if it detects
+     * that we are entering in a new module or a new target Java release.
+     *
+     * @param directory the directory which will be traversed
+     * @param attributes the directory's basic attributes
+     */
+    @Override
+    @SuppressWarnings("checkstyle:MissingSwitchDefault")
+    public FileVisitResult preVisitDirectory(final Path directory, final BasicFileAttributes attributes)
+            throws IOException {
+        DirectoryRole role;
+        if (directoryRoles.isEmpty()) {
+            role = DirectoryRole.ROOT;
+        } else {
+            if (!directoryMatcher.matches(directory)) {
+                return FileVisitResult.SKIP_SUBTREE;
+            }
+            checkForManifest = false;
+            role = directoryRoles.getLast();
+            switch (role) {
+                case ROOT:
+                    /*
+                     * Entering in any subdirectory of `target/classes` (or other directory to archive).

Review Comment:
   Replaced by "Visiting".



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3892096346


##########
src/main/java/org/apache/maven/plugins/jar/TimestampCheck.java:
##########
@@ -0,0 +1,237 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.nio.file.attribute.FileTime;
+import java.util.Collection;
+import java.util.Enumeration;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+
+import org.apache.maven.api.plugin.Log;
+
+/**
+ * Checks file timestamps in order to determine if anything changed compared to an existing <abbr>JAR</abbr> file.
+ * This class may scan directories, but only if they have not already been visited by {@link FileCollector}.
+ * Note that the latter can occur only if {@link FileCollector} has no {@code PathMatcher}.
+ * Therefore, this class uses no {@code PathMatcher} neither.
+ *
+ * <h2>Ignore files</h2>
+ * The {@code META-INF/MANIFEST.MF} file and the {@code META-INF/maven/} directory are ignored.
+ * See {@link #isIgnored(Path)} for the rational.
+ */
+final class TimestampCheck extends SimpleFileVisitor<Path> {
+    /**
+     * The base directory of archived files.
+     */
+    private final Path classesDir;
+
+    /**
+     * Path to the existing <abbr>JAR</abbr> file.
+     */
+    private final Path jarFile;
+
+    /**
+     * The last modified time of the <abbr>JAR</abbr> file.
+     */
+    private final FileTime jarFileTime;
+
+    /**
+     * Where to send non-fatal error messages.
+     */
+    private final Log logger;
+
+    /**
+     * Entries of the <abbr>JAR</abbr> file. Note that getting elements from this enumeration can be costly.
+     * Therefore, we do not fetch all elements in advance but only when needed.
+     */
+    private Enumeration<? extends ZipEntry> entries;
+
+    /**
+     * Files found in the <abbr>JAR</abbr> file but not yet traversed by the file visitor.
+     * Files are added lazily only when needed, and removed as soon as they have been traversed.
+     * Path are absolute (resolved with {@link #classesDir}).
+     */
+    private final Set<Path> filesInJAR;
+
+    /**
+     * Some of the files in the build directory. This list contains only the files for which we have already
+     * verified the timestamp. We store them in a separated list for avoiding to check the timestamp twice.

Review Comment:
   Done.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3923363997


##########
src/main/java/org/apache/maven/plugins/jar/Archive.java:
##########
@@ -0,0 +1,655 @@
+/*
+ * 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.jar;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.TreeMap;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.Type;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.MojoException;
+
+/**
+ * Files or root directories to archive for a single module.
+ * A single instance of {@code Archive} can contain many directories for different target Java releases.
+ * Many instances of {@code Archive} can exist when archiving a multi-modules project.
+ */
+final class Archive {
+    /**
+     * Path to the <abbr>POM</abbr> file generated for this archive, or {@code null} if none.
+     * This is non-null only if module source hierarchy is used, in which case the dependencies
+     * declared in this file are the intersection of the project dependencies and the content of
+     * the {@code module-info.class} file.
+     */
+    @Nullable
+    Path pomFile;
+
+    /**
+     * The <var>JAR</var> file to create. Can be an existing file,
+     * in which case the file creation can be skipped if the file is still up-to-date.
+     */
+    @Nonnull
+    final Path jarFile;
+
+    /**
+     * A helper class for checking whether an existing <abbr>JAR</abbr> file is still up-to-date.
+     * This is null if there is no existing JAR file, or if we determined that the file is outdated.
+     */
+    private TimestampCheck existingJAR;
+
+    /**
+     * Name of the module being archived when the project is using module hierarchy.
+     * This is {@code null} if the project is using package hierarchy, either because it is a classical
+     * class-path project or because it is a single module compiled without using the module hierarchy.
+     * When using module source hierarchy, {@code javac} guarantees that the module name in the output
+     * directory is the name of the parent directory of {@code module-info.class}.
+     */
+    @Nullable
+    final String moduleName;
+
+    /**
+     * Path to {@code META-INF/MANIFEST.MF}, or {@code null} if none.
+     * If non-null, this value will be given to the {@code --manifest} option.
+     * The use of this option is preferable to adding {@code MANIFEST.MF} as an ordinary file.
+     *
+     * @see #setManifest(Path, boolean)
+     * @see #mergeManifest(Path, Manifest)
+     */
+    @Nullable
+    private Path manifest;
+
+    /**
+     * The Maven generated {@code pom.xml} and {@code pom.properties} files, or {@code null} if none.
+     * This first item must be the base directory where the files are located.
+     */
+    @Nullable
+    List<Path> mavenFiles;
+
+    /**
+     * Fully-qualified name of the main class, or {@code null} if none.
+     * This is the value to provide to the {@code --main-class} option.
+     */
+    private String mainClass;
+
+    /**
+     * Files or root directories to store in the <abbr>JAR</abbr> file for each target Java release
+     * other than the base release. Keys are the target Java release with {@code null} for the base
+     * release.
+     */
+    @Nonnull
+    private final NavigableMap<Runtime.Version, FileSet> filesetForRelease;
+
+    /**
+     * Files or root directories to archive for a single target Java release of a single module.
+     * The {@link Archive} enclosing must contain at least one instance of {@code FileSet} for
+     * the base release, and an arbitrary amount of other instances for other target releases.
+     */
+    final class FileSet {
+        /**
+         * The root directory of all files or directories to archive.
+         * This is the value to pass to the {@code -C} tool option.
+         */
+        @Nonnull
+        final Path directory;
+
+        /**
+         * The files or directories to include in the <var>JAR</var> file.
+         * Can be absolute paths or paths relative to {@link #directory}.
+         * It usually contains only the files or directories directly in
+         * the root {@linkplain #directory}, not in sub-directories.
+         */
+        @Nonnull
+        final List<Path> files;
+
+        /**
+         * Creates an initially empty set of files or directories for a specific target Java release.
+         *
+         * @param directory the base directory of the files or directories to archive
+         */
+        private FileSet(Path directory) {
+            this.directory = directory;
+            this.files = new ArrayList<>();
+        }
+
+        /**
+         * 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.
+         * The caller should use that common directory for logging a warning message.
+         *
+         * @param base base directory found by previous invocations of this method, or {@code null} if none
+         * @return common directory of discarded files
+         */
+        private Path discardAllFiles(Path base) {
+            for (Path file : files) {
+                if (base == null) {
+                    base = file.getParent();
+                } else {
+                    while (!file.startsWith(base)) {
+                        base = base.getParent();
+                        if (base == null) {
+                            break;
+                        }
+                    }
+                }
+            }
+            files.clear();
+            return base;
+        }
+
+        /**
+         * Adds the given path to the list of files or directories to archive.
+         * If the given path is a directory, then all children will be included.
+         * Children to exclude, if any, should be managed by {@link ExcludedFiles}.
+         *
+         * @param item a file or directory to archive
+         * @param attributes the file's basic attributes
+         * @param isDirectory whether the file is a directory
+         */
+        void add(Path item, BasicFileAttributes attributes, boolean isDirectory) {
+            TimestampCheck tc = existingJAR;
+            if (tc != null && tc.isUpdated(item, attributes, isDirectory)) {
+                existingJAR = null; // Signal that the existing file is outdated.
+            }
+            files.add(item);
+        }
+
+        /**
+         * Adds to the given list the arguments to provide to the "jar" tool for this version.
+         * The elements added to the list will be instances of {@link String} or {@link Path}.
+         *
+         * <h4>Note about the {@code -C} option</h4>
+         * This method repeats the {@code -C} option before each file.
+         * Our tests suggest that the first file after the directory specified by the {@code -C} option must
+         * be relative to that directory and all files after the first one must be prefixed by the directory
+         * which was specified in the {@code -C} option. This behavior is not very intuitive and replying on
+         * it can be fragile. Furthermore, it seems that the relativized file needs to be the shortest one,
+         * otherwise the {@code jar} tool rejects files after the first one with "names do not match".
+         * Which file is first depends on the unspecified directory-iteration order.
+         * Repeating the {@code -C} option for each file seems safer.
+         *
+         * @param addTo the list to add the arguments as {@link String} or {@link Path} instances to
+         * @param version the target Java release, or {@code null} for the base version of the <abbr>JAR</abbr> file
+         * @throws IllegalArgumentException if a path cannot be made relative to the base directory
+         */
+        private void arguments(List<Object> addTo, Runtime.Version version) {
+            if (files.isEmpty()) {
+                return;
+            }
+            if (version != null) {
+                addTo.add("--release");
+                addTo.add(version);
+            }
+            Path previous = null;
+            for (Path file : files) {
+                if (previous != null && file.startsWith(previous)) {
+                    // Already added a parent directory.
+                    continue;
+                }
+                previous = file;
+                file = directory.relativize(file);
+                if (file.getNameCount() <= 1 && file.toString().isEmpty()) {
+                    /*
+                     * The `-C` directory itself (e.g. a "META-INF/versions/<n>" directory added as a whole).
+                     * An empty file argument is invalid for the `jar` tool (some implementations reject it,
+                     * others silently misbehave), so archive the whole directory content with ".".
+                     */
+                    file = Path.of(".");
+                }
+                addTo.add("-C");
+                addTo.add(directory);
+                addTo.add(file);
+            }
+        }
+
+        /**
+         * {@return a string representation for debugging purposes}
+         */
+        @Override
+        public String toString() {
+            return getClass().getSimpleName() + '[' + directory.getFileName() + ": " + files.size() + " files]";
+        }
+    }
+
+    /**
+     * Creates an initially empty set of files or directories.
+     *
+     * @param jarFile path to the <abbr>JAR</abbr> file to create
+     * @param moduleName the module name if using module hierarchy, or {@code null} if using package hierarchy
+     * @param version the target Java release, or {@code null} for the base version
+     * @param directory the directory of the classes targeting the base Java release
+     * @param forceCreation whether to force a new <abbr>JAR</abbr> file even if the content seems unchanged
+     * @param logger where to send a warning if an error occurred while checking an existing <abbr>JAR</abbr> file
+     */
+    @SuppressWarnings("checkstyle:NeedBraces")
+    Archive(
+            final Path jarFile,
+            final String moduleName,
+            final Runtime.Version version,
+            final Path directory,
+            final boolean forceCreation,
+            final Log logger) {
+        this.jarFile = jarFile;
+        this.moduleName = moduleName;
+        filesetForRelease = new TreeMap<>((v1, v2) -> {
+            if (v1 == v2) return 0;
+            if (v1 == null) return -1;
+            if (v2 == null) return +1;
+            return v1.compareTo(v2);
+        });
+        filesetForRelease.put(version, new FileSet(directory));
+        if (!forceCreation && Files.isRegularFile(jarFile)) {
+            try {
+                existingJAR = new TimestampCheck(jarFile, directory, logger);
+            } catch (IOException e) {
+                // Ignore, we will regenerate the JAR file.
+                logger.warn(e);
+            }
+        }
+    }
+
+    /**
+     * {@return the files or directories to store in the <abbr>JAR</abbr> file for targeting the base Java release}
+     *
+     * @throws NoSuchElementException should not happen unless {@link #prune(boolean)} has been invoked
+     */
+    FileSet baseRelease() {
+        Map.Entry<Runtime.Version, FileSet> entry = filesetForRelease.firstEntry();
+        String message = null;
+        if (entry != null) {
+            Runtime.Version version = entry.getKey();
+            if (version == null) {
+                return entry.getValue();
+            }
+            message = "Expected base version but found version " + version;
+        }
+        throw new NoSuchElementException(message);
+    }
+
+    /**
+     * Returns the {@code module-info.class} files. Conceptually, there is at most once such file per module.
+     * However, more than one file can exist if additional files are provided for additional Java releases.
+     * This method returns only the files that exist.
+     *
+     * @return all {@code module-info.class} files found for all target Java releases
+     */
+    public List<Path> moduleInfoFiles() {
+        var files = new ArrayList<Path>();
+        filesetForRelease.values().forEach((release) -> {
+            Path file = release.directory.resolve(FileCollector.MODULE_DESCRIPTOR_FILE_NAME);
+            if (Files.isRegularFile(file)) {
+                files.add(file);
+            }
+        });
+        return files;
+    }
+
+    /**
+     * Discards all files in this archive, normally because those files are not in any module.
+     * This method returns a common parent directory for all the files that were discarded.
+     * The caller should use that common directory for logging a warning message.
+     *
+     * @return common directory of discarded files, or {@code null} if none
+     */
+    Path discardAllFiles() {
+        Path base = null;
+        for (FileSet release : filesetForRelease.values()) {
+            base = release.discardAllFiles(base);
+        }
+        filesetForRelease.clear();
+        return base;
+    }
+
+    /**
+     * Removes all empty file sets 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}, then this method ensures that at least one file set
+     * remains even if that file set is empty.
+     *
+     * @param skipIfEmpty value of {@link AbstractJarMojo#skipIfEmpty}
+     */
+    public void prune(final boolean skipIfEmpty) {
+        FileSet keep = (skipIfEmpty || isEmpty())
+                ? null
+                : filesetForRelease.firstEntry().getValue();
+        filesetForRelease.values().removeIf((fs) -> fs.files.isEmpty());
+        Iterator<Map.Entry<Runtime.Version, FileSet>> it =
+                filesetForRelease.entrySet().iterator();
+        if (it.hasNext()) {
+            Map.Entry<Runtime.Version, FileSet> first = it.next();
+            if (first.getKey() == null) {
+                return; // Already contains an entry for the base version, nothing to do.
+            }
+            keep = first.getValue();
+            it.remove();
+        }
+        if (keep != null) {
+            filesetForRelease.put(null, keep);
+        }
+    }
+
+    /**
+     * {@return whether this archive has nothing to archive}
+     * This method can return {@code false} even when there is zero file to archive.
+     * It can happen if {@link AbstractJarMojo#skipIfEmpty} is {@code false}. In such case, the
+     * "empty" <abbr>JAR</abbr> file will still contain at {@code META-INF/MANIFEST.MF} file.
+     *
+     * <h4>Prerequisites</h4>
+     * The {@link #prune(boolean)} method should be invoked before this method for accurate result.
+     */
+    public boolean isEmpty() {
+        return filesetForRelease.isEmpty();
+    }
+
+    /**
+     * Checks whether the <abbr>JAR</abbr> file already exists and can be reused.
+     * This method verifies that the <abbr>JAR</abbr> file contains all the files to archive,
+     * contains no extra file, and no file to archive is newer than the <abbr>JAR</abbr> file.
+     *
+     * <p>This method can be invoked only once.
+     * If invoked more often, it returns {@code false} on all subsequent invocations.</p>

Review Comment:
   Done.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3921925448


##########
src/main/java/org/apache/maven/plugins/jar/Archive.java:
##########
@@ -0,0 +1,655 @@
+/*
+ * 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.jar;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.TreeMap;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.Type;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.MojoException;
+
+/**
+ * Files or root directories to archive for a single module.
+ * A single instance of {@code Archive} can contain many directories for different target Java releases.
+ * Many instances of {@code Archive} can exist when archiving a multi-modules project.
+ */
+final class Archive {
+    /**
+     * Path to the <abbr>POM</abbr> file generated for this archive, or {@code null} if none.
+     * This is non-null only if module source hierarchy is used, in which case the dependencies
+     * declared in this file are the intersection of the project dependencies and the content of
+     * the {@code module-info.class} file.
+     */
+    @Nullable
+    Path pomFile;
+
+    /**
+     * The <var>JAR</var> file to create. Can be an existing file,
+     * in which case the file creation can be skipped if the file is still up-to-date.
+     */
+    @Nonnull
+    final Path jarFile;
+
+    /**
+     * A helper class for checking whether an existing <abbr>JAR</abbr> file is still up-to-date.
+     * This is null if there is no existing JAR file, or if we determined that the file is outdated.
+     */
+    private TimestampCheck existingJAR;
+
+    /**
+     * Name of the module being archived when the project is using module hierarchy.
+     * This is {@code null} if the project is using package hierarchy, either because it is a classical
+     * class-path project or because it is a single module compiled without using the module hierarchy.
+     * When using module source hierarchy, {@code javac} guarantees that the module name in the output
+     * directory is the name of the parent directory of {@code module-info.class}.
+     */
+    @Nullable
+    final String moduleName;
+
+    /**
+     * Path to {@code META-INF/MANIFEST.MF}, or {@code null} if none.
+     * If non-null, this value will be given to the {@code --manifest} option.
+     * The use of this option is preferable to adding {@code MANIFEST.MF} as an ordinary file.
+     *
+     * @see #setManifest(Path, boolean)
+     * @see #mergeManifest(Path, Manifest)
+     */
+    @Nullable
+    private Path manifest;
+
+    /**
+     * The Maven generated {@code pom.xml} and {@code pom.properties} files, or {@code null} if none.
+     * This first item must be the base directory where the files are located.
+     */
+    @Nullable
+    List<Path> mavenFiles;
+
+    /**
+     * Fully-qualified name of the main class, or {@code null} if none.
+     * This is the value to provide to the {@code --main-class} option.
+     */
+    private String mainClass;
+
+    /**
+     * Files or root directories to store in the <abbr>JAR</abbr> file for each target Java release
+     * other than the base release. Keys are the target Java release with {@code null} for the base
+     * release.
+     */
+    @Nonnull
+    private final NavigableMap<Runtime.Version, FileSet> filesetForRelease;
+
+    /**
+     * Files or root directories to archive for a single target Java release of a single module.
+     * The {@link Archive} enclosing must contain at least one instance of {@code FileSet} for
+     * the base release, and an arbitrary amount of other instances for other target releases.
+     */
+    final class FileSet {
+        /**
+         * The root directory of all files or directories to archive.
+         * This is the value to pass to the {@code -C} tool option.
+         */
+        @Nonnull
+        final Path directory;
+
+        /**
+         * The files or directories to include in the <var>JAR</var> file.
+         * Can be absolute paths or paths relative to {@link #directory}.
+         * It usually contains only the files or directories directly in
+         * the root {@linkplain #directory}, not in sub-directories.
+         */
+        @Nonnull
+        final List<Path> files;
+
+        /**
+         * Creates an initially empty set of files or directories for a specific target Java release.
+         *
+         * @param directory the base directory of the files or directories to archive
+         */
+        private FileSet(Path directory) {
+            this.directory = directory;
+            this.files = new ArrayList<>();
+        }
+
+        /**
+         * 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.
+         * The caller should use that common directory for logging a warning message.
+         *
+         * @param base base directory found by previous invocations of this method, or {@code null} if none
+         * @return common directory of discarded files
+         */
+        private Path discardAllFiles(Path base) {
+            for (Path file : files) {
+                if (base == null) {
+                    base = file.getParent();
+                } else {
+                    while (!file.startsWith(base)) {
+                        base = base.getParent();
+                        if (base == null) {
+                            break;
+                        }
+                    }
+                }
+            }
+            files.clear();
+            return base;
+        }
+
+        /**
+         * Adds the given path to the list of files or directories to archive.
+         * If the given path is a directory, then all children will be included.
+         * Children to exclude, if any, should be managed by {@link ExcludedFiles}.
+         *
+         * @param item a file or directory to archive
+         * @param attributes the file's basic attributes
+         * @param isDirectory whether the file is a directory
+         */
+        void add(Path item, BasicFileAttributes attributes, boolean isDirectory) {
+            TimestampCheck tc = existingJAR;
+            if (tc != null && tc.isUpdated(item, attributes, isDirectory)) {
+                existingJAR = null; // Signal that the existing file is outdated.
+            }
+            files.add(item);
+        }
+
+        /**
+         * Adds to the given list the arguments to provide to the "jar" tool for this version.
+         * The elements added to the list will be instances of {@link String} or {@link Path}.
+         *
+         * <h4>Note about the {@code -C} option</h4>
+         * This method repeats the {@code -C} option before each file.
+         * Our tests suggest that the first file after the directory specified by the {@code -C} option must
+         * be relative to that directory and all files after the first one must be prefixed by the directory
+         * which was specified in the {@code -C} option. This behavior is not very intuitive and replying on
+         * it can be fragile. Furthermore, it seems that the relativized file needs to be the shortest one,
+         * otherwise the {@code jar} tool rejects files after the first one with "names do not match".
+         * Which file is first depends on the unspecified directory-iteration order.
+         * Repeating the {@code -C} option for each file seems safer.
+         *
+         * @param addTo the list to add the arguments as {@link String} or {@link Path} instances to
+         * @param version the target Java release, or {@code null} for the base version of the <abbr>JAR</abbr> file
+         * @throws IllegalArgumentException if a path cannot be made relative to the base directory
+         */
+        private void arguments(List<Object> addTo, Runtime.Version version) {
+            if (files.isEmpty()) {
+                return;
+            }
+            if (version != null) {
+                addTo.add("--release");
+                addTo.add(version);
+            }
+            Path previous = null;
+            for (Path file : files) {
+                if (previous != null && file.startsWith(previous)) {
+                    // Already added a parent directory.
+                    continue;
+                }
+                previous = file;
+                file = directory.relativize(file);
+                if (file.getNameCount() <= 1 && file.toString().isEmpty()) {
+                    /*
+                     * The `-C` directory itself (e.g. a "META-INF/versions/<n>" directory added as a whole).
+                     * An empty file argument is invalid for the `jar` tool (some implementations reject it,
+                     * others silently misbehave), so archive the whole directory content with ".".
+                     */
+                    file = Path.of(".");
+                }
+                addTo.add("-C");
+                addTo.add(directory);
+                addTo.add(file);
+            }
+        }
+
+        /**
+         * {@return a string representation for debugging purposes}
+         */
+        @Override
+        public String toString() {
+            return getClass().getSimpleName() + '[' + directory.getFileName() + ": " + files.size() + " files]";
+        }
+    }
+
+    /**
+     * Creates an initially empty set of files or directories.
+     *
+     * @param jarFile path to the <abbr>JAR</abbr> file to create
+     * @param moduleName the module name if using module hierarchy, or {@code null} if using package hierarchy
+     * @param version the target Java release, or {@code null} for the base version
+     * @param directory the directory of the classes targeting the base Java release
+     * @param forceCreation whether to force a new <abbr>JAR</abbr> file even if the content seems unchanged
+     * @param logger where to send a warning if an error occurred while checking an existing <abbr>JAR</abbr> file
+     */
+    @SuppressWarnings("checkstyle:NeedBraces")
+    Archive(
+            final Path jarFile,
+            final String moduleName,
+            final Runtime.Version version,
+            final Path directory,
+            final boolean forceCreation,
+            final Log logger) {
+        this.jarFile = jarFile;
+        this.moduleName = moduleName;
+        filesetForRelease = new TreeMap<>((v1, v2) -> {
+            if (v1 == v2) return 0;
+            if (v1 == null) return -1;
+            if (v2 == null) return +1;
+            return v1.compareTo(v2);
+        });
+        filesetForRelease.put(version, new FileSet(directory));
+        if (!forceCreation && Files.isRegularFile(jarFile)) {
+            try {
+                existingJAR = new TimestampCheck(jarFile, directory, logger);
+            } catch (IOException e) {
+                // Ignore, we will regenerate the JAR file.
+                logger.warn(e);
+            }
+        }
+    }
+
+    /**
+     * {@return the files or directories to store in the <abbr>JAR</abbr> file for targeting the base Java release}
+     *
+     * @throws NoSuchElementException should not happen unless {@link #prune(boolean)} has been invoked
+     */
+    FileSet baseRelease() {
+        Map.Entry<Runtime.Version, FileSet> entry = filesetForRelease.firstEntry();
+        String message = null;
+        if (entry != null) {
+            Runtime.Version version = entry.getKey();
+            if (version == null) {
+                return entry.getValue();
+            }
+            message = "Expected base version but found version " + version;
+        }
+        throw new NoSuchElementException(message);
+    }
+
+    /**
+     * Returns the {@code module-info.class} files. Conceptually, there is at most once such file per module.
+     * However, more than one file can exist if additional files are provided for additional Java releases.
+     * This method returns only the files that exist.
+     *
+     * @return all {@code module-info.class} files found for all target Java releases
+     */
+    public List<Path> moduleInfoFiles() {
+        var files = new ArrayList<Path>();
+        filesetForRelease.values().forEach((release) -> {
+            Path file = release.directory.resolve(FileCollector.MODULE_DESCRIPTOR_FILE_NAME);
+            if (Files.isRegularFile(file)) {
+                files.add(file);
+            }
+        });
+        return files;
+    }
+
+    /**
+     * Discards all files in this archive, normally because those files are not in any module.
+     * This method returns a common parent directory for all the files that were discarded.
+     * The caller should use that common directory for logging a warning message.
+     *
+     * @return common directory of discarded files, or {@code null} if none
+     */
+    Path discardAllFiles() {
+        Path base = null;
+        for (FileSet release : filesetForRelease.values()) {
+            base = release.discardAllFiles(base);
+        }
+        filesetForRelease.clear();
+        return base;
+    }
+
+    /**
+     * Removes all empty file sets 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}, then this method ensures that at least one file set
+     * remains even if that file set is empty.
+     *
+     * @param skipIfEmpty value of {@link AbstractJarMojo#skipIfEmpty}
+     */
+    public void prune(final boolean skipIfEmpty) {
+        FileSet keep = (skipIfEmpty || isEmpty())
+                ? null
+                : filesetForRelease.firstEntry().getValue();
+        filesetForRelease.values().removeIf((fs) -> fs.files.isEmpty());
+        Iterator<Map.Entry<Runtime.Version, FileSet>> it =
+                filesetForRelease.entrySet().iterator();
+        if (it.hasNext()) {
+            Map.Entry<Runtime.Version, FileSet> first = it.next();
+            if (first.getKey() == null) {
+                return; // Already contains an entry for the base version, nothing to do.
+            }
+            keep = first.getValue();
+            it.remove();
+        }
+        if (keep != null) {
+            filesetForRelease.put(null, keep);
+        }
+    }
+
+    /**
+     * {@return whether this archive has nothing to archive}
+     * This method can return {@code false} even when there is zero file to archive.
+     * It can happen if {@link AbstractJarMojo#skipIfEmpty} is {@code false}. In such case, the
+     * "empty" <abbr>JAR</abbr> file will still contain at {@code META-INF/MANIFEST.MF} file.
+     *
+     * <h4>Prerequisites</h4>
+     * The {@link #prune(boolean)} method should be invoked before this method for accurate result.
+     */
+    public boolean isEmpty() {
+        return filesetForRelease.isEmpty();
+    }
+
+    /**
+     * Checks whether the <abbr>JAR</abbr> file already exists and can be reused.
+     * This method verifies that the <abbr>JAR</abbr> file contains all the files to archive,
+     * contains no extra file, and no file to archive is newer than the <abbr>JAR</abbr> file.
+     *
+     * <p>This method can be invoked only once.
+     * If invoked more often, it returns {@code false} on all subsequent invocations.</p>
+     *
+     * @return whether the <abbr>JAR</abbr> file already exists and can be reused
+     */
+    public boolean isUpToDateJAR() {
+        final TimestampCheck tc = existingJAR;
+        if (tc == null) {
+            return false;
+        }
+        existingJAR = null; // Let GC do its job.
+        return tc.isUpToDateJAR(filesetForRelease.values());
+    }
+
+    /**
+     * Returns an initially empty set of files or directories for the specified target Java release.
+     *
+     * @param directory the base directory of the files to archive
+     * @param version the target Java release, or {@code null} for the base version
+     * @return container where to declare files and directories to archive
+     */
+    FileSet newTargetRelease(Path directory, Runtime.Version version) {
+        return filesetForRelease.computeIfAbsent(version, (key) -> new FileSet(directory));
+    }
+
+    /**
+     * Sets the {@code --main-class} option to the value of the {@code Main-Class} entry of the given manifest.
+     * As an extension, this method accepts the {@code module/classname} syntax (a syntax already used in some
+     * Java tools). If a module is specified, the main class is kept only if the module match. The intent is to
+     * allow users to specify on which module the main class applies when they use plugin configuration.
+     *
+     * <p>This method may modify the {@code content} manifest. Caller must ensure that the given manifest
+     * is not a shared instance. This method returns whether a change has actually been done.</p>

Review Comment:
   Done.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3921690017


##########
src/main/java/org/apache/maven/plugins/jar/Archive.java:
##########
@@ -0,0 +1,655 @@
+/*
+ * 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.jar;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.TreeMap;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.Type;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.MojoException;
+
+/**
+ * Files or root directories to archive for a single module.
+ * A single instance of {@code Archive} can contain many directories for different target Java releases.
+ * Many instances of {@code Archive} can exist when archiving a multi-modules project.
+ */
+final class Archive {
+    /**
+     * Path to the <abbr>POM</abbr> file generated for this archive, or {@code null} if none.
+     * This is non-null only if module source hierarchy is used, in which case the dependencies
+     * declared in this file are the intersection of the project dependencies and the content of
+     * the {@code module-info.class} file.
+     */
+    @Nullable
+    Path pomFile;
+
+    /**
+     * The <var>JAR</var> file to create. Can be an existing file,

Review Comment:
   > Checked exceptions are caught by the compiler. Unchecked exceptions are bugs in the code we want to be alerted toi.
   
   This is not a rule. Unchecked exceptions can also be user's error and not bug. Wrapping and rethrowing an exception allows to add context, such as which JAR file we were assembling. However, the current code was not yet adding contextual information, therefore I simplified to `catch (IOException)` only.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3921692677


##########
src/main/java/org/apache/maven/plugins/jar/Archive.java:
##########
@@ -0,0 +1,655 @@
+/*
+ * 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.jar;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.TreeMap;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.Type;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.MojoException;
+
+/**
+ * Files or root directories to archive for a single module.
+ * A single instance of {@code Archive} can contain many directories for different target Java releases.
+ * Many instances of {@code Archive} can exist when archiving a multi-modules project.
+ */
+final class Archive {
+    /**
+     * Path to the <abbr>POM</abbr> file generated for this archive, or {@code null} if none.
+     * This is non-null only if module source hierarchy is used, in which case the dependencies
+     * declared in this file are the intersection of the project dependencies and the content of
+     * the {@code module-info.class} file.
+     */
+    @Nullable
+    Path pomFile;
+
+    /**
+     * The <var>JAR</var> file to create. Can be an existing file,

Review Comment:
   > var is not right here.
   
   Indeed, thanks for catching.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3921825322


##########
src/main/java/org/apache/maven/plugins/jar/Archive.java:
##########
@@ -0,0 +1,655 @@
+/*
+ * 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.jar;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.TreeMap;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.Type;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.MojoException;
+
+/**
+ * Files or root directories to archive for a single module.
+ * A single instance of {@code Archive} can contain many directories for different target Java releases.
+ * Many instances of {@code Archive} can exist when archiving a multi-modules project.
+ */
+final class Archive {
+    /**
+     * Path to the <abbr>POM</abbr> file generated for this archive, or {@code null} if none.
+     * This is non-null only if module source hierarchy is used, in which case the dependencies
+     * declared in this file are the intersection of the project dependencies and the content of
+     * the {@code module-info.class} file.
+     */
+    @Nullable
+    Path pomFile;
+
+    /**
+     * The <var>JAR</var> file to create. Can be an existing file,
+     * in which case the file creation can be skipped if the file is still up-to-date.
+     */
+    @Nonnull
+    final Path jarFile;
+
+    /**
+     * A helper class for checking whether an existing <abbr>JAR</abbr> file is still up-to-date.
+     * This is null if there is no existing JAR file, or if we determined that the file is outdated.
+     */
+    private TimestampCheck existingJAR;
+
+    /**
+     * Name of the module being archived when the project is using module hierarchy.
+     * This is {@code null} if the project is using package hierarchy, either because it is a classical
+     * class-path project or because it is a single module compiled without using the module hierarchy.
+     * When using module source hierarchy, {@code javac} guarantees that the module name in the output
+     * directory is the name of the parent directory of {@code module-info.class}.
+     */
+    @Nullable
+    final String moduleName;
+
+    /**
+     * Path to {@code META-INF/MANIFEST.MF}, or {@code null} if none.
+     * If non-null, this value will be given to the {@code --manifest} option.
+     * The use of this option is preferable to adding {@code MANIFEST.MF} as an ordinary file.
+     *
+     * @see #setManifest(Path, boolean)
+     * @see #mergeManifest(Path, Manifest)
+     */
+    @Nullable
+    private Path manifest;
+
+    /**
+     * The Maven generated {@code pom.xml} and {@code pom.properties} files, or {@code null} if none.
+     * This first item must be the base directory where the files are located.
+     */
+    @Nullable
+    List<Path> mavenFiles;
+
+    /**
+     * Fully-qualified name of the main class, or {@code null} if none.
+     * This is the value to provide to the {@code --main-class} option.
+     */
+    private String mainClass;
+
+    /**
+     * Files or root directories to store in the <abbr>JAR</abbr> file for each target Java release
+     * other than the base release. Keys are the target Java release with {@code null} for the base
+     * release.
+     */
+    @Nonnull
+    private final NavigableMap<Runtime.Version, FileSet> filesetForRelease;
+
+    /**
+     * Files or root directories to archive for a single target Java release of a single module.
+     * The {@link Archive} enclosing must contain at least one instance of {@code FileSet} for
+     * the base release, and an arbitrary amount of other instances for other target releases.
+     */
+    final class FileSet {
+        /**
+         * The root directory of all files or directories to archive.
+         * This is the value to pass to the {@code -C} tool option.
+         */
+        @Nonnull
+        final Path directory;
+
+        /**
+         * The files or directories to include in the <var>JAR</var> file.
+         * Can be absolute paths or paths relative to {@link #directory}.
+         * It usually contains only the files or directories directly in
+         * the root {@linkplain #directory}, not in sub-directories.
+         */
+        @Nonnull
+        final List<Path> files;
+
+        /**
+         * Creates an initially empty set of files or directories for a specific target Java release.
+         *
+         * @param directory the base directory of the files or directories to archive
+         */
+        private FileSet(Path directory) {
+            this.directory = directory;
+            this.files = new ArrayList<>();
+        }
+
+        /**
+         * 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.
+         * The caller should use that common directory for logging a warning message.
+         *
+         * @param base base directory found by previous invocations of this method, or {@code null} if none
+         * @return common directory of discarded files
+         */
+        private Path discardAllFiles(Path base) {
+            for (Path file : files) {
+                if (base == null) {
+                    base = file.getParent();
+                } else {
+                    while (!file.startsWith(base)) {
+                        base = base.getParent();
+                        if (base == null) {
+                            break;
+                        }
+                    }
+                }
+            }
+            files.clear();
+            return base;
+        }
+
+        /**
+         * Adds the given path to the list of files or directories to archive.
+         * If the given path is a directory, then all children will be included.
+         * Children to exclude, if any, should be managed by {@link ExcludedFiles}.
+         *
+         * @param item a file or directory to archive
+         * @param attributes the file's basic attributes
+         * @param isDirectory whether the file is a directory
+         */
+        void add(Path item, BasicFileAttributes attributes, boolean isDirectory) {
+            TimestampCheck tc = existingJAR;
+            if (tc != null && tc.isUpdated(item, attributes, isDirectory)) {
+                existingJAR = null; // Signal that the existing file is outdated.
+            }
+            files.add(item);
+        }
+
+        /**
+         * Adds to the given list the arguments to provide to the "jar" tool for this version.
+         * The elements added to the list will be instances of {@link String} or {@link Path}.
+         *
+         * <h4>Note about the {@code -C} option</h4>
+         * This method repeats the {@code -C} option before each file.
+         * Our tests suggest that the first file after the directory specified by the {@code -C} option must
+         * be relative to that directory and all files after the first one must be prefixed by the directory
+         * which was specified in the {@code -C} option. This behavior is not very intuitive and replying on
+         * it can be fragile. Furthermore, it seems that the relativized file needs to be the shortest one,
+         * otherwise the {@code jar} tool rejects files after the first one with "names do not match".
+         * Which file is first depends on the unspecified directory-iteration order.
+         * Repeating the {@code -C} option for each file seems safer.
+         *
+         * @param addTo the list to add the arguments as {@link String} or {@link Path} instances to
+         * @param version the target Java release, or {@code null} for the base version of the <abbr>JAR</abbr> file
+         * @throws IllegalArgumentException if a path cannot be made relative to the base directory
+         */
+        private void arguments(List<Object> addTo, Runtime.Version version) {
+            if (files.isEmpty()) {
+                return;
+            }
+            if (version != null) {
+                addTo.add("--release");
+                addTo.add(version);
+            }
+            Path previous = null;
+            for (Path file : files) {
+                if (previous != null && file.startsWith(previous)) {
+                    // Already added a parent directory.
+                    continue;
+                }
+                previous = file;
+                file = directory.relativize(file);
+                if (file.getNameCount() <= 1 && file.toString().isEmpty()) {
+                    /*
+                     * The `-C` directory itself (e.g. a "META-INF/versions/<n>" directory added as a whole).
+                     * An empty file argument is invalid for the `jar` tool (some implementations reject it,
+                     * others silently misbehave), so archive the whole directory content with ".".
+                     */
+                    file = Path.of(".");
+                }
+                addTo.add("-C");
+                addTo.add(directory);
+                addTo.add(file);
+            }
+        }
+
+        /**
+         * {@return a string representation for debugging purposes}
+         */
+        @Override
+        public String toString() {
+            return getClass().getSimpleName() + '[' + directory.getFileName() + ": " + files.size() + " files]";
+        }
+    }
+
+    /**
+     * Creates an initially empty set of files or directories.
+     *
+     * @param jarFile path to the <abbr>JAR</abbr> file to create
+     * @param moduleName the module name if using module hierarchy, or {@code null} if using package hierarchy
+     * @param version the target Java release, or {@code null} for the base version
+     * @param directory the directory of the classes targeting the base Java release
+     * @param forceCreation whether to force a new <abbr>JAR</abbr> file even if the content seems unchanged
+     * @param logger where to send a warning if an error occurred while checking an existing <abbr>JAR</abbr> file
+     */
+    @SuppressWarnings("checkstyle:NeedBraces")
+    Archive(
+            final Path jarFile,
+            final String moduleName,
+            final Runtime.Version version,
+            final Path directory,
+            final boolean forceCreation,
+            final Log logger) {
+        this.jarFile = jarFile;
+        this.moduleName = moduleName;
+        filesetForRelease = new TreeMap<>((v1, v2) -> {
+            if (v1 == v2) return 0;
+            if (v1 == null) return -1;
+            if (v2 == null) return +1;
+            return v1.compareTo(v2);
+        });
+        filesetForRelease.put(version, new FileSet(directory));
+        if (!forceCreation && Files.isRegularFile(jarFile)) {
+            try {
+                existingJAR = new TimestampCheck(jarFile, directory, logger);
+            } catch (IOException e) {
+                // Ignore, we will regenerate the JAR file.
+                logger.warn(e);
+            }
+        }
+    }
+
+    /**
+     * {@return the files or directories to store in the <abbr>JAR</abbr> file for targeting the base Java release}
+     *
+     * @throws NoSuchElementException should not happen unless {@link #prune(boolean)} has been invoked
+     */
+    FileSet baseRelease() {
+        Map.Entry<Runtime.Version, FileSet> entry = filesetForRelease.firstEntry();
+        String message = null;
+        if (entry != null) {
+            Runtime.Version version = entry.getKey();
+            if (version == null) {
+                return entry.getValue();
+            }
+            message = "Expected base version but found version " + version;
+        }
+        throw new NoSuchElementException(message);
+    }
+
+    /**
+     * Returns the {@code module-info.class} files. Conceptually, there is at most once such file per module.
+     * However, more than one file can exist if additional files are provided for additional Java releases.
+     * This method returns only the files that exist.
+     *
+     * @return all {@code module-info.class} files found for all target Java releases
+     */
+    public List<Path> moduleInfoFiles() {
+        var files = new ArrayList<Path>();
+        filesetForRelease.values().forEach((release) -> {
+            Path file = release.directory.resolve(FileCollector.MODULE_DESCRIPTOR_FILE_NAME);
+            if (Files.isRegularFile(file)) {
+                files.add(file);
+            }
+        });
+        return files;
+    }
+
+    /**
+     * Discards all files in this archive, normally because those files are not in any module.
+     * This method returns a common parent directory for all the files that were discarded.
+     * The caller should use that common directory for logging a warning message.
+     *
+     * @return common directory of discarded files, or {@code null} if none
+     */
+    Path discardAllFiles() {
+        Path base = null;
+        for (FileSet release : filesetForRelease.values()) {
+            base = release.discardAllFiles(base);
+        }
+        filesetForRelease.clear();
+        return base;
+    }
+
+    /**
+     * Removes all empty file sets 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}, then this method ensures that at least one file set
+     * remains even if that file set is empty.
+     *
+     * @param skipIfEmpty value of {@link AbstractJarMojo#skipIfEmpty}
+     */
+    public void prune(final boolean skipIfEmpty) {
+        FileSet keep = (skipIfEmpty || isEmpty())
+                ? null
+                : filesetForRelease.firstEntry().getValue();
+        filesetForRelease.values().removeIf((fs) -> fs.files.isEmpty());
+        Iterator<Map.Entry<Runtime.Version, FileSet>> it =
+                filesetForRelease.entrySet().iterator();
+        if (it.hasNext()) {
+            Map.Entry<Runtime.Version, FileSet> first = it.next();
+            if (first.getKey() == null) {
+                return; // Already contains an entry for the base version, nothing to do.
+            }
+            keep = first.getValue();
+            it.remove();
+        }
+        if (keep != null) {
+            filesetForRelease.put(null, keep);
+        }
+    }
+
+    /**
+     * {@return whether this archive has nothing to archive}
+     * This method can return {@code false} even when there is zero file to archive.
+     * It can happen if {@link AbstractJarMojo#skipIfEmpty} is {@code false}. In such case, the
+     * "empty" <abbr>JAR</abbr> file will still contain at {@code META-INF/MANIFEST.MF} file.
+     *
+     * <h4>Prerequisites</h4>

Review Comment:
   Replaced `<h4>` by a new paragraph.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3923339885


##########
src/test/java/org/apache/maven/plugins/jar/ArchiveTest.java:
##########
@@ -0,0 +1,257 @@
+/*
+ * 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.jar;
+
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Unit tests for {@link Archive}, focused on the two behaviours that are otherwise only
+ * exercised by integration tests whose outcome depends on the (unspecified) filesystem
+ * directory-iteration order, and therefore pass on some platforms while failing on others.
+ */
+class ArchiveTest {
+
+    /**
+     * Creates an {@code Archive} suitable for a unit test. {@code forceCreation = true} skips the
+     * existing-JAR timestamp check, so the (here {@code null}) logger is never dereferenced.
+     */
+    private static Archive archive(String moduleName, Runtime.Version version, Path directory) {
+        return new Archive(directory.resolve("out.jar"), moduleName, version, directory, true, null);
+    }
+
+    /**
+     * Creates a manifest with the main class attribute set to the given value.
+     *
+     * @param value value of the main class attribute
+     * @return a new manifest with the given attribute value
+     */
+    private static Manifest manifestWithMainClass(String value) {
+        Manifest m = new Manifest();
+        Attributes attributes = m.getMainAttributes();
+        attributes.put(Attributes.Name.MANIFEST_VERSION, "1.0");
+        attributes.put(Attributes.Name.MAIN_CLASS, value);
+        return m;
+    }
+
+    /**
+     * Returns the value of the main class attribute.
+     *
+     * @param m the manifest from which to get the value
+     * @return the main class attribute value, or {@code null} if none
+     */
+    private static Object mainClassOf(Manifest m) {
+        return m.getMainAttributes().get(Attributes.Name.MAIN_CLASS);
+    }
+
+    /**
+     * Verifies that {@link Archive#setMainClass(Manifest)} takes ownership for a module-qualified
+     * {@code "module/Class"} main class.
+     *
+     * The {@code "foo.bar/"} prefix in this test (the module name) is a Maven extension.
+     * The standard <abbr>JAR</abbr> specification accepts only the {@code "foo.MainFile"} class name.
+     */
+    @Test
+    void owningModuleClaimsMainClassAndRemovesItFromManifest() {
+        Archive owner = archive("foo.bar", null, Path.of("."));
+        Manifest m = manifestWithMainClass("foo.bar/foo.MainFile");
+        // The owner keeps the main class (emitted via --main-class) ...
+        assertTrue(owner.setMainClass(m));
+        // ... and the raw `module/Class` value is removed from the written manifest.
+        assertNull(mainClassOf(m));
+    }
+
+    /**
+     * Verifies that {@link Archive#setMainClass(Manifest)} does <em>not</em> take ownership fo
+     * a module-qualified {@code "module/Class"} main class when the module name does not match.
+     * The {@code "foo.bar/"} prefix in this test (the module name) is a Maven extension.
+     * The standard <abbr>JAR</abbr> specification accepts only the {@code "foo.MainFile"} class name.
+     */
+    @Test
+    void nonOwningModuleRejectsMainClass() {
+        Archive nonOwner = archive("foo.bar.more", null, Path.of("."));
+        Manifest m = manifestWithMainClass("foo.bar/foo.MainFile");
+        assertFalse(nonOwner.setMainClass(m));
+        assertNull(mainClassOf(m));
+    }
+
+    /**
+     * Tests that which module keeps the main class does not depend on processing order.
+     * {@link ToolExecutor} gives each module a <em>copy</em> of the shared plugin manifest;
+     * this pins that the owning module (and only it) keeps the main class in either order,
+     * and that the shared manifest is never consumed.
+     */
+    @Test
+    void mainClassAssignmentIsIndependentOfModuleOrder() {
+        assertOwnership("foo.bar", "foo.bar.more", true); // owner processed first
+        assertOwnership("foo.bar.more", "foo.bar", false); // non-owner processed first
+    }
+
+    /**
+     * Helper method for {@link #mainClassAssignmentIsIndependentOfModuleOrder()}.
+     * Asserts that {@link Archive#setMainClass(Manifest)} returns {@code true}
+     * for the owner and {@code false} for the other module.
+     *
+     * <p>The {@code "foo.bar/"} prefix in this test (the module name) is a Maven extension.
+     * The standard <abbr>JAR</abbr> specification accepts only the {@code "foo.MainFile"} class name.
+     * This extension is used by the plugin for identifying in which <abbr>JAR</abbr> file to add this
+     * {@code Main-Class} manifest entry.</p>
+     */
+    private static void assertOwnership(String first, String second, boolean ownerIsFirst) {
+        final Path path = Path.of(".");
+        final Manifest shared = manifestWithMainClass("foo.bar/foo.MainFile");
+        final Manifest m1 = new Manifest(shared);
+        final Manifest m2 = new Manifest(shared);
+        assertEquals(ownerIsFirst, archive(first, null, path).setMainClass(m1));
+        assertEquals(!ownerIsFirst, archive(second, null, path).setMainClass(m2));
+        // Per-module copies must leave the shared plugin manifest untouched.
+        assertEquals("foo.bar/foo.MainFile", mainClassOf(shared));
+        assertNull(mainClassOf(m1));
+        assertNull(mainClassOf(m2));
+    }
+
+    /**
+     * Tests that {@code FileSet} association to target release is consistent regardless creation order.

Review Comment:
   Done.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "elharo (via GitHub)" <gi...@apache.org>.
elharo commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3945382693


##########
src/main/java/org/apache/maven/plugins/jar/DirectoryRole.java:
##########
@@ -0,0 +1,73 @@
+/*
+ * 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.jar;
+
+/**
+ * Directories that the archiver needs to handle in a special way.
+ */
+enum DirectoryRole {
+    /**
+     * The root directory. This is usually {@code "target/classes"}.
+     * The next locations can be {@link #META_INF}, {@link #NAMED_MODULE} or {@link #RESOURCES}.
+     */
+    ROOT,
+
+    /**
+     * The {@code "META-INF"} or {@code "<module>/META-INF"} directory.
+     * This is part of the <abbr>JAR</abbr> specification.
+     * The next locations can be {@link #VERSIONS} or {@link #VERSIONS_MODULAR}.
+     */
+    META_INF,
+
+    /**
+     * The {@code "META-INF/versions"} or {@code "<module>/META-INF/versions"} directory.
+     * This is part of the <abbr>JAR</abbr> specification, except the {@code <module>} prefix.
+     * The sub-directories are named according to Java releases such as "21".
+     * The next location can only be {@link #RESOURCES}.
+     */
+    VERSIONS,
+
+    /**
+     * The Maven-specific {@code "META-INF/versions-modular"} directory.
+     * {@code "<module>/META-INF/versions-modular"} is not forbidden, but does not make sense.
+     * The sub-directories are named according to Java releases such as "21".
+     * The next location can only be {@link #MODULES}.
+     */
+    VERSIONS_MODULAR,
+
+    /**
+     * The Maven-specific {@code "META-INF/versions-modular"} directory.

Review Comment:
   Why is this the same as VERSIONS_MODULAR? Is one of them off in the docs?



##########
src/main/java/org/apache/maven/plugins/jar/ExcludedFiles.java:
##########
@@ -0,0 +1,146 @@
+/*
+ * 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.jar;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardCopyOption;
+import java.util.List;
+
+/**
+ * A list of files to temporarily move outside the directory to package in a <abbr>JAR</abbr> archive.
+ * This class is needed when the {@link AbstractJarMojo} configuration has include or exclude filters.
+ * Excluded files are temporarily moved outside the directory to archive.
+ * We move these files for making possible to specify the whole directory to the {@code jar} tool.
+ * This approach is used instead of enumerating files in arguments given to the {@code jar} tool because
+ * such enumeration cannot contain directory entries (otherwise the whole directory would be included).
+ * Some software such as Spring applications component scan relies on the presence of directory entries.
+ */
+final class ExcludedFiles implements Closeable {
+    /**
+     * The paths of files or directories to temporarily move in another directory.
+     */
+    private final Path[] original;
+
+    /**
+     * The paths where files or directories were moved.
+     * For each index <var>i</var>, the original path of {@code moved[i]} was {@code original[i]}.
+     */
+    private final Path[] moved;
+
+    /**
+     * Temporary directory which will contain the {@code moved} files.
+     * It should be a parent directory of {@link #original} files for
+     * increasing the chances that it is on the same file system.
+     */
+    private final Path temporaryDirectory;
+
+    /**
+     * Index of the first path which is a directory instead of a file.
+     * All paths before this index in the {@link #original} and {@link #moved} arrays are files.
+     * All paths at this index and after this index are directories.
+     */
+    private final int indexOfFirstDirectory;
+
+    /**
+     * Creates a new list of files to move in a temporary directory.
+     *
+     * @param directory the directory which was scanned for files to include in the <abbr>JAR</abbr>
+     * @param excludedFiles paths of files to temporarily move in another directory

Review Comment:
   move in --> move to



##########
src/main/java/org/apache/maven/plugins/jar/TimestampCheck.java:
##########
@@ -0,0 +1,261 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.nio.file.attribute.FileTime;
+import java.util.Collection;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+
+import org.apache.maven.api.plugin.Log;
+
+/**
+ * Checks file timestamps in order to determine if anything changed compared to an existing <abbr>JAR</abbr> file.
+ * This class may scan directories, but only if they have not already been visited by {@link FileCollector}.
+ * The latter can only occur if {@link FileCollector} has no {@code PathMatcher}.
+ * Therefore, this class uses no {@code PathMatcher}.
+ *
+ * <h2>Ignore files</h2>

Review Comment:
   get rid of the h2



##########
src/it/jar-without-sources/pom.xml:
##########
@@ -0,0 +1,44 @@
+<?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>jar-without-sources</artifactId>
+  <version>1.0-SNAPSHOT</version>
+  <packaging>jar</packaging>
+  <name>jar-without-sources-it</name>
+  <description>This project has neither `src/main` nor `src/test`, so nothing is compiled
+    and the `target` directory is never created by an earlier lifecycle phase.
+    Versions 3.x of the JAR plugin still produced an empty, manifest-only JAR in that case.
+    This IT verifies that versions 4.x of the JAR plugin has the same behavior for compatibility purposes.

Review Comment:
   version 4.x
   
   or
   
   has --> have



##########
src/test/java/org/apache/maven/plugins/jar/ArchiveTest.java:
##########
@@ -0,0 +1,257 @@
+/*
+ * 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.jar;
+
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Unit tests for {@link Archive}, focused on the two behaviours that are otherwise only
+ * exercised by integration tests whose outcome depends on the (unspecified) filesystem
+ * directory-iteration order, and therefore pass on some platforms while failing on others.
+ */
+class ArchiveTest {
+
+    /**
+     * Creates an {@code Archive} suitable for a unit test. {@code forceCreation = true} skips the
+     * existing-JAR timestamp check, so the (here {@code null}) logger is never dereferenced.
+     */
+    private static Archive archive(String moduleName, Runtime.Version version, Path directory) {
+        return new Archive(directory.resolve("out.jar"), moduleName, version, directory, true, null);
+    }
+
+    /**
+     * Creates a manifest with the main class attribute set to the given value.
+     *
+     * @param value value of the main class attribute
+     * @return a new manifest with the given attribute value
+     */
+    private static Manifest manifestWithMainClass(String value) {
+        Manifest m = new Manifest();
+        Attributes attributes = m.getMainAttributes();
+        attributes.put(Attributes.Name.MANIFEST_VERSION, "1.0");
+        attributes.put(Attributes.Name.MAIN_CLASS, value);
+        return m;
+    }
+
+    /**
+     * Returns the value of the main class attribute.
+     *
+     * @param m the manifest from which to get the value
+     * @return the main class attribute value, or {@code null} if none
+     */
+    private static Object mainClassOf(Manifest m) {
+        return m.getMainAttributes().get(Attributes.Name.MAIN_CLASS);
+    }
+
+    /**
+     * Verifies that {@link Archive#setMainClass(Manifest)} takes ownership for a module-qualified
+     * {@code "module/Class"} main class.
+     *
+     * The {@code "foo.bar/"} prefix in this test (the module name) is a Maven extension.
+     * The standard <abbr>JAR</abbr> specification accepts only the {@code "foo.MainFile"} class name.
+     */
+    @Test
+    void owningModuleClaimsMainClassAndRemovesItFromManifest() {
+        Archive owner = archive("foo.bar", null, Path.of("."));
+        Manifest m = manifestWithMainClass("foo.bar/foo.MainFile");
+        // The owner keeps the main class (emitted via --main-class) ...
+        assertTrue(owner.setMainClass(m));
+        // ... and the raw `module/Class` value is removed from the written manifest.
+        assertNull(mainClassOf(m));
+    }
+
+    /**
+     * Verifies that {@link Archive#setMainClass(Manifest)} does <em>not</em> take ownership of
+     * a module-qualified {@code "module/Class"} main class when the module name does not match.
+     * The {@code "foo.bar/"} prefix in this test (the module name) is a Maven extension.
+     * The standard <abbr>JAR</abbr> specification accepts only the {@code "foo.MainFile"} class name.
+     */
+    @Test
+    void nonOwningModuleRejectsMainClass() {
+        Archive nonOwner = archive("foo.bar.more", null, Path.of("."));
+        Manifest m = manifestWithMainClass("foo.bar/foo.MainFile");
+        assertFalse(nonOwner.setMainClass(m));
+        assertNull(mainClassOf(m));
+    }
+
+    /**
+     * Tests that which module keeps the main class does not depend on processing order.
+     * {@link ToolExecutor} gives each module a <em>copy</em> of the shared plugin manifest;
+     * this pins that the owning module (and only it) keeps the main class in either order,
+     * and that the shared manifest is never consumed.
+     */
+    @Test
+    void mainClassAssignmentIsIndependentOfModuleOrder() {
+        assertOwnership("foo.bar", "foo.bar.more", true); // owner processed first
+        assertOwnership("foo.bar.more", "foo.bar", false); // non-owner processed first
+    }
+
+    /**
+     * Helper method for {@link #mainClassAssignmentIsIndependentOfModuleOrder()}.
+     * Asserts that {@link Archive#setMainClass(Manifest)} returns {@code true}
+     * for the owner and {@code false} for the other module.
+     *
+     * <p>The {@code "foo.bar/"} prefix in this test (the module name) is a Maven extension.
+     * The standard <abbr>JAR</abbr> specification accepts only the {@code "foo.MainFile"} class name.
+     * This extension is used by the plugin for identifying in which <abbr>JAR</abbr> file to add this
+     * {@code Main-Class} manifest entry.</p>
+     */
+    private static void assertOwnership(String first, String second, boolean ownerIsFirst) {
+        final Path path = Path.of(".");
+        final Manifest shared = manifestWithMainClass("foo.bar/foo.MainFile");
+        final Manifest m1 = new Manifest(shared);
+        final Manifest m2 = new Manifest(shared);
+        assertEquals(ownerIsFirst, archive(first, null, path).setMainClass(m1));
+        assertEquals(!ownerIsFirst, archive(second, null, path).setMainClass(m2));
+        // Per-module copies must leave the shared plugin manifest untouched.
+        assertEquals("foo.bar/foo.MainFile", mainClassOf(shared));
+        assertNull(mainClassOf(m1));
+        assertNull(mainClassOf(m2));
+    }
+
+    /**
+     * Tests that {@code FileSet} association to target release is consistent regardless of creation order.
+     * Verifies that the base (version-less) release binds to the true {@code <module>} directory even
+     * when the {@link Archive} was first created from a {@code META-INF/versions-modular/<n>/<module>}
+     * directory (which happens when the file-tree walk visits the version directory first).
+     */
+    @Test
+    void baseReleaseBindingIsIndependentOfDirectoryOrder() {
+        final Path base = Path.of("classes", "foo.bar");
+        final Path v16 = Path.of("classes", "META-INF", "versions-modular", "16", "foo.bar");
+        final Runtime.Version r16 = Runtime.Version.parse("16");
+
+        // Version-directory first (the failing order): Archive seeded from v16, base registered later.
+        final Archive a = archive("foo.bar", r16, v16);
+        assertNotSame(a.newTargetRelease(v16, r16), a.newTargetRelease(base, null));
+        assertEquals(base, a.baseRelease().directory, "base must rebind to the version-less directory");
+
+        // Base-directory first: still correct.
+        final Archive b = archive("foo.bar", null, base);
+        assertNotSame(b.newTargetRelease(base, null), b.newTargetRelease(v16, r16));
+        assertEquals(base, b.baseRelease().directory);
+    }
+
+    /**
+     * Ensures that all path are relative.
+     *
+     * <h4>Historical note</h4>
+     * In our tests, it seems that the first <abbr>JAR</abbr> entry after the {@code -C} option
+     * must be relative, and only that file. Furthermore, it seems that this file must be the
+     * shortest. We tried to apply this heuristic rules in a branch, but it does not save a lot

Review Comment:
   file is the shortest or file name is the shortest?



##########
src/test/java/org/apache/maven/plugins/jar/ArchiveTest.java:
##########
@@ -0,0 +1,257 @@
+/*
+ * 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.jar;
+
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Unit tests for {@link Archive}, focused on the two behaviours that are otherwise only
+ * exercised by integration tests whose outcome depends on the (unspecified) filesystem
+ * directory-iteration order, and therefore pass on some platforms while failing on others.
+ */
+class ArchiveTest {
+
+    /**
+     * Creates an {@code Archive} suitable for a unit test. {@code forceCreation = true} skips the
+     * existing-JAR timestamp check, so the (here {@code null}) logger is never dereferenced.
+     */
+    private static Archive archive(String moduleName, Runtime.Version version, Path directory) {
+        return new Archive(directory.resolve("out.jar"), moduleName, version, directory, true, null);
+    }
+
+    /**
+     * Creates a manifest with the main class attribute set to the given value.
+     *
+     * @param value value of the main class attribute
+     * @return a new manifest with the given attribute value
+     */
+    private static Manifest manifestWithMainClass(String value) {
+        Manifest m = new Manifest();
+        Attributes attributes = m.getMainAttributes();
+        attributes.put(Attributes.Name.MANIFEST_VERSION, "1.0");
+        attributes.put(Attributes.Name.MAIN_CLASS, value);
+        return m;
+    }
+
+    /**
+     * Returns the value of the main class attribute.
+     *
+     * @param m the manifest from which to get the value
+     * @return the main class attribute value, or {@code null} if none
+     */
+    private static Object mainClassOf(Manifest m) {
+        return m.getMainAttributes().get(Attributes.Name.MAIN_CLASS);
+    }
+
+    /**
+     * Verifies that {@link Archive#setMainClass(Manifest)} takes ownership for a module-qualified
+     * {@code "module/Class"} main class.
+     *
+     * The {@code "foo.bar/"} prefix in this test (the module name) is a Maven extension.
+     * The standard <abbr>JAR</abbr> specification accepts only the {@code "foo.MainFile"} class name.
+     */
+    @Test
+    void owningModuleClaimsMainClassAndRemovesItFromManifest() {
+        Archive owner = archive("foo.bar", null, Path.of("."));
+        Manifest m = manifestWithMainClass("foo.bar/foo.MainFile");
+        // The owner keeps the main class (emitted via --main-class) ...
+        assertTrue(owner.setMainClass(m));
+        // ... and the raw `module/Class` value is removed from the written manifest.
+        assertNull(mainClassOf(m));
+    }
+
+    /**
+     * Verifies that {@link Archive#setMainClass(Manifest)} does <em>not</em> take ownership of
+     * a module-qualified {@code "module/Class"} main class when the module name does not match.
+     * The {@code "foo.bar/"} prefix in this test (the module name) is a Maven extension.
+     * The standard <abbr>JAR</abbr> specification accepts only the {@code "foo.MainFile"} class name.
+     */
+    @Test
+    void nonOwningModuleRejectsMainClass() {
+        Archive nonOwner = archive("foo.bar.more", null, Path.of("."));
+        Manifest m = manifestWithMainClass("foo.bar/foo.MainFile");
+        assertFalse(nonOwner.setMainClass(m));
+        assertNull(mainClassOf(m));
+    }
+
+    /**
+     * Tests that which module keeps the main class does not depend on processing order.
+     * {@link ToolExecutor} gives each module a <em>copy</em> of the shared plugin manifest;
+     * this pins that the owning module (and only it) keeps the main class in either order,
+     * and that the shared manifest is never consumed.
+     */
+    @Test
+    void mainClassAssignmentIsIndependentOfModuleOrder() {
+        assertOwnership("foo.bar", "foo.bar.more", true); // owner processed first
+        assertOwnership("foo.bar.more", "foo.bar", false); // non-owner processed first
+    }
+
+    /**
+     * Helper method for {@link #mainClassAssignmentIsIndependentOfModuleOrder()}.
+     * Asserts that {@link Archive#setMainClass(Manifest)} returns {@code true}
+     * for the owner and {@code false} for the other module.
+     *
+     * <p>The {@code "foo.bar/"} prefix in this test (the module name) is a Maven extension.
+     * The standard <abbr>JAR</abbr> specification accepts only the {@code "foo.MainFile"} class name.
+     * This extension is used by the plugin for identifying in which <abbr>JAR</abbr> file to add this

Review Comment:
    for identifying in which --> to identify which



##########
src/main/java/org/apache/maven/plugins/jar/ExcludedFiles.java:
##########
@@ -0,0 +1,146 @@
+/*
+ * 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.jar;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardCopyOption;
+import java.util.List;
+
+/**
+ * A list of files to temporarily move outside the directory to package in a <abbr>JAR</abbr> archive.
+ * This class is needed when the {@link AbstractJarMojo} configuration has include or exclude filters.
+ * Excluded files are temporarily moved outside the directory to archive.
+ * We move these files for making possible to specify the whole directory to the {@code jar} tool.

Review Comment:
   We move these files to make it possible to pass an entire directory to the {@code jar} tool.



##########
src/main/java/org/apache/maven/plugins/jar/FileCollector.java:
##########
@@ -0,0 +1,542 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.PathMatcher;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Deque;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.services.PathMatcherFactory;
+
+/**
+ * Dispatch the files from the output directory into the <abbr>JAR</abbr> files to create.
+ * Instead of just archiving as-is the content of the output directory, this class separates
+ * the following subdirectories to the options listed below:
+ *
+ * <ul>
+ *   <li>The {@code META-INF/MANIFEST.MF} file will be given to the {@code --manifest} option.</li>
+ *   <li>Files in the following directories will be given to the {@code --release} option:
+ *     <ul>
+ *       <li>{@code META-INF/versions/}</li>
+ *       <li>{@code META-INF/versions-modular/<module>/}</li>
+ *       <li>{@code <module>/META-INF/versions/}</li>
+ *     </ul>
+ *   </li>
+ * </ul>
+ *
+ * The reason for using the {@code --release} and {@code --manifest} options instead of adding explicitly
+ * the entries is because the options allow the {@code jar} tool to perform additional verifications.
+ * For example, when using the {@code --release} option, {@code jar} verifies the <abbr>API</abbr> compatibility.

Review Comment:
   the <abbr>API</abbr> compatibility --> <abbr>API</abbr> compatibility



##########
src/main/java/org/apache/maven/plugins/jar/ExcludedFiles.java:
##########
@@ -0,0 +1,146 @@
+/*
+ * 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.jar;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardCopyOption;
+import java.util.List;
+
+/**
+ * A list of files to temporarily move outside the directory to package in a <abbr>JAR</abbr> archive.
+ * This class is needed when the {@link AbstractJarMojo} configuration has include or exclude filters.
+ * Excluded files are temporarily moved outside the directory to archive.
+ * We move these files for making possible to specify the whole directory to the {@code jar} tool.
+ * This approach is used instead of enumerating files in arguments given to the {@code jar} tool because
+ * such enumeration cannot contain directory entries (otherwise the whole directory would be included).
+ * Some software such as Spring applications component scan relies on the presence of directory entries.
+ */
+final class ExcludedFiles implements Closeable {
+    /**
+     * The paths of files or directories to temporarily move in another directory.
+     */
+    private final Path[] original;
+
+    /**
+     * The paths where files or directories were moved.
+     * For each index <var>i</var>, the original path of {@code moved[i]} was {@code original[i]}.
+     */
+    private final Path[] moved;
+
+    /**
+     * Temporary directory which will contain the {@code moved} files.
+     * It should be a parent directory of {@link #original} files for
+     * increasing the chances that it is on the same file system.
+     */
+    private final Path temporaryDirectory;
+
+    /**
+     * Index of the first path which is a directory instead of a file.
+     * All paths before this index in the {@link #original} and {@link #moved} arrays are files.
+     * All paths at this index and after this index are directories.
+     */
+    private final int indexOfFirstDirectory;
+
+    /**
+     * Creates a new list of files to move in a temporary directory.
+     *
+     * @param directory the directory which was scanned for files to include in the <abbr>JAR</abbr>
+     * @param excludedFiles paths of files to temporarily move in another directory
+     * @param excludedDirectories paths of directories to temporarily move in another directory

Review Comment:
   move in --> move to



##########
src/main/java/org/apache/maven/plugins/jar/FileCollector.java:
##########
@@ -0,0 +1,542 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.PathMatcher;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Deque;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.services.PathMatcherFactory;
+
+/**
+ * Dispatch the files from the output directory into the <abbr>JAR</abbr> files to create.
+ * Instead of just archiving as-is the content of the output directory, this class separates
+ * the following subdirectories to the options listed below:
+ *
+ * <ul>
+ *   <li>The {@code META-INF/MANIFEST.MF} file will be given to the {@code --manifest} option.</li>
+ *   <li>Files in the following directories will be given to the {@code --release} option:
+ *     <ul>
+ *       <li>{@code META-INF/versions/}</li>
+ *       <li>{@code META-INF/versions-modular/<module>/}</li>
+ *       <li>{@code <module>/META-INF/versions/}</li>
+ *     </ul>
+ *   </li>
+ * </ul>
+ *
+ * The reason for using the {@code --release} and {@code --manifest} options instead of adding explicitly

Review Comment:
   adding the entries explicitly



##########
src/main/java/org/apache/maven/plugins/jar/FileCollector.java:
##########
@@ -0,0 +1,542 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.PathMatcher;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Deque;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.services.PathMatcherFactory;
+
+/**
+ * Dispatch the files from the output directory into the <abbr>JAR</abbr> files to create.

Review Comment:
   Dispatch might not be the right word here



##########
src/main/java/org/apache/maven/plugins/jar/ExcludedFiles.java:
##########
@@ -0,0 +1,146 @@
+/*
+ * 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.jar;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardCopyOption;
+import java.util.List;
+
+/**
+ * A list of files to temporarily move outside the directory to package in a <abbr>JAR</abbr> archive.
+ * This class is needed when the {@link AbstractJarMojo} configuration has include or exclude filters.
+ * Excluded files are temporarily moved outside the directory to archive.
+ * We move these files for making possible to specify the whole directory to the {@code jar} tool.
+ * This approach is used instead of enumerating files in arguments given to the {@code jar} tool because
+ * such enumeration cannot contain directory entries (otherwise the whole directory would be included).
+ * Some software such as Spring applications component scan relies on the presence of directory entries.
+ */
+final class ExcludedFiles implements Closeable {
+    /**
+     * The paths of files or directories to temporarily move in another directory.
+     */
+    private final Path[] original;
+
+    /**
+     * The paths where files or directories were moved.
+     * For each index <var>i</var>, the original path of {@code moved[i]} was {@code original[i]}.
+     */
+    private final Path[] moved;
+
+    /**
+     * Temporary directory which will contain the {@code moved} files.
+     * It should be a parent directory of {@link #original} files for
+     * increasing the chances that it is on the same file system.
+     */
+    private final Path temporaryDirectory;
+
+    /**
+     * Index of the first path which is a directory instead of a file.
+     * All paths before this index in the {@link #original} and {@link #moved} arrays are files.
+     * All paths at this index and after this index are directories.
+     */
+    private final int indexOfFirstDirectory;
+
+    /**
+     * Creates a new list of files to move in a temporary directory.
+     *
+     * @param directory the directory which was scanned for files to include in the <abbr>JAR</abbr>
+     * @param excludedFiles paths of files to temporarily move in another directory
+     * @param excludedDirectories paths of directories to temporarily move in another directory
+     * @throws IOException if an error occurred while creating the temporary directory.
+     */
+    ExcludedFiles(Path directory, List<Path> excludedFiles, List<Path> excludedDirectories) throws IOException {
+        indexOfFirstDirectory = excludedFiles.size();

Review Comment:
   This is backwards from the usual way this is done. Not necessarily wrong, but normally the files to include would be copied into a temporary location instead. Is any cleanup needed to move these files back if something fails?
   
   I hope this is all working only in the target directory. We shouldn't be moving files around anywhere else. 



##########
src/main/java/org/apache/maven/plugins/jar/FileCollector.java:
##########
@@ -0,0 +1,542 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.PathMatcher;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Deque;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.services.PathMatcherFactory;
+
+/**
+ * Dispatch the files from the output directory into the <abbr>JAR</abbr> files to create.
+ * Instead of just archiving as-is the content of the output directory, this class separates
+ * the following subdirectories to the options listed below:
+ *
+ * <ul>
+ *   <li>The {@code META-INF/MANIFEST.MF} file will be given to the {@code --manifest} option.</li>
+ *   <li>Files in the following directories will be given to the {@code --release} option:
+ *     <ul>
+ *       <li>{@code META-INF/versions/}</li>
+ *       <li>{@code META-INF/versions-modular/<module>/}</li>
+ *       <li>{@code <module>/META-INF/versions/}</li>
+ *     </ul>
+ *   </li>
+ * </ul>
+ *
+ * The reason for using the {@code --release} and {@code --manifest} options instead of adding explicitly
+ * the entries is because the options allow the {@code jar} tool to perform additional verifications.
+ * For example, when using the {@code --release} option, {@code jar} verifies the <abbr>API</abbr> compatibility.
+ */
+final class FileCollector extends SimpleFileVisitor<Path> {
+    /**
+     * The file to check for deciding whether the <abbr>JAR</abbr> is modular.
+     */
+    static final String MODULE_DESCRIPTOR_FILE_NAME = "module-info.class";
+
+    /**
+     * The {@value} directory.
+     * This is part of <abbr>JAR</abbr> file specification.
+     */
+    private static final String VERSIONS = "versions";
+
+    /**
+     * The {@value} directory.
+     * This is Maven-specific.
+     */
+    private static final String VERSIONS_MODULAR = "versions-modular";
+
+    /**
+     * Context (logger, configuration) in which the <abbr>JAR</abbr> file are created.
+     */
+    private final ToolExecutor context;
+
+    /**
+     * Whether to detect multi-release <abbr>JAR</abbr> files.
+     * The default value is {@code true}.
+     *
+     * @see AbstractJarMojo#detectMultiReleaseJar
+     */
+    private final boolean detectMultiReleaseJar;
+
+    /**
+     * The root directory to traverse. It will be used for temporarily moving excluded files.
+     */
+    private final Path rootDirectory;
+
+    /**
+     * Combination of includes and excludes path matcher applied on files.
+     */
+    @Nonnull
+    private final PathMatcher fileMatcher;
+
+    /**
+     * Combination of includes and excludes path matcher applied on directories.
+     */
+    @Nonnull
+    private final PathMatcher directoryMatcher;
+
+    /**
+     * Files to exclude. These files will be moved to a temporary location
+     * for allowing {@link ToolExecutor} to specify whole directories to the {@code jar} tool.

Review Comment:
   to allow



##########
src/main/java/org/apache/maven/plugins/jar/FileCollector.java:
##########
@@ -0,0 +1,542 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.PathMatcher;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Deque;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.services.PathMatcherFactory;
+
+/**
+ * Dispatch the files from the output directory into the <abbr>JAR</abbr> files to create.
+ * Instead of just archiving as-is the content of the output directory, this class separates

Review Comment:
   Instead of just archiving the content of the output directory as-is,



##########
src/main/java/org/apache/maven/plugins/jar/FileCollector.java:
##########
@@ -0,0 +1,542 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.PathMatcher;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Deque;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.services.PathMatcherFactory;
+
+/**
+ * Dispatch the files from the output directory into the <abbr>JAR</abbr> files to create.
+ * Instead of just archiving as-is the content of the output directory, this class separates
+ * the following subdirectories to the options listed below:
+ *
+ * <ul>
+ *   <li>The {@code META-INF/MANIFEST.MF} file will be given to the {@code --manifest} option.</li>
+ *   <li>Files in the following directories will be given to the {@code --release} option:
+ *     <ul>
+ *       <li>{@code META-INF/versions/}</li>
+ *       <li>{@code META-INF/versions-modular/<module>/}</li>
+ *       <li>{@code <module>/META-INF/versions/}</li>
+ *     </ul>
+ *   </li>
+ * </ul>
+ *
+ * The reason for using the {@code --release} and {@code --manifest} options instead of adding explicitly
+ * the entries is because the options allow the {@code jar} tool to perform additional verifications.
+ * For example, when using the {@code --release} option, {@code jar} verifies the <abbr>API</abbr> compatibility.
+ */
+final class FileCollector extends SimpleFileVisitor<Path> {
+    /**
+     * The file to check for deciding whether the <abbr>JAR</abbr> is modular.
+     */
+    static final String MODULE_DESCRIPTOR_FILE_NAME = "module-info.class";
+
+    /**
+     * The {@value} directory.
+     * This is part of <abbr>JAR</abbr> file specification.
+     */
+    private static final String VERSIONS = "versions";
+
+    /**
+     * The {@value} directory.
+     * This is Maven-specific.
+     */
+    private static final String VERSIONS_MODULAR = "versions-modular";
+
+    /**
+     * Context (logger, configuration) in which the <abbr>JAR</abbr> file are created.
+     */
+    private final ToolExecutor context;
+
+    /**
+     * Whether to detect multi-release <abbr>JAR</abbr> files.
+     * The default value is {@code true}.
+     *
+     * @see AbstractJarMojo#detectMultiReleaseJar
+     */
+    private final boolean detectMultiReleaseJar;
+
+    /**
+     * The root directory to traverse. It will be used for temporarily moving excluded files.
+     */
+    private final Path rootDirectory;
+
+    /**
+     * Combination of includes and excludes path matcher applied on files.
+     */
+    @Nonnull
+    private final PathMatcher fileMatcher;
+
+    /**
+     * Combination of includes and excludes path matcher applied on directories.
+     */
+    @Nonnull
+    private final PathMatcher directoryMatcher;
+
+    /**
+     * Files to exclude. These files will be moved to a temporary location
+     * for allowing {@link ToolExecutor} to specify whole directories to the {@code jar} tool.
+     * Specifying whole directories is preferable to enumerating the files because otherwise,
+     * the generated <abbr>JAR</abbr> file contains only entries for the files and is missing
+     * entries for the directories.
+     *
+     * <p>This field is {@code null} if it is not possible to have any excluded file
+     * (because there is no include/exclude filters).</p>
+     */
+    @Nullable
+    private final List<Path> excludedFiles;
+
+    /**
+     * Directories to exclude. This field serves the same purpose as {@link #excludedFiles},
+     * but where the sources a directories instead of files.

Review Comment:
   sources are



##########
src/main/java/org/apache/maven/plugins/jar/FileCollector.java:
##########
@@ -0,0 +1,542 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.PathMatcher;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Deque;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.services.PathMatcherFactory;
+
+/**
+ * Dispatch the files from the output directory into the <abbr>JAR</abbr> files to create.
+ * Instead of just archiving as-is the content of the output directory, this class separates
+ * the following subdirectories to the options listed below:
+ *
+ * <ul>
+ *   <li>The {@code META-INF/MANIFEST.MF} file will be given to the {@code --manifest} option.</li>
+ *   <li>Files in the following directories will be given to the {@code --release} option:
+ *     <ul>
+ *       <li>{@code META-INF/versions/}</li>
+ *       <li>{@code META-INF/versions-modular/<module>/}</li>
+ *       <li>{@code <module>/META-INF/versions/}</li>
+ *     </ul>
+ *   </li>
+ * </ul>
+ *
+ * The reason for using the {@code --release} and {@code --manifest} options instead of adding explicitly
+ * the entries is because the options allow the {@code jar} tool to perform additional verifications.
+ * For example, when using the {@code --release} option, {@code jar} verifies the <abbr>API</abbr> compatibility.
+ */
+final class FileCollector extends SimpleFileVisitor<Path> {
+    /**
+     * The file to check for deciding whether the <abbr>JAR</abbr> is modular.

Review Comment:
   for deciding --> to decide



##########
src/main/java/org/apache/maven/plugins/jar/FileCollector.java:
##########
@@ -0,0 +1,542 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.PathMatcher;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Deque;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.services.PathMatcherFactory;
+
+/**
+ * Dispatch the files from the output directory into the <abbr>JAR</abbr> files to create.
+ * Instead of just archiving as-is the content of the output directory, this class separates
+ * the following subdirectories to the options listed below:
+ *
+ * <ul>
+ *   <li>The {@code META-INF/MANIFEST.MF} file will be given to the {@code --manifest} option.</li>
+ *   <li>Files in the following directories will be given to the {@code --release} option:
+ *     <ul>
+ *       <li>{@code META-INF/versions/}</li>
+ *       <li>{@code META-INF/versions-modular/<module>/}</li>
+ *       <li>{@code <module>/META-INF/versions/}</li>
+ *     </ul>
+ *   </li>
+ * </ul>
+ *
+ * The reason for using the {@code --release} and {@code --manifest} options instead of adding explicitly
+ * the entries is because the options allow the {@code jar} tool to perform additional verifications.
+ * For example, when using the {@code --release} option, {@code jar} verifies the <abbr>API</abbr> compatibility.
+ */
+final class FileCollector extends SimpleFileVisitor<Path> {
+    /**
+     * The file to check for deciding whether the <abbr>JAR</abbr> is modular.
+     */
+    static final String MODULE_DESCRIPTOR_FILE_NAME = "module-info.class";
+
+    /**
+     * The {@value} directory.
+     * This is part of <abbr>JAR</abbr> file specification.
+     */
+    private static final String VERSIONS = "versions";
+
+    /**
+     * The {@value} directory.

Review Comment:
   again, why the same directory as above?



##########
src/test/java/org/apache/maven/plugins/jar/ArchiveTest.java:
##########
@@ -0,0 +1,257 @@
+/*
+ * 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.jar;
+
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Unit tests for {@link Archive}, focused on the two behaviours that are otherwise only
+ * exercised by integration tests whose outcome depends on the (unspecified) filesystem
+ * directory-iteration order, and therefore pass on some platforms while failing on others.
+ */
+class ArchiveTest {
+
+    /**
+     * Creates an {@code Archive} suitable for a unit test. {@code forceCreation = true} skips the
+     * existing-JAR timestamp check, so the (here {@code null}) logger is never dereferenced.
+     */
+    private static Archive archive(String moduleName, Runtime.Version version, Path directory) {
+        return new Archive(directory.resolve("out.jar"), moduleName, version, directory, true, null);
+    }
+
+    /**
+     * Creates a manifest with the main class attribute set to the given value.
+     *
+     * @param value value of the main class attribute
+     * @return a new manifest with the given attribute value
+     */
+    private static Manifest manifestWithMainClass(String value) {
+        Manifest m = new Manifest();
+        Attributes attributes = m.getMainAttributes();
+        attributes.put(Attributes.Name.MANIFEST_VERSION, "1.0");
+        attributes.put(Attributes.Name.MAIN_CLASS, value);
+        return m;
+    }
+
+    /**
+     * Returns the value of the main class attribute.
+     *
+     * @param m the manifest from which to get the value

Review Comment:
   m --> manifest



##########
src/main/java/org/apache/maven/plugins/jar/ToolExecutor.java:
##########
@@ -0,0 +1,551 @@
+/*
+ * 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.jar;
+
+import javax.lang.model.SourceVersion;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+import java.util.spi.ToolProvider;
+
+import org.apache.maven.api.Project;
+import org.apache.maven.api.Type;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.MojoException;
+import org.apache.maven.shared.archiver.MavenArchiveConfiguration;
+
+/**
+ * Writer of <abbr>JAR</abbr> files using the information collected by {@link FileCollector}.
+ * This class uses the {@code "jar"} tool provided with the <abbr>JDK</abbr>.
+ */
+final class ToolExecutor {
+    /**
+     * First JDK feature version whose {@code jar} tool can run {@code --validate} on archives
+     * that contain records. Earlier {@code jar} tools failed with "This feature requires ASM8"
+     * (JDK-8282446, fixed by JDK-8282508 in JDK 19 by not backported to a 17u or 18u update).
+     *
+     * @see <a href="https://bugs.openjdk.org/browse/JDK-8282446">JDK-8282446</a>
+     * @see <a href="https://bugs.openjdk.org/browse/JDK-8282508">JDK-8282508</a>
+     */
+    private static final int JDK_FIXING_JAR_VALIDATE = 19;
+
+    /**
+     * First JDK feature version whose {@code jar} tool support the {@code --date} option.
+     */
+    private static final int JDK_SUPPORT_DATE = 19;
+
+    /**
+     * The {@value} attribute. Its value is automatically generated by {@link Manifest},
+     * but may need to be replaced by another value if JDK-independent value is desired
+     * for strictly reproducible builds.
+     */
+    private static final String CREATED_BY = "Created-By";
+
+    /**
+     * The Maven project for which to create an archive.
+     */
+    final Project project;
+
+    /**
+     * {@code "jar"} or {@link "test-jar"}.
+     */
+    private final String artifactType;
+
+    /**
+     * The output directory where to write the <abbr>JAR</abbr> file.
+     * This is usually {@code ${baseDir}/target/}.
+     */
+    private final Path outputDirectory;
+
+    /**
+     * The <abbr>JAR</abbr> file name when package hierarchy is used.
+     * This is usually a file placed in the {@link ToolExecutor#outputDirectory} directory.
+     */
+    private final String finalName;
+
+    /**
+     * The classifier (e.g. "test"), or {@code null} if none.
+     */
+    private final String classifier;
+
+    /**
+     * Whether to validate the <abbr>JAR</abbr> file after its creation.
+     * If {@code null}, a value will be determined automatically based on heuristic rules.
+     */
+    private final Boolean validate;
+
+    /**
+     * The tool to use for creating the <abbr>JAR</abbr> files.
+     */
+    private final ToolProvider tool;
+
+    /**
+     * Where to send messages emitted by the "jar" tool.
+     */
+    private final PrintWriter messageWriter;
+
+    /**
+     * Where to send error messages emitted by the "jar" tool.
+     */
+    private final PrintWriter errorWriter;
+
+    /**
+     * Where the messages sent to {@link #messageWriter} are stored.
+     */
+    private final StringBuffer messages;
+
+    /**
+     * Where the messages sent to {@link #errorWriter} are stored.
+     */
+    private final StringBuffer errors;
+
+    /**
+     * A buffer for the arguments given to the "jar" tool, reused for each module.
+     * Each element of the list must be instances of either {@link String} or {@link Path}.
+     */
+    private final List<Object> arguments;
+
+    /**
+     * The paths to the created archive files.
+     * Map keys are module names or {@code null} if the project does not use module hierarchy.
+     * Values are (<var>type</var>, <var>path</var>) pairs associated with each module where
+     * <var>type</var> is {@code "pom"}, {@code "jar"} or {@code "test-jar"} and <var>path</var>
+     * is the path to the <abbr>POM</abbr> or <abbr>JAR</abbr> file.
+     */
+    private final Map<String, Map<String, Path>> result;
+
+    /**
+     * Mapper from Maven dependencies to Java modules, or {@code null} if the project does not use module hierarchy.
+     * This mapper is created only once for a Maven project and reused for each Java module to archive.
+     *
+     * <p>This field is not used directly by {@code ToolExecutor}. It is defined in this class for transferring
+     * this information from {@link AbstractJarMojo} to {@link PomDerivation.ForModule}.
+     * This is an internal mechanism that should not be public or protected.</p>
+     */
+    PomDerivation pomDerivation;
+
+    /**
+     * Manifest to merge with the manifest found in the files to archive.
+     * This is a manifest built from the {@code <archive>} plugin configuration.
+     * Can be {@code null} if there is noting to add to the existing manifests.
+     */
+    private final Manifest manifestFromPlugin;
+
+    /**
+     * The file from which {@link #manifestFromPlugin} has been read, or {@code null} if none.
+     * If non-null, reading that file must produce the same manifest as {@link #manifestFromPlugin}.
+     * It implies that this field must be {@code null} if {@link #manifestFromPlugin} is the result
+     * of merging elements specified in {@code <archive>} with a file specified in the plugin configuration.
+     */
+    private final Path manifestFile;
+
+    /**
+     * The archive configuration to use.
+     */
+    private final MavenArchiveConfiguration archiveConfiguration;
+
+    /**
+     * The timestamp in ISO-8601 extended offset date-time, or {@code null} if none.
+     * If user provided a value in seconds, it must have been converted to ISO-8601.
+     * This is used for reproducible builds.
+     */
+    private final String outputTimestamp;
+
+    /**
+     * Whether to force to build new <abbr>JAR</abbr> files even if none of the contents appear to have changed.
+     */
+    private final boolean forceCreation;
+
+    /**
+     * Where to send informative or error messages.
+     */
+    private final Log logger;
+
+    /**
+     * Creates a new writer.
+     *
+     * @param mojo the <abbr>MOJO</abbr> from which to get the configuration
+     * @param manifest manifest built from plugin configuration, or {@code null} if none
+     * @param archive the archive configuration
+     * @throws IOException if an error occurred while reading the manifest file
+     */
+    ToolExecutor(AbstractJarMojo mojo, Manifest manifest, MavenArchiveConfiguration archive) throws IOException {
+        project = mojo.project;
+        artifactType = mojo.getType();
+        outputDirectory = mojo.getOutputDirectory();
+        classifier = AbstractJarMojo.nullIfAbsent(mojo.getClassifier());
+        finalName =
+                (mojo.finalName != null) ? mojo.finalName : project.getBuild().getFinalName();
+        forceCreation = mojo.forceCreation;
+        outputTimestamp = mojo.getOutputTimestamp();
+        validate = mojo.getValidate();
+        logger = mojo.log;
+        tool = mojo.getJarTool();
+
+        var buffer = new StringWriter();
+        messages = buffer.getBuffer();
+        messageWriter = new PrintWriter(buffer);
+
+        buffer = new StringWriter();
+        errors = buffer.getBuffer();
+        errorWriter = new PrintWriter(buffer);

Review Comment:
   It's strange we have an errorWriter and a logger. Should we just log error messages instead?



##########
src/main/java/org/apache/maven/plugins/jar/FileCollector.java:
##########
@@ -0,0 +1,542 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.PathMatcher;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Deque;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.services.PathMatcherFactory;
+
+/**
+ * Dispatch the files from the output directory into the <abbr>JAR</abbr> files to create.
+ * Instead of just archiving as-is the content of the output directory, this class separates
+ * the following subdirectories to the options listed below:
+ *
+ * <ul>
+ *   <li>The {@code META-INF/MANIFEST.MF} file will be given to the {@code --manifest} option.</li>
+ *   <li>Files in the following directories will be given to the {@code --release} option:
+ *     <ul>
+ *       <li>{@code META-INF/versions/}</li>
+ *       <li>{@code META-INF/versions-modular/<module>/}</li>
+ *       <li>{@code <module>/META-INF/versions/}</li>
+ *     </ul>
+ *   </li>
+ * </ul>
+ *
+ * The reason for using the {@code --release} and {@code --manifest} options instead of adding explicitly
+ * the entries is because the options allow the {@code jar} tool to perform additional verifications.
+ * For example, when using the {@code --release} option, {@code jar} verifies the <abbr>API</abbr> compatibility.
+ */
+final class FileCollector extends SimpleFileVisitor<Path> {
+    /**
+     * The file to check for deciding whether the <abbr>JAR</abbr> is modular.
+     */
+    static final String MODULE_DESCRIPTOR_FILE_NAME = "module-info.class";
+
+    /**
+     * The {@value} directory.
+     * This is part of <abbr>JAR</abbr> file specification.
+     */
+    private static final String VERSIONS = "versions";
+
+    /**
+     * The {@value} directory.
+     * This is Maven-specific.
+     */
+    private static final String VERSIONS_MODULAR = "versions-modular";
+
+    /**
+     * Context (logger, configuration) in which the <abbr>JAR</abbr> file are created.
+     */
+    private final ToolExecutor context;
+
+    /**
+     * Whether to detect multi-release <abbr>JAR</abbr> files.
+     * The default value is {@code true}.
+     *
+     * @see AbstractJarMojo#detectMultiReleaseJar
+     */
+    private final boolean detectMultiReleaseJar;
+
+    /**
+     * The root directory to traverse. It will be used for temporarily moving excluded files.
+     */
+    private final Path rootDirectory;
+
+    /**
+     * Combination of includes and excludes path matcher applied on files.
+     */
+    @Nonnull
+    private final PathMatcher fileMatcher;
+
+    /**
+     * Combination of includes and excludes path matcher applied on directories.
+     */
+    @Nonnull
+    private final PathMatcher directoryMatcher;
+
+    /**
+     * Files to exclude. These files will be moved to a temporary location
+     * for allowing {@link ToolExecutor} to specify whole directories to the {@code jar} tool.
+     * Specifying whole directories is preferable to enumerating the files because otherwise,
+     * the generated <abbr>JAR</abbr> file contains only entries for the files and is missing
+     * entries for the directories.
+     *
+     * <p>This field is {@code null} if it is not possible to have any excluded file
+     * (because there is no include/exclude filters).</p>
+     */
+    @Nullable
+    private final List<Path> excludedFiles;
+
+    /**
+     * Directories to exclude. This field serves the same purpose as {@link #excludedFiles},
+     * but where the sources a directories instead of files.
+     */
+    @Nullable
+    private final List<Path> excludedDirectories;
+
+    /**
+     * Files found in the output directory when package hierarchy is used.
+     * At most one of {@code packageHierarchy} and {@link #moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Archive packageHierarchy;
+
+    /**
+     * Files found in the output directory when module hierarchy is used. Keys are module names.
+     * At most one of {@link #packageHierarchy} and {@code moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Map<String, Archive> moduleHierarchy;
+
+    /**
+     * The current module being archived. This field is updated every times that {@code FileCollector}
+     * visits a new module directory.
+     */
+    @Nonnull
+    private Archive currentModule;
+
+    /**
+     * The module and target Java release currently being scanned. This field is updated every times that

Review Comment:
   every time



##########
src/test/java/org/apache/maven/plugins/jar/ArchiveTest.java:
##########
@@ -0,0 +1,257 @@
+/*
+ * 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.jar;
+
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Unit tests for {@link Archive}, focused on the two behaviours that are otherwise only
+ * exercised by integration tests whose outcome depends on the (unspecified) filesystem
+ * directory-iteration order, and therefore pass on some platforms while failing on others.
+ */
+class ArchiveTest {
+
+    /**
+     * Creates an {@code Archive} suitable for a unit test. {@code forceCreation = true} skips the
+     * existing-JAR timestamp check, so the (here {@code null}) logger is never dereferenced.
+     */
+    private static Archive archive(String moduleName, Runtime.Version version, Path directory) {
+        return new Archive(directory.resolve("out.jar"), moduleName, version, directory, true, null);
+    }
+
+    /**
+     * Creates a manifest with the main class attribute set to the given value.
+     *
+     * @param value value of the main class attribute
+     * @return a new manifest with the given attribute value
+     */
+    private static Manifest manifestWithMainClass(String value) {
+        Manifest m = new Manifest();

Review Comment:
   m --> manifest



##########
src/main/java/org/apache/maven/plugins/jar/FileCollector.java:
##########
@@ -0,0 +1,542 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.PathMatcher;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Deque;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.services.PathMatcherFactory;
+
+/**
+ * Dispatch the files from the output directory into the <abbr>JAR</abbr> files to create.
+ * Instead of just archiving as-is the content of the output directory, this class separates
+ * the following subdirectories to the options listed below:
+ *
+ * <ul>
+ *   <li>The {@code META-INF/MANIFEST.MF} file will be given to the {@code --manifest} option.</li>
+ *   <li>Files in the following directories will be given to the {@code --release} option:
+ *     <ul>
+ *       <li>{@code META-INF/versions/}</li>
+ *       <li>{@code META-INF/versions-modular/<module>/}</li>
+ *       <li>{@code <module>/META-INF/versions/}</li>
+ *     </ul>
+ *   </li>
+ * </ul>
+ *
+ * The reason for using the {@code --release} and {@code --manifest} options instead of adding explicitly
+ * the entries is because the options allow the {@code jar} tool to perform additional verifications.
+ * For example, when using the {@code --release} option, {@code jar} verifies the <abbr>API</abbr> compatibility.
+ */
+final class FileCollector extends SimpleFileVisitor<Path> {
+    /**
+     * The file to check for deciding whether the <abbr>JAR</abbr> is modular.
+     */
+    static final String MODULE_DESCRIPTOR_FILE_NAME = "module-info.class";
+
+    /**
+     * The {@value} directory.
+     * This is part of <abbr>JAR</abbr> file specification.
+     */
+    private static final String VERSIONS = "versions";
+
+    /**
+     * The {@value} directory.
+     * This is Maven-specific.
+     */
+    private static final String VERSIONS_MODULAR = "versions-modular";
+
+    /**
+     * Context (logger, configuration) in which the <abbr>JAR</abbr> file are created.
+     */
+    private final ToolExecutor context;
+
+    /**
+     * Whether to detect multi-release <abbr>JAR</abbr> files.
+     * The default value is {@code true}.
+     *
+     * @see AbstractJarMojo#detectMultiReleaseJar
+     */
+    private final boolean detectMultiReleaseJar;
+
+    /**
+     * The root directory to traverse. It will be used for temporarily moving excluded files.
+     */
+    private final Path rootDirectory;
+
+    /**
+     * Combination of includes and excludes path matcher applied on files.
+     */
+    @Nonnull
+    private final PathMatcher fileMatcher;
+
+    /**
+     * Combination of includes and excludes path matcher applied on directories.
+     */
+    @Nonnull
+    private final PathMatcher directoryMatcher;
+
+    /**
+     * Files to exclude. These files will be moved to a temporary location
+     * for allowing {@link ToolExecutor} to specify whole directories to the {@code jar} tool.
+     * Specifying whole directories is preferable to enumerating the files because otherwise,
+     * the generated <abbr>JAR</abbr> file contains only entries for the files and is missing
+     * entries for the directories.
+     *
+     * <p>This field is {@code null} if it is not possible to have any excluded file
+     * (because there is no include/exclude filters).</p>
+     */
+    @Nullable
+    private final List<Path> excludedFiles;
+
+    /**
+     * Directories to exclude. This field serves the same purpose as {@link #excludedFiles},
+     * but where the sources a directories instead of files.
+     */
+    @Nullable
+    private final List<Path> excludedDirectories;
+
+    /**
+     * Files found in the output directory when package hierarchy is used.
+     * At most one of {@code packageHierarchy} and {@link #moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Archive packageHierarchy;
+
+    /**
+     * Files found in the output directory when module hierarchy is used. Keys are module names.
+     * At most one of {@link #packageHierarchy} and {@code moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Map<String, Archive> moduleHierarchy;
+
+    /**
+     * The current module being archived. This field is updated every times that {@code FileCollector}
+     * visits a new module directory.
+     */
+    @Nonnull
+    private Archive currentModule;
+
+    /**
+     * The module and target Java release currently being scanned. This field is updated every times that
+     * {@code FileCollector} visits a new module directory or in a new target Java release for a given module.
+     */
+    @Nonnull
+    private Archive.FileSet currentFilesToArchive;
+
+    /**
+     * The current target Java release, or {@code null} if none.
+     */
+    @Nullable
+    private Runtime.Version currentTargetVersion;
+
+    /**
+     * Identification of the kinds of directories being traversed.
+     * The length of this list is the depth in the directory hierarchy.
+     * The last element identifies the type of the current directory.
+     */
+    private final Deque<DirectoryRole> directoryRoles;
+
+    /**
+     * Whether to check when a file is the {@code MANIFEST.MF} file.
+     * This is allowed only when scanning the content of a {@code META-INF} directory.
+     */
+    private boolean checkForManifest;
+
+    /**
+     * Creates a new file collector.
+     *
+     * @param mojo the <abbr>MOJO</abbr> from which to get the configuration
+     * @param context context (logger, configuration) in which the <abbr>JAR</abbr> file are created
+     * @param directory the base directory of the files to archive
+     */
+    FileCollector(AbstractJarMojo mojo, ToolExecutor context, Path directory, PathMatcherFactory matcherFactory) {
+        this.context = context;
+        rootDirectory = directory;
+        detectMultiReleaseJar = mojo.detectMultiReleaseJar;
+        directoryRoles = new ArrayDeque<>();
+        fileMatcher = matcherFactory.createPathMatcher(directory, mojo.getIncludes(), mojo.getExcludes(), false);
+        directoryMatcher = matcherFactory.deriveDirectoryMatcher(fileMatcher);
+        if (matcherFactory.isIncludesAll(fileMatcher) && matcherFactory.isIncludesAll(directoryMatcher)) {
+            excludedFiles = null;
+            excludedDirectories = null;
+        } else {
+            excludedFiles = new ArrayList<>();
+            excludedDirectories = new ArrayList<>();
+        }
+        packageHierarchy = context.newArchive(null, null, directory);
+        moduleHierarchy = new LinkedHashMap<>();
+        resetToPackageHierarchy();
+    }
+
+    /**
+     * Resets this {@code FileCollector} to the state where a package hierarchy is presumed.
+     */
+    private void resetToPackageHierarchy() {
+        currentModule = packageHierarchy;
+        currentFilesToArchive = currentModule.baseRelease();
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a module.
+     * For an output generated by {@code javac} from a module source hierarchy,
+     * the directory name is the module name.
+     *
+     * @param directory a {@code "<module>"} or {@code "META-INF/versions-modular/<module>"} directory
+     */
+    private void preVisitVersionDirectory(final Path directory) {
+        String moduleName = directory.getFileName().toString();
+        currentModule = moduleHierarchy.computeIfAbsent(
+                moduleName, (name) -> context.newArchive(name, currentTargetVersion, directory));
+        currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a target Java version.
+     * The {@code useDirectly} argument tells whether the content of this directory will be specified directly
+     * as the content to add in the <abbr>JAR</abbr> file. This argument should be {@code false} when there is
+     * another directory level (the module names) to process before to add content.
+     *
+     * @param directory a {@code "META-INF/versions/<n>"} or {@code "META-INF/versions-modular/<n>"} directory
+     * @param useDirectly whether the directory is {@code "META-INF/versions/<n>"}
+     * @return whether to skip the directory because of invalid version number
+     */
+    private boolean preVisitVersionDirectory(final Path directory, final boolean useDirectly) {
+        try {
+            currentTargetVersion = Runtime.Version.parse(directory.getFileName().toString());
+        } catch (IllegalArgumentException e) {
+            context.warnInvalidVersion(directory, e);
+            return true;
+        }
+        if (useDirectly) {
+            currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+        }
+        return false;
+    }
+
+    /**
+     * Determines if the given directory should be scanned for files to archive.
+     * This method may also update {@link #currentFilesToArchive} if it detects
+     * that we are visiting the content of a new module or a new target Java release.
+     *
+     * @param directory the directory which will be traversed
+     * @param attributes the directory's basic attributes
+     */
+    @Override
+    @SuppressWarnings("checkstyle:MissingSwitchDefault")
+    public FileVisitResult preVisitDirectory(final Path directory, final BasicFileAttributes attributes)
+            throws IOException {
+        DirectoryRole role;
+        if (directoryRoles.isEmpty()) {
+            role = DirectoryRole.ROOT;
+        } else {
+            if (!directoryMatcher.matches(directory)) {
+                excludedDirectories.add(directory); // Cannot be null if excluded directories may exist.
+                return FileVisitResult.SKIP_SUBTREE;
+            }
+            checkForManifest = false;
+            role = directoryRoles.getLast();
+            switch (role) {
+                case ROOT:
+                    /*
+                     * Visiting any subdirectory of `target/classes` (or other directory to archive).
+                     * We need to handle `META-INF` and modules in a special way, and archive the rest.
+                     */
+                    if (directory.endsWith(MetadataFiles.META_INF)) {
+                        role = DirectoryRole.META_INF;
+                        checkForManifest = true;
+                    } else if (Files.isRegularFile(directory.resolve(MODULE_DESCRIPTOR_FILE_NAME))) {
+                        role = DirectoryRole.NAMED_MODULE;
+                        preVisitVersionDirectory(directory);
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case META_INF:
+                    /*
+                     * Visiting a subdirectory of `META-INF` or `<module>/META-INF`. We will need to handle
+                     * `MANIFEST.MF`, `versions` and `versions-modular` in a special way, and archive the rest.
+                     */
+                    if (detectMultiReleaseJar && directory.endsWith(VERSIONS)) {
+                        role = DirectoryRole.VERSIONS;
+                    } else if (directory.endsWith(VERSIONS_MODULAR)) {
+                        if (!detectMultiReleaseJar) {
+                            // Used asked for no multi-release JAR.
+                            return FileVisitResult.SKIP_SUBTREE;
+                        }
+                        role = DirectoryRole.VERSIONS_MODULAR;
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case VERSIONS:
+                    /*
+                     * Visiting a `META-INF/versions/<n>/` directory for a specific target Java release.
+                     * Can also be a `<module>/META-INF/versions/<n>/` directory, even if the latter is not
+                     * the layout generated by Maven Compiler Plugin.
+                     */
+                    if (preVisitVersionDirectory(directory, true)) {
+                        // An error occurred while parsing the version number.
+                        return FileVisitResult.SKIP_SUBTREE;
+                    }
+                    role = DirectoryRole.RESOURCES;
+                    break;
+
+                case VERSIONS_MODULAR:
+                    /*
+                     * Visiting a `META-INF/versions-modular/<n>/` directory for a specific target Java release.
+                     * That directory contains all modules for the version.
+                     */
+                    resetToPackageHierarchy(); // No module in particular yet.
+                    if (preVisitVersionDirectory(directory, false)) {
+                        // An error occurred while parsing the version number.
+                        return FileVisitResult.SKIP_SUBTREE;
+                    }
+                    role = DirectoryRole.MODULES;
+                    break;
+
+                case MODULES:
+                    /*
+                     * Visiting a `META-INF/versions-modular/<n>/<module>` directory.
+                     */
+                    preVisitVersionDirectory(directory);
+                    role = DirectoryRole.NAMED_MODULE;
+                    break;
+
+                case NAMED_MODULE:
+                    /*
+                     * Visiting a `<module>` or `META-INF/versions-modular/<n>/<module>` subdirectory.
+                     * A module could have its own `META-INF` subdirectory, so we need to check again.
+                     */
+                    if (directory.endsWith(MetadataFiles.META_INF)) {
+                        role = DirectoryRole.META_INF;
+                        checkForManifest = true;
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+            }
+        }
+        /*
+         * Do not move this condition inside the `switch` block because `role` may have been modified.
+         * The `role` value is now the role of `directory`, not the role of parent directory.
+         */
+        if (role == DirectoryRole.RESOURCES) {
+            currentFilesToArchive.add(directory, attributes, true);
+            if (excludedFiles == null) {
+                /*
+                 * Since we are skipping the whole directory, `postVisitDirectory(…)` will not be invoked.
+                 * We must reset `currentFilesToArchive` and `currentTargetVersion` by an explicit call.
+                 * This is important mostly after we added a whole `META-INF/versions/<n>` directory.
+                 * Otherwise, since directory iteration order is unspecified, base files visited afterwards
+                 * would be added to this version's file set instead of the base release.
+                 */
+                resetToParentDirectoryState();
+                return FileVisitResult.SKIP_SUBTREE;
+            }
+        }
+        directoryRoles.addLast(role);
+        return FileVisitResult.CONTINUE;
+    }
+
+    /**
+     * Updates the {@code FileCollector} state after we finished scanning the contents of a directory.
+     * The fields to update depend on which directory has been visited (module, version, etc.).
+     *
+     * @param directory the directory which has been traversed
+     * @param error the error that occurred while traversing the directory, or {@code null} if none
+     */
+    @Override
+    public FileVisitResult postVisitDirectory(final Path directory, final IOException error) throws IOException {
+        if (error != null) {
+            throw error;
+        }
+        switch (directoryRoles.removeLast()) {
+            case ROOT:
+                break;
+
+            case NAMED_MODULE:
+                // Exited the directory of a single module.
+                resetToPackageHierarchy();
+                break;
+
+            default:
+                resetToParentDirectoryState();
+                break;
+        }
+        return FileVisitResult.CONTINUE;
+    }
+
+    /**
+     * Updates {@code FileCollector} to a state suitable for the parent of the directory that we finished to scan.
+     * Contrary to {@link #postVisitDirectory(Path, IOException)}, this method expects the last element of
+     * {@link #directoryRoles} to describe the parent directory, not the directory that we finished to visit.
+     */
+    @SuppressWarnings("checkstyle:MissingSwitchDefault")
+    private void resetToParentDirectoryState() {
+        switch (directoryRoles.getLast()) {
+            case VERSIONS:
+            case VERSIONS_MODULAR:
+                // Exited the directory for one target Java release.
+                currentFilesToArchive = currentModule.baseRelease();
+                currentTargetVersion = null;
+                break;
+
+            case META_INF:
+                checkForManifest = true;
+                break;
+        }
+    }
+
+    /**
+     * Archives a single file if accepted by the matcher.
+     *
+     * @param file the file
+     * @param attributes the file's basic attributes
+     */
+    @Override
+    public FileVisitResult visitFile(final Path file, final BasicFileAttributes attributes) {
+        if (fileMatcher.matches(file)) {
+            if (checkForManifest && file.endsWith(MetadataFiles.MANIFEST) && currentModule.setManifest(file, false)) {

Review Comment:
   Instead of tracking checkForManifest can't we figure out from file if we're ina  META-INF directory?



##########
src/test/java/org/apache/maven/plugins/jar/ArchiveTest.java:
##########
@@ -0,0 +1,257 @@
+/*
+ * 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.jar;
+
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Unit tests for {@link Archive}, focused on the two behaviours that are otherwise only
+ * exercised by integration tests whose outcome depends on the (unspecified) filesystem
+ * directory-iteration order, and therefore pass on some platforms while failing on others.
+ */
+class ArchiveTest {
+
+    /**
+     * Creates an {@code Archive} suitable for a unit test. {@code forceCreation = true} skips the
+     * existing-JAR timestamp check, so the (here {@code null}) logger is never dereferenced.
+     */
+    private static Archive archive(String moduleName, Runtime.Version version, Path directory) {
+        return new Archive(directory.resolve("out.jar"), moduleName, version, directory, true, null);
+    }
+
+    /**
+     * Creates a manifest with the main class attribute set to the given value.
+     *
+     * @param value value of the main class attribute
+     * @return a new manifest with the given attribute value
+     */
+    private static Manifest manifestWithMainClass(String value) {
+        Manifest m = new Manifest();
+        Attributes attributes = m.getMainAttributes();
+        attributes.put(Attributes.Name.MANIFEST_VERSION, "1.0");
+        attributes.put(Attributes.Name.MAIN_CLASS, value);
+        return m;
+    }
+
+    /**
+     * Returns the value of the main class attribute.
+     *
+     * @param m the manifest from which to get the value
+     * @return the main class attribute value, or {@code null} if none
+     */
+    private static Object mainClassOf(Manifest m) {
+        return m.getMainAttributes().get(Attributes.Name.MAIN_CLASS);
+    }
+
+    /**
+     * Verifies that {@link Archive#setMainClass(Manifest)} takes ownership for a module-qualified
+     * {@code "module/Class"} main class.
+     *
+     * The {@code "foo.bar/"} prefix in this test (the module name) is a Maven extension.
+     * The standard <abbr>JAR</abbr> specification accepts only the {@code "foo.MainFile"} class name.
+     */
+    @Test
+    void owningModuleClaimsMainClassAndRemovesItFromManifest() {
+        Archive owner = archive("foo.bar", null, Path.of("."));
+        Manifest m = manifestWithMainClass("foo.bar/foo.MainFile");
+        // The owner keeps the main class (emitted via --main-class) ...
+        assertTrue(owner.setMainClass(m));
+        // ... and the raw `module/Class` value is removed from the written manifest.
+        assertNull(mainClassOf(m));
+    }
+
+    /**
+     * Verifies that {@link Archive#setMainClass(Manifest)} does <em>not</em> take ownership of
+     * a module-qualified {@code "module/Class"} main class when the module name does not match.
+     * The {@code "foo.bar/"} prefix in this test (the module name) is a Maven extension.
+     * The standard <abbr>JAR</abbr> specification accepts only the {@code "foo.MainFile"} class name.
+     */
+    @Test
+    void nonOwningModuleRejectsMainClass() {
+        Archive nonOwner = archive("foo.bar.more", null, Path.of("."));
+        Manifest m = manifestWithMainClass("foo.bar/foo.MainFile");
+        assertFalse(nonOwner.setMainClass(m));
+        assertNull(mainClassOf(m));
+    }
+
+    /**
+     * Tests that which module keeps the main class does not depend on processing order.
+     * {@link ToolExecutor} gives each module a <em>copy</em> of the shared plugin manifest;
+     * this pins that the owning module (and only it) keeps the main class in either order,
+     * and that the shared manifest is never consumed.
+     */
+    @Test
+    void mainClassAssignmentIsIndependentOfModuleOrder() {
+        assertOwnership("foo.bar", "foo.bar.more", true); // owner processed first
+        assertOwnership("foo.bar.more", "foo.bar", false); // non-owner processed first
+    }
+
+    /**
+     * Helper method for {@link #mainClassAssignmentIsIndependentOfModuleOrder()}.
+     * Asserts that {@link Archive#setMainClass(Manifest)} returns {@code true}
+     * for the owner and {@code false} for the other module.
+     *
+     * <p>The {@code "foo.bar/"} prefix in this test (the module name) is a Maven extension.
+     * The standard <abbr>JAR</abbr> specification accepts only the {@code "foo.MainFile"} class name.
+     * This extension is used by the plugin for identifying in which <abbr>JAR</abbr> file to add this
+     * {@code Main-Class} manifest entry.</p>
+     */
+    private static void assertOwnership(String first, String second, boolean ownerIsFirst) {
+        final Path path = Path.of(".");
+        final Manifest shared = manifestWithMainClass("foo.bar/foo.MainFile");
+        final Manifest m1 = new Manifest(shared);
+        final Manifest m2 = new Manifest(shared);
+        assertEquals(ownerIsFirst, archive(first, null, path).setMainClass(m1));
+        assertEquals(!ownerIsFirst, archive(second, null, path).setMainClass(m2));

Review Comment:
   assertNotEquals?



##########
src/main/java/org/apache/maven/plugins/jar/Providers.java:
##########
@@ -22,25 +22,13 @@
 import org.apache.maven.api.di.Named;
 import org.apache.maven.api.di.Provides;
 import org.apache.maven.api.services.ProjectManager;
-import org.codehaus.plexus.archiver.Archiver;
-import org.codehaus.plexus.archiver.jar.JarArchiver;
-import org.codehaus.plexus.archiver.jar.JarToolModularJarArchiver;
 
+/**
+ * For providing instances to fields annotated with {@code @Inject} if the MOJO.

Review Comment:
   Ping @gnodet 



##########
src/main/java/org/apache/maven/plugins/jar/ToolExecutor.java:
##########
@@ -0,0 +1,551 @@
+/*
+ * 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.jar;
+
+import javax.lang.model.SourceVersion;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+import java.util.spi.ToolProvider;
+
+import org.apache.maven.api.Project;
+import org.apache.maven.api.Type;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.MojoException;
+import org.apache.maven.shared.archiver.MavenArchiveConfiguration;
+
+/**
+ * Writer of <abbr>JAR</abbr> files using the information collected by {@link FileCollector}.
+ * This class uses the {@code "jar"} tool provided with the <abbr>JDK</abbr>.
+ */
+final class ToolExecutor {
+    /**
+     * First JDK feature version whose {@code jar} tool can run {@code --validate} on archives
+     * that contain records. Earlier {@code jar} tools failed with "This feature requires ASM8"
+     * (JDK-8282446, fixed by JDK-8282508 in JDK 19 by not backported to a 17u or 18u update).
+     *
+     * @see <a href="https://bugs.openjdk.org/browse/JDK-8282446">JDK-8282446</a>
+     * @see <a href="https://bugs.openjdk.org/browse/JDK-8282508">JDK-8282508</a>
+     */
+    private static final int JDK_FIXING_JAR_VALIDATE = 19;
+
+    /**
+     * First JDK feature version whose {@code jar} tool support the {@code --date} option.
+     */
+    private static final int JDK_SUPPORT_DATE = 19;
+
+    /**
+     * The {@value} attribute. Its value is automatically generated by {@link Manifest},
+     * but may need to be replaced by another value if JDK-independent value is desired
+     * for strictly reproducible builds.
+     */
+    private static final String CREATED_BY = "Created-By";
+
+    /**
+     * The Maven project for which to create an archive.
+     */
+    final Project project;
+
+    /**
+     * {@code "jar"} or {@link "test-jar"}.
+     */
+    private final String artifactType;
+
+    /**
+     * The output directory where to write the <abbr>JAR</abbr> file.
+     * This is usually {@code ${baseDir}/target/}.
+     */
+    private final Path outputDirectory;
+
+    /**
+     * The <abbr>JAR</abbr> file name when package hierarchy is used.
+     * This is usually a file placed in the {@link ToolExecutor#outputDirectory} directory.
+     */
+    private final String finalName;
+
+    /**
+     * The classifier (e.g. "test"), or {@code null} if none.
+     */
+    private final String classifier;
+
+    /**
+     * Whether to validate the <abbr>JAR</abbr> file after its creation.
+     * If {@code null}, a value will be determined automatically based on heuristic rules.
+     */
+    private final Boolean validate;
+
+    /**
+     * The tool to use for creating the <abbr>JAR</abbr> files.
+     */
+    private final ToolProvider tool;
+
+    /**
+     * Where to send messages emitted by the "jar" tool.
+     */
+    private final PrintWriter messageWriter;
+
+    /**
+     * Where to send error messages emitted by the "jar" tool.
+     */
+    private final PrintWriter errorWriter;
+
+    /**
+     * Where the messages sent to {@link #messageWriter} are stored.
+     */
+    private final StringBuffer messages;
+
+    /**
+     * Where the messages sent to {@link #errorWriter} are stored.
+     */
+    private final StringBuffer errors;
+
+    /**
+     * A buffer for the arguments given to the "jar" tool, reused for each module.
+     * Each element of the list must be instances of either {@link String} or {@link Path}.
+     */
+    private final List<Object> arguments;
+
+    /**
+     * The paths to the created archive files.
+     * Map keys are module names or {@code null} if the project does not use module hierarchy.
+     * Values are (<var>type</var>, <var>path</var>) pairs associated with each module where
+     * <var>type</var> is {@code "pom"}, {@code "jar"} or {@code "test-jar"} and <var>path</var>
+     * is the path to the <abbr>POM</abbr> or <abbr>JAR</abbr> file.
+     */
+    private final Map<String, Map<String, Path>> result;
+
+    /**
+     * Mapper from Maven dependencies to Java modules, or {@code null} if the project does not use module hierarchy.
+     * This mapper is created only once for a Maven project and reused for each Java module to archive.
+     *
+     * <p>This field is not used directly by {@code ToolExecutor}. It is defined in this class for transferring
+     * this information from {@link AbstractJarMojo} to {@link PomDerivation.ForModule}.
+     * This is an internal mechanism that should not be public or protected.</p>
+     */
+    PomDerivation pomDerivation;
+
+    /**
+     * Manifest to merge with the manifest found in the files to archive.
+     * This is a manifest built from the {@code <archive>} plugin configuration.
+     * Can be {@code null} if there is noting to add to the existing manifests.
+     */
+    private final Manifest manifestFromPlugin;
+
+    /**
+     * The file from which {@link #manifestFromPlugin} has been read, or {@code null} if none.
+     * If non-null, reading that file must produce the same manifest as {@link #manifestFromPlugin}.
+     * It implies that this field must be {@code null} if {@link #manifestFromPlugin} is the result
+     * of merging elements specified in {@code <archive>} with a file specified in the plugin configuration.
+     */
+    private final Path manifestFile;
+
+    /**
+     * The archive configuration to use.
+     */
+    private final MavenArchiveConfiguration archiveConfiguration;
+
+    /**
+     * The timestamp in ISO-8601 extended offset date-time, or {@code null} if none.
+     * If user provided a value in seconds, it must have been converted to ISO-8601.
+     * This is used for reproducible builds.
+     */
+    private final String outputTimestamp;
+
+    /**
+     * Whether to force to build new <abbr>JAR</abbr> files even if none of the contents appear to have changed.
+     */
+    private final boolean forceCreation;
+
+    /**
+     * Where to send informative or error messages.
+     */
+    private final Log logger;
+
+    /**
+     * Creates a new writer.
+     *
+     * @param mojo the <abbr>MOJO</abbr> from which to get the configuration
+     * @param manifest manifest built from plugin configuration, or {@code null} if none
+     * @param archive the archive configuration
+     * @throws IOException if an error occurred while reading the manifest file
+     */
+    ToolExecutor(AbstractJarMojo mojo, Manifest manifest, MavenArchiveConfiguration archive) throws IOException {
+        project = mojo.project;
+        artifactType = mojo.getType();
+        outputDirectory = mojo.getOutputDirectory();
+        classifier = AbstractJarMojo.nullIfAbsent(mojo.getClassifier());
+        finalName =
+                (mojo.finalName != null) ? mojo.finalName : project.getBuild().getFinalName();
+        forceCreation = mojo.forceCreation;
+        outputTimestamp = mojo.getOutputTimestamp();
+        validate = mojo.getValidate();
+        logger = mojo.log;
+        tool = mojo.getJarTool();
+
+        var buffer = new StringWriter();
+        messages = buffer.getBuffer();
+        messageWriter = new PrintWriter(buffer);
+
+        buffer = new StringWriter();
+        errors = buffer.getBuffer();
+        errorWriter = new PrintWriter(buffer);
+
+        arguments = new ArrayList<>();
+        result = new LinkedHashMap<>();
+        archiveConfiguration = archive;
+
+        Path file = archive.getManifestFile();
+        if (file != null) {
+            try (InputStream in = Files.newInputStream(file)) {
+                // No need to wrap in `BufferedInputStream`.
+                if (manifest != null) {
+                    manifest.read(in);
+                    file = null; // Because the manifest is the result of a merge.
+                } else {
+                    manifest = new Manifest(in);
+                }
+            }
+        }
+        if (manifest != null) {
+            final Attributes mainAttributes = manifest.getMainAttributes();
+            if (mojo.detectMultiReleaseJar) {
+                mainAttributes.remove(Attributes.Name.MULTI_RELEASE);
+            }
+            if (isReproducible()) {
+                // If a "Created-By" attribute was generated by Maven Archiver, it is assumed JDK-independent.
+                // Otherwise, substitute by another value which does not depend on the JDK.
+                if (mainAttributes.getValue(CREATED_BY) == null) {
+                    mainAttributes.putValue(CREATED_BY, createdBy());
+                }
+            } else {
+                // If reproducible build was not requested, let the tool declares itself.
+                // This is a workaround until we port Maven archiver to this JAR plugin.
+                mainAttributes.remove(CREATED_BY);
+            }
+        }
+        manifestFromPlugin = manifest;
+        manifestFile = file;
+    }
+
+    /**
+     * Whether reproducible build was requested.
+     * In current version, the output time stamp is used as a sentinel value.
+     */
+    public boolean isReproducible() {
+        return outputTimestamp != null;
+    }
+
+    /**
+     * Returns the default {@value #CREATED_BY} value to use when strictly reproducible builds is requested.
+     * This value is ignored if the Maven Archiver or if user's configuration provided themselves a value.
+     *
+     * @return a JDK-independent {@value #CREATED_BY} value
+     */
+    private static String createdBy() {
+        String value = "Maven JAR Plugin";
+        String version = ToolExecutor.class.getPackage().getImplementationVersion();
+        if (version != null) {
+            value = value + ' ' + version;
+        }
+        return value;
+    }
+
+    /**
+     * Creates an initially empty archive for <abbr>JAR</abbr> file to generate.
+     * This method does not create the <abbr>JAR</abbr> file immediately,
+     * but collect information for creating the file later.
+     *
+     * @param  moduleName the module name if using module hierarchy, or {@code null} if using package hierarchy
+     * @param  version the target Java release, or {@code null} for the base version
+     * @param  directory the directory of the classes targeting the base Java release
+     */
+    Archive newArchive(final String moduleName, final Runtime.Version version, final Path directory) {
+        var sb = new StringBuilder(60);
+        if (moduleName != null) {
+            sb.append(moduleName).append('-').append(project.getVersion());
+        } else {
+            sb.append(finalName);
+        }
+        if (classifier != null) {
+            sb.append('-').append(classifier);
+        }
+        String filename = sb.append(".jar").toString();
+        return new Archive(outputDirectory.resolve(filename), moduleName, version, directory, forceCreation, logger);
+    }
+
+    /**
+     * Writes all <abbr>JAR</abbr> files, together with their derived <abbr>POM</abbr> files if applicable.
+     * The derived <abbr>POM</abbr> files are the intersections of the project <abbr>POM</abbr> with the
+     * content of {@code module-info.class} files.
+     *
+     * <h4>Prerequisites</h4>
+     * The {@link FileCollector#prune(boolean)} method should have been invoked once before to invoke this method.
+     *
+     * @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
+     * @throws MojoException if an error occurred during the execution of the "jar" tool
+     * @throws IOException if an error occurred while reading or writing a manifest file
+     */
+    @SuppressWarnings("ReturnOfCollectionOrArrayField")
+    public Map<String, Map<String, Path>> writeAllJARs(final FileCollector files) throws IOException {
+        Path ignored = files.handleOrphanFiles();
+        Path parentPOM = files.writeAllJARs(this);
+        if (ignored != null) {
+            logger.warn("Some files in \"" + relativize(outputDirectory, ignored)
+                    + "\" were ignored because they belong to no module.");
+        }
+        if (parentPOM != null) {
+            if (result.put(null, Map.of(Type.POM, parentPOM)) != null) {
+                throw new MojoException("Internal error."); // Should never happen.
+            }
+        }
+        return result;
+    }
+
+    /**
+     * Creates the <abbr>JAR</abbr> files for the specified set of files.
+     * If the operation fails, an error message may be available in the {@link #errors} buffer.
+     *
+     * @param files the result of scanning the build directory for listing the files or directories to archive
+     * @throws MojoException if an error occurred during the execution of the "jar" tool
+     * @throws IOException if an error occurred while reading or writing a manifest file
+     */
+    void writeSingleJAR(final FileCollector files, final Archive archive) throws IOException {
+        final Path relativePath = relativize(project.getRootDirectory(), archive.jarFile);
+        if (archive.isUpToDateJAR()) {
+            logger.info("Keep up-to-date JAR: \"" + relativePath + "\".");
+            archive.saveArtifactPaths(artifactType, result);
+            return;
+        }
+        logger.info("Building JAR: \"" + relativePath + "\".");
+        /*
+         * If `MANIFEST.MF` entries were specified by JAR plugin configuration,
+         * merge those entries with the content of `MANIFEST.MF` file found in
+         * the files to archive.
+         */
+        boolean writeTemporaryManifest = (manifestFromPlugin != null && manifestFile == null); // Check <archive>.
+        Manifest manifest = archive.mergeManifest(manifestFile, manifestFromPlugin);
+        if (manifest != manifestFromPlugin) {
+            writeTemporaryManifest |= (manifestFromPlugin != null); // Check if a merge of two manifests.
+        } else if (manifest != null) {
+            /*
+             * `setMainClass` below removes the Main-Class attribute, and `manifestFromPlugin` is
+             * shared across every module of a module hierarchy. Work on a per-module copy so that
+             * the (unspecified) directory iteration order does not decide which module keeps the
+             * main class: otherwise a non-owning module processed first consumes the attribute and
+             * the owning module never receives it.
+             */
+            manifest = new Manifest(manifest);
+        }
+        writeTemporaryManifest |= archive.setMainClass(manifest);
+        if (manifest != null) {
+            String name = manifest.getMainAttributes().getValue("Automatic-Module-Name");
+            if (name != null && !SourceVersion.isName(name)) {
+                throw new MojoException("Invalid automatic module name: \"" + name + "\".");
+            }
+        }
+        /*
+         * Creates temporary files for META-INF (if the existing file cannot be used directly)
+         * and for the Maven metadata (if requested). The temporary files are in the `target`
+         * directory and will be deleted, unless the build fails or is run in verbose mode.
+         */
+        try (MetadataFiles metadata = new MetadataFiles(project, outputDirectory)) {
+            if (writeTemporaryManifest) {
+                archive.setManifest(metadata.addManifest(manifest), true);
+            }
+            if (archive.moduleName != null) {
+                metadata.deriveModulePOM(this, archive, manifest);
+            }
+            if (archiveConfiguration.isAddMavenDescriptor()) {
+                archive.mavenFiles = metadata.addPOM(archiveConfiguration, isReproducible());
+            }
+            /*
+             * Prepare the arguments to send to the `jar` tool and log a message.
+             */
+            arguments.add("--create");
+            if (!archiveConfiguration.isCompress()) {
+                arguments.add("--no-compress");
+            }
+            if (outputTimestamp != null) {
+                if (Runtime.version().feature() >= JDK_SUPPORT_DATE) {

Review Comment:
   maybe OK but the variable name needs to be clearer



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#issuecomment-5574162284

   I think that we should merge now for the reason given by @ascheman in #561. The latest changes in this pull requests were mostly clarifications with fixes in English sentences and variable renaming. If there are still issues, we can fix them in other pull requests.


-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3949133680


##########
src/main/java/org/apache/maven/plugins/jar/FileCollector.java:
##########
@@ -0,0 +1,542 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.PathMatcher;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Deque;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.services.PathMatcherFactory;
+
+/**
+ * Dispatch the files from the output directory into the <abbr>JAR</abbr> files to create.
+ * Instead of just archiving as-is the content of the output directory, this class separates

Review Comment:
   Done.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3948952961


##########
src/it/jar-without-sources/pom.xml:
##########
@@ -0,0 +1,44 @@
+<?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>jar-without-sources</artifactId>
+  <version>1.0-SNAPSHOT</version>
+  <packaging>jar</packaging>
+  <name>jar-without-sources-it</name>
+  <description>This project has neither `src/main` nor `src/test`, so nothing is compiled
+    and the `target` directory is never created by an earlier lifecycle phase.
+    Versions 3.x of the JAR plugin still produced an empty, manifest-only JAR in that case.
+    This IT verifies that versions 4.x of the JAR plugin has the same behavior for compatibility purposes.

Review Comment:
   Done (used "have").



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "elharo (via GitHub)" <gi...@apache.org>.
elharo commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3949133825


##########
src/main/java/org/apache/maven/plugins/jar/ExcludedFiles.java:
##########
@@ -0,0 +1,146 @@
+/*
+ * 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.jar;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardCopyOption;
+import java.util.List;
+
+/**
+ * A list of files to temporarily move outside the directory to package in a <abbr>JAR</abbr> archive.
+ * This class is needed when the {@link AbstractJarMojo} configuration has include or exclude filters.
+ * Excluded files are temporarily moved outside the directory to archive.
+ * We move these files for making possible to specify the whole directory to the {@code jar} tool.
+ * This approach is used instead of enumerating files in arguments given to the {@code jar} tool because
+ * such enumeration cannot contain directory entries (otherwise the whole directory would be included).
+ * Some software such as Spring applications component scan relies on the presence of directory entries.
+ */
+final class ExcludedFiles implements Closeable {
+    /**
+     * The paths of files or directories to temporarily move in another directory.
+     */
+    private final Path[] original;
+
+    /**
+     * The paths where files or directories were moved.
+     * For each index <var>i</var>, the original path of {@code moved[i]} was {@code original[i]}.
+     */
+    private final Path[] moved;
+
+    /**
+     * Temporary directory which will contain the {@code moved} files.
+     * It should be a parent directory of {@link #original} files for
+     * increasing the chances that it is on the same file system.
+     */
+    private final Path temporaryDirectory;
+
+    /**
+     * Index of the first path which is a directory instead of a file.
+     * All paths before this index in the {@link #original} and {@link #moved} arrays are files.
+     * All paths at this index and after this index are directories.
+     */
+    private final int indexOfFirstDirectory;
+
+    /**
+     * Creates a new list of files to move in a temporary directory.
+     *
+     * @param directory the directory which was scanned for files to include in the <abbr>JAR</abbr>
+     * @param excludedFiles paths of files to temporarily move in another directory

Review Comment:
   I don't see the change. Do you need to push?



##########
src/main/java/org/apache/maven/plugins/jar/ExcludedFiles.java:
##########
@@ -0,0 +1,146 @@
+/*
+ * 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.jar;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardCopyOption;
+import java.util.List;
+
+/**
+ * A list of files to temporarily move outside the directory to package in a <abbr>JAR</abbr> archive.
+ * This class is needed when the {@link AbstractJarMojo} configuration has include or exclude filters.
+ * Excluded files are temporarily moved outside the directory to archive.
+ * We move these files for making possible to specify the whole directory to the {@code jar} tool.
+ * This approach is used instead of enumerating files in arguments given to the {@code jar} tool because
+ * such enumeration cannot contain directory entries (otherwise the whole directory would be included).
+ * Some software such as Spring applications component scan relies on the presence of directory entries.
+ */
+final class ExcludedFiles implements Closeable {
+    /**
+     * The paths of files or directories to temporarily move in another directory.
+     */
+    private final Path[] original;
+
+    /**
+     * The paths where files or directories were moved.
+     * For each index <var>i</var>, the original path of {@code moved[i]} was {@code original[i]}.
+     */
+    private final Path[] moved;
+
+    /**
+     * Temporary directory which will contain the {@code moved} files.
+     * It should be a parent directory of {@link #original} files for
+     * increasing the chances that it is on the same file system.
+     */
+    private final Path temporaryDirectory;
+
+    /**
+     * Index of the first path which is a directory instead of a file.
+     * All paths before this index in the {@link #original} and {@link #moved} arrays are files.
+     * All paths at this index and after this index are directories.
+     */
+    private final int indexOfFirstDirectory;
+
+    /**
+     * Creates a new list of files to move in a temporary directory.
+     *
+     * @param directory the directory which was scanned for files to include in the <abbr>JAR</abbr>
+     * @param excludedFiles paths of files to temporarily move in another directory
+     * @param excludedDirectories paths of directories to temporarily move in another directory
+     * @throws IOException if an error occurred while creating the temporary directory.
+     */
+    ExcludedFiles(Path directory, List<Path> excludedFiles, List<Path> excludedDirectories) throws IOException {
+        indexOfFirstDirectory = excludedFiles.size();

Review Comment:
   That makes some sense. The key difference is that you don't have to move the files you include. Instead you just copy them. This makes cleanup easier and safer. It also avoids random metadata files from getting picked up like .git or .DS_Store. How are those handled now?
   
   
   
   



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3949181343


##########
src/main/java/org/apache/maven/plugins/jar/FileCollector.java:
##########
@@ -0,0 +1,542 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.PathMatcher;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Deque;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.services.PathMatcherFactory;
+
+/**
+ * Dispatch the files from the output directory into the <abbr>JAR</abbr> files to create.
+ * Instead of just archiving as-is the content of the output directory, this class separates
+ * the following subdirectories to the options listed below:
+ *
+ * <ul>
+ *   <li>The {@code META-INF/MANIFEST.MF} file will be given to the {@code --manifest} option.</li>
+ *   <li>Files in the following directories will be given to the {@code --release} option:
+ *     <ul>
+ *       <li>{@code META-INF/versions/}</li>
+ *       <li>{@code META-INF/versions-modular/<module>/}</li>
+ *       <li>{@code <module>/META-INF/versions/}</li>
+ *     </ul>
+ *   </li>
+ * </ul>
+ *
+ * The reason for using the {@code --release} and {@code --manifest} options instead of adding explicitly
+ * the entries is because the options allow the {@code jar} tool to perform additional verifications.
+ * For example, when using the {@code --release} option, {@code jar} verifies the <abbr>API</abbr> compatibility.
+ */
+final class FileCollector extends SimpleFileVisitor<Path> {
+    /**
+     * The file to check for deciding whether the <abbr>JAR</abbr> is modular.
+     */
+    static final String MODULE_DESCRIPTOR_FILE_NAME = "module-info.class";
+
+    /**
+     * The {@value} directory.
+     * This is part of <abbr>JAR</abbr> file specification.
+     */
+    private static final String VERSIONS = "versions";
+
+    /**
+     * The {@value} directory.
+     * This is Maven-specific.
+     */
+    private static final String VERSIONS_MODULAR = "versions-modular";
+
+    /**
+     * Context (logger, configuration) in which the <abbr>JAR</abbr> file are created.
+     */
+    private final ToolExecutor context;
+
+    /**
+     * Whether to detect multi-release <abbr>JAR</abbr> files.
+     * The default value is {@code true}.
+     *
+     * @see AbstractJarMojo#detectMultiReleaseJar
+     */
+    private final boolean detectMultiReleaseJar;
+
+    /**
+     * The root directory to traverse. It will be used for temporarily moving excluded files.
+     */
+    private final Path rootDirectory;
+
+    /**
+     * Combination of includes and excludes path matcher applied on files.
+     */
+    @Nonnull
+    private final PathMatcher fileMatcher;
+
+    /**
+     * Combination of includes and excludes path matcher applied on directories.
+     */
+    @Nonnull
+    private final PathMatcher directoryMatcher;
+
+    /**
+     * Files to exclude. These files will be moved to a temporary location
+     * for allowing {@link ToolExecutor} to specify whole directories to the {@code jar} tool.

Review Comment:
   Done.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3949176980


##########
src/main/java/org/apache/maven/plugins/jar/FileCollector.java:
##########
@@ -0,0 +1,542 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.PathMatcher;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Deque;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.services.PathMatcherFactory;
+
+/**
+ * Dispatch the files from the output directory into the <abbr>JAR</abbr> files to create.
+ * Instead of just archiving as-is the content of the output directory, this class separates
+ * the following subdirectories to the options listed below:
+ *
+ * <ul>
+ *   <li>The {@code META-INF/MANIFEST.MF} file will be given to the {@code --manifest} option.</li>
+ *   <li>Files in the following directories will be given to the {@code --release} option:
+ *     <ul>
+ *       <li>{@code META-INF/versions/}</li>
+ *       <li>{@code META-INF/versions-modular/<module>/}</li>
+ *       <li>{@code <module>/META-INF/versions/}</li>
+ *     </ul>
+ *   </li>
+ * </ul>
+ *
+ * The reason for using the {@code --release} and {@code --manifest} options instead of adding explicitly
+ * the entries is because the options allow the {@code jar} tool to perform additional verifications.
+ * For example, when using the {@code --release} option, {@code jar} verifies the <abbr>API</abbr> compatibility.
+ */
+final class FileCollector extends SimpleFileVisitor<Path> {
+    /**
+     * The file to check for deciding whether the <abbr>JAR</abbr> is modular.
+     */
+    static final String MODULE_DESCRIPTOR_FILE_NAME = "module-info.class";
+
+    /**
+     * The {@value} directory.
+     * This is part of <abbr>JAR</abbr> file specification.
+     */
+    private static final String VERSIONS = "versions";
+
+    /**
+     * The {@value} directory.

Review Comment:
   The comment looks identical in the source code but does not produce the same javadoc, because `{@value}` is replaced by the actual value. So the comment is _The "versions" directory_ in the first case and _The "versions-modular" directory_ in the second case.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3949147579


##########
src/main/java/org/apache/maven/plugins/jar/FileCollector.java:
##########
@@ -0,0 +1,542 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.PathMatcher;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Deque;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.services.PathMatcherFactory;
+
+/**
+ * Dispatch the files from the output directory into the <abbr>JAR</abbr> files to create.
+ * Instead of just archiving as-is the content of the output directory, this class separates
+ * the following subdirectories to the options listed below:
+ *
+ * <ul>
+ *   <li>The {@code META-INF/MANIFEST.MF} file will be given to the {@code --manifest} option.</li>
+ *   <li>Files in the following directories will be given to the {@code --release} option:
+ *     <ul>
+ *       <li>{@code META-INF/versions/}</li>
+ *       <li>{@code META-INF/versions-modular/<module>/}</li>
+ *       <li>{@code <module>/META-INF/versions/}</li>
+ *     </ul>
+ *   </li>
+ * </ul>
+ *
+ * The reason for using the {@code --release} and {@code --manifest} options instead of adding explicitly
+ * the entries is because the options allow the {@code jar} tool to perform additional verifications.
+ * For example, when using the {@code --release} option, {@code jar} verifies the <abbr>API</abbr> compatibility.
+ */
+final class FileCollector extends SimpleFileVisitor<Path> {
+    /**
+     * The file to check for deciding whether the <abbr>JAR</abbr> is modular.

Review Comment:
   Done.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3949144052


##########
src/main/java/org/apache/maven/plugins/jar/FileCollector.java:
##########
@@ -0,0 +1,542 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.PathMatcher;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Deque;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.services.PathMatcherFactory;
+
+/**
+ * Dispatch the files from the output directory into the <abbr>JAR</abbr> files to create.
+ * Instead of just archiving as-is the content of the output directory, this class separates
+ * the following subdirectories to the options listed below:
+ *
+ * <ul>
+ *   <li>The {@code META-INF/MANIFEST.MF} file will be given to the {@code --manifest} option.</li>
+ *   <li>Files in the following directories will be given to the {@code --release} option:
+ *     <ul>
+ *       <li>{@code META-INF/versions/}</li>
+ *       <li>{@code META-INF/versions-modular/<module>/}</li>
+ *       <li>{@code <module>/META-INF/versions/}</li>
+ *     </ul>
+ *   </li>
+ * </ul>
+ *
+ * The reason for using the {@code --release} and {@code --manifest} options instead of adding explicitly
+ * the entries is because the options allow the {@code jar} tool to perform additional verifications.
+ * For example, when using the {@code --release} option, {@code jar} verifies the <abbr>API</abbr> compatibility.

Review Comment:
   Done.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3949140634


##########
src/main/java/org/apache/maven/plugins/jar/FileCollector.java:
##########
@@ -0,0 +1,542 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.PathMatcher;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Deque;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.services.PathMatcherFactory;
+
+/**
+ * Dispatch the files from the output directory into the <abbr>JAR</abbr> files to create.
+ * Instead of just archiving as-is the content of the output directory, this class separates
+ * the following subdirectories to the options listed below:
+ *
+ * <ul>
+ *   <li>The {@code META-INF/MANIFEST.MF} file will be given to the {@code --manifest} option.</li>
+ *   <li>Files in the following directories will be given to the {@code --release} option:
+ *     <ul>
+ *       <li>{@code META-INF/versions/}</li>
+ *       <li>{@code META-INF/versions-modular/<module>/}</li>
+ *       <li>{@code <module>/META-INF/versions/}</li>
+ *     </ul>
+ *   </li>
+ * </ul>
+ *
+ * The reason for using the {@code --release} and {@code --manifest} options instead of adding explicitly

Review Comment:
   Done.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3949352425


##########
src/test/java/org/apache/maven/plugins/jar/ArchiveTest.java:
##########
@@ -0,0 +1,257 @@
+/*
+ * 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.jar;
+
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Unit tests for {@link Archive}, focused on the two behaviours that are otherwise only
+ * exercised by integration tests whose outcome depends on the (unspecified) filesystem
+ * directory-iteration order, and therefore pass on some platforms while failing on others.
+ */
+class ArchiveTest {
+
+    /**
+     * Creates an {@code Archive} suitable for a unit test. {@code forceCreation = true} skips the
+     * existing-JAR timestamp check, so the (here {@code null}) logger is never dereferenced.
+     */
+    private static Archive archive(String moduleName, Runtime.Version version, Path directory) {
+        return new Archive(directory.resolve("out.jar"), moduleName, version, directory, true, null);
+    }
+
+    /**
+     * Creates a manifest with the main class attribute set to the given value.
+     *
+     * @param value value of the main class attribute
+     * @return a new manifest with the given attribute value
+     */
+    private static Manifest manifestWithMainClass(String value) {
+        Manifest m = new Manifest();
+        Attributes attributes = m.getMainAttributes();
+        attributes.put(Attributes.Name.MANIFEST_VERSION, "1.0");
+        attributes.put(Attributes.Name.MAIN_CLASS, value);
+        return m;
+    }
+
+    /**
+     * Returns the value of the main class attribute.
+     *
+     * @param m the manifest from which to get the value

Review Comment:
   Done.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "elharo (via GitHub)" <gi...@apache.org>.
elharo commented on PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#issuecomment-5525480441

   Javadoc HTML is not super up-to-date. acronym was removed in HTML 5. I don't think using unrecognized markup breaks things, just issues a warning. But keep in mind that a lot of Javadoc is either primarily or equally intended for reading in source code as in a web browser. In these contexts markup is a distraction and plain text wins. 


-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3923625990


##########
src/main/java/org/apache/maven/plugins/jar/PomDerivation.java:
##########
@@ -0,0 +1,529 @@
+/*
+ * 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.jar;
+
+import javax.xml.stream.XMLStreamException;
+
+import java.io.BufferedInputStream;
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.UncheckedIOException;
+import java.lang.module.ModuleDescriptor;
+import java.lang.module.ModuleFinder;
+import java.lang.module.ModuleReference;
+import java.net.URI;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.DependencyCoordinates;
+import org.apache.maven.api.JavaPathType;
+import org.apache.maven.api.Session;
+import org.apache.maven.api.Type;
+import org.apache.maven.api.model.Dependency;
+import org.apache.maven.api.model.Model;
+import org.apache.maven.api.model.Parent;
+import org.apache.maven.api.plugin.MojoException;
+import org.apache.maven.api.services.DependencyCoordinatesFactory;
+import org.apache.maven.api.services.DependencyCoordinatesFactoryRequest;
+import org.apache.maven.api.services.DependencyResolver;
+import org.apache.maven.api.services.DependencyResolverRequest;
+import org.apache.maven.api.services.DependencyResolverResult;
+import org.apache.maven.api.services.ModelBuilderException;
+import org.apache.maven.model.v4.MavenStaxWriter;
+
+/**
+ * A mapper from Maven model dependencies to Java module names.
+ * A single instance of this class is created for a Maven project,
+ * then shared by all {@link ForModule} instances (one per module to archive).
+ */
+final class PomDerivation {
+    /**
+     * Whether to expand the list of transitive dependencies in the generated <abbr>POM</abbr>.
+     */
+    private static final boolean EXPAND_TRANSITIVE = false;
+
+    /**
+     * Copy of {@link AbstractJarMojo#session}.
+     */
+    private final Session session;
+
+    /**
+     * The project model, which includes dependencies of all modules.
+     */
+    private final Model projectModel;
+
+    /**
+     * The factory to use for creating temporary {@link DependencyCoordinates} instances.
+     */
+    private final DependencyCoordinatesFactory coordinateFactory;
+
+    /**
+     * Provide module descriptors from module names.
+     * May be {@code null} if no {@code module-info} was found.
+     */
+    private final ModuleFinder moduleFinder;
+
+    /**
+     * Module references from paths to the <abbr>JAR</abbr> file or root directory.
+     */
+    private final Map<URI, ModuleReference> fromURI;
+
+    /**
+     * Module names associated with Maven dependencies.
+     * This map contains {@link DependencyCoordinates#getId()} as keys and module references as values.
+     * This is used to detect which dependencies are really used according to {@code module-info.class}.
+     *
+     * @todo The keys should be instances of {@link DependencyCoordinates}. Unfortunately, as of Maven 4.0.0-rc-5
+     *       that interface does not define the {@code equals} and {@code hashCode} contracts.
+     */
+    private final Map<String, ModuleReference> fromDependency;
+
+    /**
+     * Modules that are built by the project. Keys are module names.
+     */
+    private final Map<String, Dependency> builtModules;
+
+    /**
+     * Creates a new mapper from Maven dependency to module name.
+     *
+     * @param mojo the enclosing <abbr>MOJO</abbr>
+     * @param moduleRoots paths to root directories of each module to archive in a module hierarchy
+     * @throws IOException if an I/O error occurred while fetching dependencies
+     * @throws MavenException if an error occurred while fetching dependencies for a reason other than I/O.
+     */
+    PomDerivation(final AbstractJarMojo mojo, final List<Path> moduleRoots) throws IOException {
+        this.session = mojo.session;
+        projectModel = mojo.project.getModel();
+        coordinateFactory = session.getService(DependencyCoordinatesFactory.class);
+        DependencyResolver resolver = session.getService(DependencyResolver.class);
+        DependencyResolverResult result = resolver.resolve(DependencyResolverRequest.builder()
+                .session(session)
+                .project(mojo.project)
+                .requestType(DependencyResolverRequest.RequestType.RESOLVE)
+                .pathScope(mojo.getDependencyScope())
+                .pathTypeFilter(Set.of(JavaPathType.MODULES, JavaPathType.CLASSES))
+                .build());
+
+        rethrow(result);
+        final Map<org.apache.maven.api.Dependency, Path> dependencies = result.getDependencies();
+        final Path[] allModulePaths = toRealPaths(moduleRoots, dependencies.values());
+        fromURI = new HashMap<>(allModulePaths.length); // TODO: use newHashMap with JDK19.
+        moduleFinder = ModuleFinder.of(allModulePaths);
+        if (moduleFinder != null) {
+            for (ModuleReference reference : moduleFinder.findAll()) {
+                reference.location().ifPresent((location) -> fromURI.put(location, reference));
+            }
+        }
+        fromDependency = new HashMap<>(dependencies.size()); // TODO: use newHashMap with JDK19.
+        for (Map.Entry<org.apache.maven.api.Dependency, Path> entry : dependencies.entrySet()) {
+            Path modulePath = entry.getValue().toRealPath();
+            ModuleReference reference = fromURI.get(modulePath.toUri());
+            if (reference != null) {
+                DependencyCoordinates coordinates = entry.getKey().toCoordinates();
+                String id = coordinates.getId();
+                ModuleReference old = fromDependency.putIfAbsent(id, reference);
+                if (old == null) {
+                    coordinates = withoutVersion(coordinates);
+                    id = coordinates.getId();
+                    old = fromDependency.putIfAbsent(id, reference);
+                }
+                if (old != null && !old.equals(reference)) {
+                    mojo.log.warn("The \"" + id + "\" dependency is declared twice with different module names: \""
+                            + old.descriptor().name() + "\" and \""
+                            + reference.descriptor().name() + "\".");
+                }
+            }
+        }
+        builtModules = new HashMap<>(moduleRoots.size()); // TODO: use newHashMap with JDK19.
+        for (Path root : moduleRoots) {
+            root = root.toRealPath();
+            ModuleReference reference = fromURI.get(root.toUri());
+            if (reference != null) { // Actually a null value would be a bug, but be tolerant.
+                String moduleName = reference.descriptor().name();
+                builtModules.put(
+                        moduleName,
+                        Dependency.newBuilder()
+                                .groupId(projectModel.getGroupId())
+                                .artifactId(moduleName)
+                                .version(projectModel.getVersion())
+                                .type(Type.MODULAR_JAR)
+                                .build());
+            }
+        }
+    }
+
+    /**
+     * Rebuilds the given dependency coordinates without version.
+     *
+     * Note: I'm not sure if it is necessary. This is done in case version numbers are not resolved

Review Comment:
   That would be ideal, but it requires a deeper knowledge of Maven behaviour than what I have. This is not the final version of the JAR plugin anyway. If this merge request is accepted, it will be followed by other (much smaller) merge requests, e.g. for bringing Archiver code in the JAR plugin.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3923605965


##########
src/main/java/org/apache/maven/plugins/jar/PomDerivation.java:
##########
@@ -0,0 +1,529 @@
+/*
+ * 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.jar;
+
+import javax.xml.stream.XMLStreamException;
+
+import java.io.BufferedInputStream;
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.UncheckedIOException;
+import java.lang.module.ModuleDescriptor;
+import java.lang.module.ModuleFinder;
+import java.lang.module.ModuleReference;
+import java.net.URI;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.DependencyCoordinates;
+import org.apache.maven.api.JavaPathType;
+import org.apache.maven.api.Session;
+import org.apache.maven.api.Type;
+import org.apache.maven.api.model.Dependency;
+import org.apache.maven.api.model.Model;
+import org.apache.maven.api.model.Parent;
+import org.apache.maven.api.plugin.MojoException;
+import org.apache.maven.api.services.DependencyCoordinatesFactory;
+import org.apache.maven.api.services.DependencyCoordinatesFactoryRequest;
+import org.apache.maven.api.services.DependencyResolver;
+import org.apache.maven.api.services.DependencyResolverRequest;
+import org.apache.maven.api.services.DependencyResolverResult;
+import org.apache.maven.api.services.ModelBuilderException;
+import org.apache.maven.model.v4.MavenStaxWriter;
+
+/**
+ * A mapper from Maven model dependencies to Java module names.
+ * A single instance of this class is created for a Maven project,
+ * then shared by all {@link ForModule} instances (one per module to archive).
+ */
+final class PomDerivation {
+    /**
+     * Whether to expand the list of transitive dependencies in the generated <abbr>POM</abbr>.
+     */
+    private static final boolean EXPAND_TRANSITIVE = false;
+
+    /**
+     * Copy of {@link AbstractJarMojo#session}.
+     */
+    private final Session session;
+
+    /**
+     * The project model, which includes dependencies of all modules.
+     */
+    private final Model projectModel;
+
+    /**
+     * The factory to use for creating temporary {@link DependencyCoordinates} instances.
+     */
+    private final DependencyCoordinatesFactory coordinateFactory;
+
+    /**
+     * Provide module descriptors from module names.
+     * May be {@code null} if no {@code module-info} was found.
+     */
+    private final ModuleFinder moduleFinder;
+
+    /**
+     * Module references from paths to the <abbr>JAR</abbr> file or root directory.
+     */
+    private final Map<URI, ModuleReference> fromURI;
+
+    /**
+     * Module names associated with Maven dependencies.
+     * This map contains {@link DependencyCoordinates#getId()} as keys and module references as values.
+     * This is used to detect which dependencies are really used according to {@code module-info.class}.
+     *
+     * @todo The keys should be instances of {@link DependencyCoordinates}. Unfortunately, as of Maven 4.0.0-rc-5
+     *       that interface does not define the {@code equals} and {@code hashCode} contracts.
+     */
+    private final Map<String, ModuleReference> fromDependency;
+
+    /**
+     * Modules that are built by the project. Keys are module names.
+     */
+    private final Map<String, Dependency> builtModules;
+
+    /**
+     * Creates a new mapper from Maven dependency to module name.
+     *
+     * @param mojo the enclosing <abbr>MOJO</abbr>
+     * @param moduleRoots paths to root directories of each module to archive in a module hierarchy
+     * @throws IOException if an I/O error occurred while fetching dependencies
+     * @throws MavenException if an error occurred while fetching dependencies for a reason other than I/O.
+     */
+    PomDerivation(final AbstractJarMojo mojo, final List<Path> moduleRoots) throws IOException {
+        this.session = mojo.session;
+        projectModel = mojo.project.getModel();
+        coordinateFactory = session.getService(DependencyCoordinatesFactory.class);
+        DependencyResolver resolver = session.getService(DependencyResolver.class);
+        DependencyResolverResult result = resolver.resolve(DependencyResolverRequest.builder()
+                .session(session)
+                .project(mojo.project)
+                .requestType(DependencyResolverRequest.RequestType.RESOLVE)
+                .pathScope(mojo.getDependencyScope())
+                .pathTypeFilter(Set.of(JavaPathType.MODULES, JavaPathType.CLASSES))
+                .build());
+
+        rethrow(result);
+        final Map<org.apache.maven.api.Dependency, Path> dependencies = result.getDependencies();
+        final Path[] allModulePaths = toRealPaths(moduleRoots, dependencies.values());
+        fromURI = new HashMap<>(allModulePaths.length); // TODO: use newHashMap with JDK19.
+        moduleFinder = ModuleFinder.of(allModulePaths);
+        if (moduleFinder != null) {
+            for (ModuleReference reference : moduleFinder.findAll()) {
+                reference.location().ifPresent((location) -> fromURI.put(location, reference));
+            }
+        }
+        fromDependency = new HashMap<>(dependencies.size()); // TODO: use newHashMap with JDK19.
+        for (Map.Entry<org.apache.maven.api.Dependency, Path> entry : dependencies.entrySet()) {
+            Path modulePath = entry.getValue().toRealPath();
+            ModuleReference reference = fromURI.get(modulePath.toUri());
+            if (reference != null) {
+                DependencyCoordinates coordinates = entry.getKey().toCoordinates();
+                String id = coordinates.getId();
+                ModuleReference old = fromDependency.putIfAbsent(id, reference);
+                if (old == null) {
+                    coordinates = withoutVersion(coordinates);
+                    id = coordinates.getId();
+                    old = fromDependency.putIfAbsent(id, reference);
+                }
+                if (old != null && !old.equals(reference)) {
+                    mojo.log.warn("The \"" + id + "\" dependency is declared twice with different module names: \""
+                            + old.descriptor().name() + "\" and \""
+                            + reference.descriptor().name() + "\".");
+                }
+            }
+        }
+        builtModules = new HashMap<>(moduleRoots.size()); // TODO: use newHashMap with JDK19.
+        for (Path root : moduleRoots) {
+            root = root.toRealPath();

Review Comment:
   It is not really reusing. It is the variable we are interested in. If we were using classical loop instead, it would be like below:
   
   ```java
   for (int i = 0; i < moduleRoots.size(); i++) {
       Path root = moduleRoots.get(i).toRealPath();
   ```
   
   It appears as a modification of `root` only because the loop syntax does not allow us to specify that we are interested in a derived value (equivalent to `moduleRoots.stream().map(Path::toRealPath)`). Updating `root` directly makes sure that the non-real path is never used. Using a different variable would increase the risk of bug, not reduce it.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3923535434


##########
src/main/java/org/apache/maven/plugins/jar/FileCollector.java:
##########
@@ -0,0 +1,541 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.PathMatcher;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Deque;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.services.PathMatcherFactory;
+
+/**
+ * Dispatch the files from the output directory into the <abbr>JAR</abbr> files to create.
+ * Instead of just archiving as-is the content of the output directory, this class separates
+ * the following subdirectories to the options listed below:
+ *
+ * <ul>
+ *   <li>The {@code META-INF/MANIFEST.MF} file will be given to the {@code --manifest} option.</li>
+ *   <li>Files in the following directories will be given to the {@code --release} option:
+ *     <ul>
+ *       <li>{@code META-INF/versions/}</li>
+ *       <li>{@code META-INF/versions-modular/<module>/}</li>
+ *       <li>{@code <module>/META-INF/versions/}</li>
+ *     </ul>
+ *   </li>
+ * </ul>
+ *
+ * The reason for using the options is that they allow the {@code jar} tool to perform additional verifications.
+ * For example, when using the {@code --release} option, {@code jar} verifies the <abbr>API</abbr> compatibility.
+ */
+final class FileCollector extends SimpleFileVisitor<Path> {
+    /**
+     * The file to check for deciding whether the <abbr>JAR</abbr> is modular.
+     */
+    static final String MODULE_DESCRIPTOR_FILE_NAME = "module-info.class";
+
+    /**
+     * The {@value} directory.
+     * This is part of <abbr>JAR</abbr> file specification.
+     */
+    private static final String VERSIONS = "versions";
+
+    /**
+     * The {@value} directory.
+     * This is Maven-specific.
+     */
+    private static final String VERSIONS_MODULAR = "versions-modular";
+
+    /**
+     * Context (logger, configuration) in which the <abbr>JAR</abbr> file are created.
+     */
+    private final ToolExecutor context;
+
+    /**
+     * Whether to detect multi-release <abbr>JAR</abbr> files.
+     * The default value is {@code true}.
+     *
+     * @see AbstractJarMojo#detectMultiReleaseJar
+     */
+    private final boolean detectMultiReleaseJar;
+
+    /**
+     * The root directory to traverse. It will be used for temporarily moving excluded files.
+     */
+    private final Path rootDirectory;
+
+    /**
+     * Combination of includes and excludes path matcher applied on files.
+     */
+    @Nonnull
+    private final PathMatcher fileMatcher;
+
+    /**
+     * Combination of includes and excludes path matcher applied on directories.
+     */
+    @Nonnull
+    private final PathMatcher directoryMatcher;
+
+    /**
+     * Files to exclude. These files will be moved to a temporary location
+     * for allowing {@link ToolExecutor} to specify whole directories to the {@code jar} tool.
+     * Specifying whole directories is preferable to enumerating the files because otherwise,
+     * the generated <abbr>JAR</abbr> file contains only entries for the files and is missing
+     * entries for the directories.
+     *
+     * <p>This field is {@code null} if it is not possible to have any excluded file
+     * (because there is no include/exclude filters).</p>
+     */
+    @Nullable
+    private final List<Path> excludedFiles;
+
+    /**
+     * Directories to exclude. This field serves the same purpose as {@link #excludedFiles},
+     * but where the sources a directories instead of files.
+     */
+    @Nullable
+    private final List<Path> excludedDirectories;
+
+    /**
+     * Files found in the output directory when package hierarchy is used.
+     * At most one of {@code packageHierarchy} and {@link #moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Archive packageHierarchy;
+
+    /**
+     * Files found in the output directory when module hierarchy is used. Keys are module names.
+     * At most one of {@link #packageHierarchy} and {@code moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Map<String, Archive> moduleHierarchy;
+
+    /**
+     * The current module being archived. This field is updated every times that {@code FileCollector}
+     * visits a new module directory.
+     */
+    @Nonnull
+    private Archive currentModule;
+
+    /**
+     * The module and target Java release currently being scanned. This field is updated every times that
+     * {@code FileCollector} visits a new module directory or in a new target Java release for a given module.
+     */
+    @Nonnull
+    private Archive.FileSet currentFilesToArchive;
+
+    /**
+     * The current target Java release, or {@code null} if none.
+     */
+    @Nullable
+    private Runtime.Version currentTargetVersion;
+
+    /**
+     * Identification of the kinds of directories being traversed.
+     * The length of this list is the depth in the directory hierarchy.
+     * The last element identifies the type of the current directory.
+     */
+    private final Deque<DirectoryRole> directoryRoles;
+
+    /**
+     * Whether to check when a file is the {@code MANIFEST.MF} file.
+     * This is allowed only when scanning the content of a {@code META-INF} directory.
+     */
+    private boolean checkForManifest;
+
+    /**
+     * Creates a new file collector.
+     *
+     * @param mojo the <abbr>MOJO</abbr> from which to get the configuration
+     * @param context context (logger, configuration) in which the <abbr>JAR</abbr> file are created
+     * @param directory the base directory of the files to archive
+     */
+    FileCollector(AbstractJarMojo mojo, ToolExecutor context, Path directory, PathMatcherFactory matcherFactory) {
+        this.context = context;
+        rootDirectory = directory;
+        detectMultiReleaseJar = mojo.detectMultiReleaseJar;
+        directoryRoles = new ArrayDeque<>();
+        fileMatcher = matcherFactory.createPathMatcher(directory, mojo.getIncludes(), mojo.getExcludes(), false);
+        directoryMatcher = matcherFactory.deriveDirectoryMatcher(fileMatcher);
+        if (matcherFactory.isIncludesAll(fileMatcher) && matcherFactory.isIncludesAll(directoryMatcher)) {
+            excludedFiles = null;
+            excludedDirectories = null;
+        } else {
+            excludedFiles = new ArrayList<>();
+            excludedDirectories = new ArrayList<>();
+        }
+        packageHierarchy = context.newArchive(null, null, directory);
+        moduleHierarchy = new LinkedHashMap<>();
+        resetToPackageHierarchy();
+    }
+
+    /**
+     * Resets this {@code FileCollector} to the state where a package hierarchy is presumed.
+     */
+    private void resetToPackageHierarchy() {
+        currentModule = packageHierarchy;
+        currentFilesToArchive = currentModule.baseRelease();
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a module.
+     * For an output generated by {@code javac} from a module source hierarchy,
+     * the directory name is guaranteed to be the module name.
+     *
+     * @param directory a {@code "<module>"} or {@code "META-INF/versions-modular/<module>"} directory
+     */
+    private void preVisitVersionDirectory(final Path directory) {
+        String moduleName = directory.getFileName().toString();
+        currentModule = moduleHierarchy.computeIfAbsent(
+                moduleName, (name) -> context.newArchive(name, currentTargetVersion, directory));
+        currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a target Java version.
+     * The {@code useDirectly} argument tells whether the content of this directory will be specified directly
+     * as the content to add in the <abbr>JAR</abbr> file. This argument should be {@code false} when there is
+     * another directory level (the module names) to process before to add content.
+     *
+     * @param directory a {@code "META-INF/versions/<n>"} or {@code "META-INF/versions-modular/<n>"} directory
+     * @param useDirectly whether the directory is {@code "META-INF/versions/<n>"}
+     * @return whether to skip the directory because of invalid version number
+     */
+    private boolean preVisitVersionDirectory(final Path directory, final boolean useDirectly) {
+        try {
+            currentTargetVersion = Runtime.Version.parse(directory.getFileName().toString());
+        } catch (IllegalArgumentException e) {
+            context.warnInvalidVersion(directory, e);
+            return true;
+        }
+        if (useDirectly) {
+            currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+        }
+        return false;
+    }
+
+    /**
+     * Determines if the given directory should be scanned for files to archive.
+     * This method may also update {@link #currentFilesToArchive} if it detects
+     * that we are visiting the content of a new module or a new target Java release.
+     *
+     * @param directory the directory which will be traversed
+     * @param attributes the directory's basic attributes
+     */
+    @Override
+    @SuppressWarnings("checkstyle:MissingSwitchDefault")
+    public FileVisitResult preVisitDirectory(final Path directory, final BasicFileAttributes attributes)
+            throws IOException {
+        DirectoryRole role;
+        if (directoryRoles.isEmpty()) {
+            role = DirectoryRole.ROOT;
+        } else {
+            if (!directoryMatcher.matches(directory)) {
+                excludedDirectories.add(directory); // Cannot be null if excluded directories may exist.
+                return FileVisitResult.SKIP_SUBTREE;
+            }
+            checkForManifest = false;
+            role = directoryRoles.getLast();
+            switch (role) {
+                case ROOT:
+                    /*
+                     * Visiting any subdirectory of `target/classes` (or other directory to archive).
+                     * We need to handle `META-INF` and modules in a special way, and archive the rest.
+                     */
+                    if (directory.endsWith(MetadataFiles.META_INF)) {
+                        role = DirectoryRole.META_INF;
+                        checkForManifest = true;
+                    } else if (Files.isRegularFile(directory.resolve(MODULE_DESCRIPTOR_FILE_NAME))) {
+                        role = DirectoryRole.NAMED_MODULE;
+                        preVisitVersionDirectory(directory);
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case META_INF:
+                    /*
+                     * Visiting a subdirectory of `META-INF` or `<module>/META-INF`. We will need to handle
+                     * `MANIFEST.MF`, `versions` and `versions-modular` in a special way, and archive the rest.
+                     */
+                    if (detectMultiReleaseJar && directory.endsWith(VERSIONS)) {
+                        role = DirectoryRole.VERSIONS;
+                    } else if (directory.endsWith(VERSIONS_MODULAR)) {
+                        if (!detectMultiReleaseJar) {
+                            // Used asked for no multi-release JAR.
+                            return FileVisitResult.SKIP_SUBTREE;
+                        }
+                        role = DirectoryRole.VERSIONS_MODULAR;
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case VERSIONS:
+                    /*
+                     * Visiting a `META-INF/versions/<n>/` directory for a specific target Java release.
+                     * Can also be a `<module>/META-INF/versions/<n>/` directory, even if the latter is not
+                     * the layout generated by Maven Compiler Plugin.
+                     */
+                    if (preVisitVersionDirectory(directory, true)) {
+                        // An error occurred while parsing the version number.
+                        return FileVisitResult.SKIP_SUBTREE;
+                    }
+                    role = DirectoryRole.RESOURCES;
+                    break;
+
+                case VERSIONS_MODULAR:
+                    /*
+                     * Visiting a `META-INF/versions-modular/<n>/` directory for a specific target Java release.
+                     * That directory contains all modules for the version.
+                     */
+                    resetToPackageHierarchy(); // No module in particular yet.
+                    if (preVisitVersionDirectory(directory, false)) {
+                        // An error occurred while parsing the version number.
+                        return FileVisitResult.SKIP_SUBTREE;
+                    }
+                    role = DirectoryRole.MODULES;
+                    break;
+
+                case MODULES:
+                    /*
+                     * Visiting a `META-INF/versions-modular/<n>/<module>` directory.
+                     */
+                    preVisitVersionDirectory(directory);
+                    role = DirectoryRole.NAMED_MODULE;
+                    break;
+
+                case NAMED_MODULE:
+                    /*
+                     * Visiting a `<module>` or `META-INF/versions-modular/<n>/<module>` subdirectory.
+                     * A module could have its own `META-INF` subdirectory, so we need to check again.
+                     */
+                    if (directory.endsWith(MetadataFiles.META_INF)) {
+                        role = DirectoryRole.META_INF;
+                        checkForManifest = true;
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+            }
+        }
+        /*
+         * Do not move this condition inside the `switch` block because `role` may have been modified.
+         * The `role` value is now the role of `directory`, not the role of parent directory.
+         */
+        if (role == DirectoryRole.RESOURCES) {
+            currentFilesToArchive.add(directory, attributes, true);
+            if (excludedFiles == null) {
+                /*
+                 * Since we are skipping the whole directory, `postVisitDirectory(…)` will not be invoked.
+                 * We must reset `currentFilesToArchive` and `currentTargetVersion` by an explicit call.
+                 * This is important mostly after we added a whole `META-INF/versions/<n>` directory.
+                 * Otherwise, since directory iteration order is unspecified, base files visited afterwards
+                 * would be added to this version's file set instead of the base release.
+                 */
+                resetToParentDirectoryState();
+                return FileVisitResult.SKIP_SUBTREE;
+            }
+        }
+        directoryRoles.addLast(role);
+        return FileVisitResult.CONTINUE;
+    }
+
+    /**
+     * Updates the {@code FileCollector} state after we finished scanning the contents of a directory.
+     * The fields to update depend on which directory has been visited (module, version, etc.).
+     *
+     * @param directory the directory which has been traversed
+     * @param error the error that occurred while traversing the directory, or {@code null} if none
+     */
+    @Override
+    public FileVisitResult postVisitDirectory(final Path directory, final IOException error) throws IOException {
+        if (error != null) {
+            throw error;
+        }
+        switch (directoryRoles.removeLast()) {
+            case ROOT:
+                break;
+
+            case NAMED_MODULE:
+                // Exited the directory of a single module.
+                resetToPackageHierarchy();
+                break;
+
+            default:
+                resetToParentDirectoryState();
+                break;
+        }
+        return FileVisitResult.CONTINUE;
+    }
+
+    /**
+     * Updates {@code FileCollector} to a state suitable for the parent of the directory that we finished to scan.
+     * Contrary to {@link #postVisitDirectory(Path, IOException)}, this method expects the last element of
+     * {@link #directoryRoles} to describe the parent directory, not the directory that we finished to visit.
+     */
+    @SuppressWarnings("checkstyle:MissingSwitchDefault")
+    private void resetToParentDirectoryState() {
+        switch (directoryRoles.getLast()) {
+            case VERSIONS:
+            case VERSIONS_MODULAR:
+                // Exited the directory for one target Java release.
+                currentFilesToArchive = currentModule.baseRelease();
+                currentTargetVersion = null;
+                break;
+
+            case META_INF:
+                checkForManifest = true;
+                break;
+        }
+    }
+
+    /**
+     * Archives a single file if accepted by the matcher.
+     *
+     * @param file the file
+     * @param attributes the file's basic attributes
+     */
+    @Override
+    public FileVisitResult visitFile(final Path file, final BasicFileAttributes attributes) {
+        if (fileMatcher.matches(file)) {
+            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.add(file, attributes, false);
+            }
+        } else {
+            excludedFiles.add(file); // Cannot be null if excluded files may exist.
+        }
+        return FileVisitResult.CONTINUE;
+    }
+
+    /**
+     * 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}
+     */
+    public void prune(boolean skipIfEmpty) {
+        boolean isModuleHierarchy = !moduleHierarchy.isEmpty();
+        moduleHierarchy.values().forEach((archive) -> archive.prune(skipIfEmpty));
+        moduleHierarchy.values().removeIf(Archive::isEmpty);
+        packageHierarchy.prune(isModuleHierarchy || skipIfEmpty);
+    }
+
+    /**
+     * Moves, copies, or ignores orphan files.
+     * An orphan file is a file which is not in any module when module hierarchy is used.
+     * For example, some Maven plugins may create files such as {@code META-INF/LICENSE},
+     * {@code META-INF/NOTICE} or {@code META-INF/DEPENDENCIES}. These files are not in
+     * the correct directory (they should be in a {@code "<module>/META-INF"} directory)
+     * because the plugin may not be aware of module hierarchy.
+     *
+     * <p>A possible strategy could be to copy the {@code LICENSE} and {@code NOTICE} files
+     * in each module, and ignore the {@code DEPENDENCIES} file because its content is not
+     * correct for a module. For now, we just log a warning and ignore.</p>
+     *
+     * <h4>Prerequisites</h4>

Review Comment:
   This is a constraint inherited from `Archive.isEmpty()`. This method does not invoke `prune` because it may be already done by the caller for other reasons, and it would force us to cascade the `boolean` argument expected by `prune`: `isEmpty` ← `handleOrphanFiles` ← `writeAllJARs` ← `createArchives`.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3921602001


##########
src/main/java/org/apache/maven/plugins/jar/AbstractJarMojo.java:
##########
@@ -140,24 +144,52 @@ public abstract class AbstractJarMojo implements org.apache.maven.api.plugin.Moj
      * Timestamp for reproducible output archive entries.
      * This is either formatted as ISO 8601 extended offset date-time
      * (e.g. in UTC such as '2011-12-03T10:15:30Z' or with an offset '2019-10-05T20:37:42+06:00'),
-     * or as an integer representing seconds since the epoch
-     * (like <a href="https://reproducible-builds.org/docs/source-date-epoch/">SOURCE_DATE_EPOCH</a>).
+     * or as an integer representing seconds since the Java epoch (January 1st, 1970).
+     * If not configured or disabled,
+     * the <a href="https://reproducible-builds.org/docs/source-date-epoch/">SOURCE_DATE_EPOCH</a>
+     * environment variable is used as a fallback value,
+     * to ease forcing Reproducible Build externally when the build has not enabled it natively in <abbr>POM</abbr>.
+     *
+     * <p>This property is supported only in Java 19 or later.</p>
      *
      * @since 3.2.0
      */
     @Parameter(defaultValue = "${project.build.outputTimestamp}")
     protected String outputTimestamp;
 
     /**
-     * Whether to detect multi-release JAR files.
-     * If the JAR contains the {@code META-INF/versions} directory it will be detected as a multi-release JAR file
-     * ("MRJAR"), adding the {@code Multi-Release: true} attribute to the main section of the JAR {@code MANIFEST.MF}.
+     * Whether to detect multi-release <abbr>JAR</abbr> files.
+     * If the JAR contains the {@code META-INF/versions} directory, it is detected as a multi-release JAR file.

Review Comment:
   I do not put `<abbr>` everywhere. We are often asked to avoid abbreviations, or at least give their meaning. I put some `<abbr>` in prominent occurrences of the abbreviation and omit `<abbr>` elsewhere. I agree that `<abbr>` without `title` is not very useful, but I tend to omit `title` because it could be automatized (even if this is not the case yet).



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3921812844


##########
src/main/java/org/apache/maven/plugins/jar/Archive.java:
##########
@@ -0,0 +1,655 @@
+/*
+ * 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.jar;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.TreeMap;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.Type;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.MojoException;
+
+/**
+ * Files or root directories to archive for a single module.
+ * A single instance of {@code Archive} can contain many directories for different target Java releases.
+ * Many instances of {@code Archive} can exist when archiving a multi-modules project.
+ */
+final class Archive {
+    /**
+     * Path to the <abbr>POM</abbr> file generated for this archive, or {@code null} if none.
+     * This is non-null only if module source hierarchy is used, in which case the dependencies
+     * declared in this file are the intersection of the project dependencies and the content of
+     * the {@code module-info.class} file.
+     */
+    @Nullable
+    Path pomFile;
+
+    /**
+     * The <var>JAR</var> file to create. Can be an existing file,
+     * in which case the file creation can be skipped if the file is still up-to-date.
+     */
+    @Nonnull
+    final Path jarFile;
+
+    /**
+     * A helper class for checking whether an existing <abbr>JAR</abbr> file is still up-to-date.
+     * This is null if there is no existing JAR file, or if we determined that the file is outdated.
+     */
+    private TimestampCheck existingJAR;
+
+    /**
+     * Name of the module being archived when the project is using module hierarchy.
+     * This is {@code null} if the project is using package hierarchy, either because it is a classical
+     * class-path project or because it is a single module compiled without using the module hierarchy.
+     * When using module source hierarchy, {@code javac} guarantees that the module name in the output
+     * directory is the name of the parent directory of {@code module-info.class}.
+     */
+    @Nullable
+    final String moduleName;
+
+    /**
+     * Path to {@code META-INF/MANIFEST.MF}, or {@code null} if none.
+     * If non-null, this value will be given to the {@code --manifest} option.
+     * The use of this option is preferable to adding {@code MANIFEST.MF} as an ordinary file.
+     *
+     * @see #setManifest(Path, boolean)
+     * @see #mergeManifest(Path, Manifest)
+     */
+    @Nullable
+    private Path manifest;
+
+    /**
+     * The Maven generated {@code pom.xml} and {@code pom.properties} files, or {@code null} if none.
+     * This first item must be the base directory where the files are located.
+     */
+    @Nullable
+    List<Path> mavenFiles;
+
+    /**
+     * Fully-qualified name of the main class, or {@code null} if none.
+     * This is the value to provide to the {@code --main-class} option.
+     */
+    private String mainClass;
+
+    /**
+     * Files or root directories to store in the <abbr>JAR</abbr> file for each target Java release
+     * other than the base release. Keys are the target Java release with {@code null} for the base
+     * release.
+     */
+    @Nonnull
+    private final NavigableMap<Runtime.Version, FileSet> filesetForRelease;
+
+    /**
+     * Files or root directories to archive for a single target Java release of a single module.
+     * The {@link Archive} enclosing must contain at least one instance of {@code FileSet} for
+     * the base release, and an arbitrary amount of other instances for other target releases.
+     */
+    final class FileSet {
+        /**
+         * The root directory of all files or directories to archive.
+         * This is the value to pass to the {@code -C} tool option.
+         */
+        @Nonnull
+        final Path directory;
+
+        /**
+         * The files or directories to include in the <var>JAR</var> file.
+         * Can be absolute paths or paths relative to {@link #directory}.
+         * It usually contains only the files or directories directly in
+         * the root {@linkplain #directory}, not in sub-directories.
+         */
+        @Nonnull
+        final List<Path> files;
+
+        /**
+         * Creates an initially empty set of files or directories for a specific target Java release.
+         *
+         * @param directory the base directory of the files or directories to archive
+         */
+        private FileSet(Path directory) {
+            this.directory = directory;
+            this.files = new ArrayList<>();
+        }
+
+        /**
+         * 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.
+         * The caller should use that common directory for logging a warning message.
+         *
+         * @param base base directory found by previous invocations of this method, or {@code null} if none
+         * @return common directory of discarded files
+         */
+        private Path discardAllFiles(Path base) {
+            for (Path file : files) {
+                if (base == null) {
+                    base = file.getParent();
+                } else {
+                    while (!file.startsWith(base)) {
+                        base = base.getParent();
+                        if (base == null) {
+                            break;
+                        }
+                    }
+                }
+            }
+            files.clear();
+            return base;
+        }
+
+        /**
+         * Adds the given path to the list of files or directories to archive.
+         * If the given path is a directory, then all children will be included.
+         * Children to exclude, if any, should be managed by {@link ExcludedFiles}.
+         *
+         * @param item a file or directory to archive
+         * @param attributes the file's basic attributes
+         * @param isDirectory whether the file is a directory
+         */
+        void add(Path item, BasicFileAttributes attributes, boolean isDirectory) {
+            TimestampCheck tc = existingJAR;
+            if (tc != null && tc.isUpdated(item, attributes, isDirectory)) {
+                existingJAR = null; // Signal that the existing file is outdated.
+            }
+            files.add(item);
+        }
+
+        /**
+         * Adds to the given list the arguments to provide to the "jar" tool for this version.
+         * The elements added to the list will be instances of {@link String} or {@link Path}.
+         *
+         * <h4>Note about the {@code -C} option</h4>
+         * This method repeats the {@code -C} option before each file.
+         * Our tests suggest that the first file after the directory specified by the {@code -C} option must
+         * be relative to that directory and all files after the first one must be prefixed by the directory
+         * which was specified in the {@code -C} option. This behavior is not very intuitive and replying on
+         * it can be fragile. Furthermore, it seems that the relativized file needs to be the shortest one,
+         * otherwise the {@code jar} tool rejects files after the first one with "names do not match".
+         * Which file is first depends on the unspecified directory-iteration order.
+         * Repeating the {@code -C} option for each file seems safer.
+         *
+         * @param addTo the list to add the arguments as {@link String} or {@link Path} instances to
+         * @param version the target Java release, or {@code null} for the base version of the <abbr>JAR</abbr> file
+         * @throws IllegalArgumentException if a path cannot be made relative to the base directory
+         */
+        private void arguments(List<Object> addTo, Runtime.Version version) {
+            if (files.isEmpty()) {
+                return;
+            }
+            if (version != null) {
+                addTo.add("--release");
+                addTo.add(version);
+            }
+            Path previous = null;
+            for (Path file : files) {
+                if (previous != null && file.startsWith(previous)) {
+                    // Already added a parent directory.
+                    continue;
+                }
+                previous = file;
+                file = directory.relativize(file);
+                if (file.getNameCount() <= 1 && file.toString().isEmpty()) {
+                    /*
+                     * The `-C` directory itself (e.g. a "META-INF/versions/<n>" directory added as a whole).
+                     * An empty file argument is invalid for the `jar` tool (some implementations reject it,
+                     * others silently misbehave), so archive the whole directory content with ".".
+                     */
+                    file = Path.of(".");
+                }
+                addTo.add("-C");
+                addTo.add(directory);
+                addTo.add(file);
+            }
+        }
+
+        /**
+         * {@return a string representation for debugging purposes}
+         */
+        @Override
+        public String toString() {
+            return getClass().getSimpleName() + '[' + directory.getFileName() + ": " + files.size() + " files]";
+        }
+    }
+
+    /**
+     * Creates an initially empty set of files or directories.
+     *
+     * @param jarFile path to the <abbr>JAR</abbr> file to create
+     * @param moduleName the module name if using module hierarchy, or {@code null} if using package hierarchy
+     * @param version the target Java release, or {@code null} for the base version
+     * @param directory the directory of the classes targeting the base Java release
+     * @param forceCreation whether to force a new <abbr>JAR</abbr> file even if the content seems unchanged
+     * @param logger where to send a warning if an error occurred while checking an existing <abbr>JAR</abbr> file
+     */
+    @SuppressWarnings("checkstyle:NeedBraces")
+    Archive(
+            final Path jarFile,
+            final String moduleName,
+            final Runtime.Version version,
+            final Path directory,
+            final boolean forceCreation,
+            final Log logger) {
+        this.jarFile = jarFile;
+        this.moduleName = moduleName;
+        filesetForRelease = new TreeMap<>((v1, v2) -> {
+            if (v1 == v2) return 0;
+            if (v1 == null) return -1;
+            if (v2 == null) return +1;
+            return v1.compareTo(v2);
+        });
+        filesetForRelease.put(version, new FileSet(directory));
+        if (!forceCreation && Files.isRegularFile(jarFile)) {
+            try {
+                existingJAR = new TimestampCheck(jarFile, directory, logger);
+            } catch (IOException e) {
+                // Ignore, we will regenerate the JAR file.
+                logger.warn(e);
+            }
+        }
+    }
+
+    /**
+     * {@return the files or directories to store in the <abbr>JAR</abbr> file for targeting the base Java release}
+     *
+     * @throws NoSuchElementException should not happen unless {@link #prune(boolean)} has been invoked
+     */
+    FileSet baseRelease() {
+        Map.Entry<Runtime.Version, FileSet> entry = filesetForRelease.firstEntry();
+        String message = null;
+        if (entry != null) {
+            Runtime.Version version = entry.getKey();
+            if (version == null) {
+                return entry.getValue();
+            }
+            message = "Expected base version but found version " + version;
+        }
+        throw new NoSuchElementException(message);
+    }
+
+    /**
+     * Returns the {@code module-info.class} files. Conceptually, there is at most once such file per module.
+     * However, more than one file can exist if additional files are provided for additional Java releases.
+     * This method returns only the files that exist.
+     *
+     * @return all {@code module-info.class} files found for all target Java releases
+     */
+    public List<Path> moduleInfoFiles() {
+        var files = new ArrayList<Path>();
+        filesetForRelease.values().forEach((release) -> {
+            Path file = release.directory.resolve(FileCollector.MODULE_DESCRIPTOR_FILE_NAME);
+            if (Files.isRegularFile(file)) {
+                files.add(file);
+            }
+        });
+        return files;
+    }
+
+    /**
+     * Discards all files in this archive, normally because those files are not in any module.
+     * This method returns a common parent directory for all the files that were discarded.
+     * The caller should use that common directory for logging a warning message.
+     *
+     * @return common directory of discarded files, or {@code null} if none
+     */
+    Path discardAllFiles() {
+        Path base = null;
+        for (FileSet release : filesetForRelease.values()) {
+            base = release.discardAllFiles(base);
+        }
+        filesetForRelease.clear();
+        return base;
+    }
+
+    /**
+     * Removes all empty file sets 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}, then this method ensures that at least one file set
+     * remains even if that file set is empty.
+     *
+     * @param skipIfEmpty value of {@link AbstractJarMojo#skipIfEmpty}
+     */
+    public void prune(final boolean skipIfEmpty) {
+        FileSet keep = (skipIfEmpty || isEmpty())
+                ? null
+                : filesetForRelease.firstEntry().getValue();
+        filesetForRelease.values().removeIf((fs) -> fs.files.isEmpty());
+        Iterator<Map.Entry<Runtime.Version, FileSet>> it =
+                filesetForRelease.entrySet().iterator();
+        if (it.hasNext()) {
+            Map.Entry<Runtime.Version, FileSet> first = it.next();
+            if (first.getKey() == null) {
+                return; // Already contains an entry for the base version, nothing to do.
+            }
+            keep = first.getValue();
+            it.remove();
+        }
+        if (keep != null) {
+            filesetForRelease.put(null, keep);
+        }
+    }
+
+    /**
+     * {@return whether this archive has nothing to archive}
+     * This method can return {@code false} even when there is zero file to archive.
+     * It can happen if {@link AbstractJarMojo#skipIfEmpty} is {@code false}. In such case, the

Review Comment:
   Done.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3921803299


##########
src/main/java/org/apache/maven/plugins/jar/Archive.java:
##########
@@ -0,0 +1,655 @@
+/*
+ * 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.jar;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.TreeMap;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.Type;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.MojoException;
+
+/**
+ * Files or root directories to archive for a single module.
+ * A single instance of {@code Archive} can contain many directories for different target Java releases.
+ * Many instances of {@code Archive} can exist when archiving a multi-modules project.
+ */
+final class Archive {
+    /**
+     * Path to the <abbr>POM</abbr> file generated for this archive, or {@code null} if none.
+     * This is non-null only if module source hierarchy is used, in which case the dependencies
+     * declared in this file are the intersection of the project dependencies and the content of
+     * the {@code module-info.class} file.
+     */
+    @Nullable
+    Path pomFile;
+
+    /**
+     * The <var>JAR</var> file to create. Can be an existing file,
+     * in which case the file creation can be skipped if the file is still up-to-date.
+     */
+    @Nonnull
+    final Path jarFile;
+
+    /**
+     * A helper class for checking whether an existing <abbr>JAR</abbr> file is still up-to-date.
+     * This is null if there is no existing JAR file, or if we determined that the file is outdated.
+     */
+    private TimestampCheck existingJAR;
+
+    /**
+     * Name of the module being archived when the project is using module hierarchy.
+     * This is {@code null} if the project is using package hierarchy, either because it is a classical
+     * class-path project or because it is a single module compiled without using the module hierarchy.
+     * When using module source hierarchy, {@code javac} guarantees that the module name in the output
+     * directory is the name of the parent directory of {@code module-info.class}.
+     */
+    @Nullable
+    final String moduleName;
+
+    /**
+     * Path to {@code META-INF/MANIFEST.MF}, or {@code null} if none.
+     * If non-null, this value will be given to the {@code --manifest} option.
+     * The use of this option is preferable to adding {@code MANIFEST.MF} as an ordinary file.
+     *
+     * @see #setManifest(Path, boolean)
+     * @see #mergeManifest(Path, Manifest)
+     */
+    @Nullable
+    private Path manifest;
+
+    /**
+     * The Maven generated {@code pom.xml} and {@code pom.properties} files, or {@code null} if none.
+     * This first item must be the base directory where the files are located.
+     */
+    @Nullable
+    List<Path> mavenFiles;
+
+    /**
+     * Fully-qualified name of the main class, or {@code null} if none.
+     * This is the value to provide to the {@code --main-class} option.
+     */
+    private String mainClass;
+
+    /**
+     * Files or root directories to store in the <abbr>JAR</abbr> file for each target Java release
+     * other than the base release. Keys are the target Java release with {@code null} for the base
+     * release.
+     */
+    @Nonnull
+    private final NavigableMap<Runtime.Version, FileSet> filesetForRelease;
+
+    /**
+     * Files or root directories to archive for a single target Java release of a single module.
+     * The {@link Archive} enclosing must contain at least one instance of {@code FileSet} for
+     * the base release, and an arbitrary amount of other instances for other target releases.
+     */
+    final class FileSet {
+        /**
+         * The root directory of all files or directories to archive.
+         * This is the value to pass to the {@code -C} tool option.
+         */
+        @Nonnull
+        final Path directory;
+
+        /**
+         * The files or directories to include in the <var>JAR</var> file.
+         * Can be absolute paths or paths relative to {@link #directory}.
+         * It usually contains only the files or directories directly in
+         * the root {@linkplain #directory}, not in sub-directories.
+         */
+        @Nonnull
+        final List<Path> files;
+
+        /**
+         * Creates an initially empty set of files or directories for a specific target Java release.
+         *
+         * @param directory the base directory of the files or directories to archive
+         */
+        private FileSet(Path directory) {
+            this.directory = directory;
+            this.files = new ArrayList<>();
+        }
+
+        /**
+         * 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.
+         * The caller should use that common directory for logging a warning message.
+         *
+         * @param base base directory found by previous invocations of this method, or {@code null} if none
+         * @return common directory of discarded files
+         */
+        private Path discardAllFiles(Path base) {
+            for (Path file : files) {
+                if (base == null) {
+                    base = file.getParent();
+                } else {
+                    while (!file.startsWith(base)) {
+                        base = base.getParent();
+                        if (base == null) {
+                            break;
+                        }
+                    }
+                }
+            }
+            files.clear();
+            return base;
+        }
+
+        /**
+         * Adds the given path to the list of files or directories to archive.
+         * If the given path is a directory, then all children will be included.
+         * Children to exclude, if any, should be managed by {@link ExcludedFiles}.
+         *
+         * @param item a file or directory to archive
+         * @param attributes the file's basic attributes
+         * @param isDirectory whether the file is a directory
+         */
+        void add(Path item, BasicFileAttributes attributes, boolean isDirectory) {
+            TimestampCheck tc = existingJAR;
+            if (tc != null && tc.isUpdated(item, attributes, isDirectory)) {
+                existingJAR = null; // Signal that the existing file is outdated.
+            }
+            files.add(item);
+        }
+
+        /**
+         * Adds to the given list the arguments to provide to the "jar" tool for this version.
+         * The elements added to the list will be instances of {@link String} or {@link Path}.
+         *
+         * <h4>Note about the {@code -C} option</h4>
+         * This method repeats the {@code -C} option before each file.
+         * Our tests suggest that the first file after the directory specified by the {@code -C} option must
+         * be relative to that directory and all files after the first one must be prefixed by the directory
+         * which was specified in the {@code -C} option. This behavior is not very intuitive and replying on
+         * it can be fragile. Furthermore, it seems that the relativized file needs to be the shortest one,
+         * otherwise the {@code jar} tool rejects files after the first one with "names do not match".
+         * Which file is first depends on the unspecified directory-iteration order.
+         * Repeating the {@code -C} option for each file seems safer.
+         *
+         * @param addTo the list to add the arguments as {@link String} or {@link Path} instances to
+         * @param version the target Java release, or {@code null} for the base version of the <abbr>JAR</abbr> file
+         * @throws IllegalArgumentException if a path cannot be made relative to the base directory
+         */
+        private void arguments(List<Object> addTo, Runtime.Version version) {
+            if (files.isEmpty()) {
+                return;
+            }
+            if (version != null) {
+                addTo.add("--release");
+                addTo.add(version);
+            }
+            Path previous = null;
+            for (Path file : files) {
+                if (previous != null && file.startsWith(previous)) {
+                    // Already added a parent directory.
+                    continue;
+                }
+                previous = file;
+                file = directory.relativize(file);
+                if (file.getNameCount() <= 1 && file.toString().isEmpty()) {
+                    /*
+                     * The `-C` directory itself (e.g. a "META-INF/versions/<n>" directory added as a whole).
+                     * An empty file argument is invalid for the `jar` tool (some implementations reject it,
+                     * others silently misbehave), so archive the whole directory content with ".".
+                     */
+                    file = Path.of(".");
+                }
+                addTo.add("-C");
+                addTo.add(directory);
+                addTo.add(file);
+            }
+        }
+
+        /**
+         * {@return a string representation for debugging purposes}
+         */
+        @Override
+        public String toString() {
+            return getClass().getSimpleName() + '[' + directory.getFileName() + ": " + files.size() + " files]";
+        }
+    }
+
+    /**
+     * Creates an initially empty set of files or directories.
+     *
+     * @param jarFile path to the <abbr>JAR</abbr> file to create
+     * @param moduleName the module name if using module hierarchy, or {@code null} if using package hierarchy
+     * @param version the target Java release, or {@code null} for the base version
+     * @param directory the directory of the classes targeting the base Java release
+     * @param forceCreation whether to force a new <abbr>JAR</abbr> file even if the content seems unchanged
+     * @param logger where to send a warning if an error occurred while checking an existing <abbr>JAR</abbr> file
+     */
+    @SuppressWarnings("checkstyle:NeedBraces")
+    Archive(
+            final Path jarFile,
+            final String moduleName,
+            final Runtime.Version version,
+            final Path directory,
+            final boolean forceCreation,
+            final Log logger) {
+        this.jarFile = jarFile;
+        this.moduleName = moduleName;
+        filesetForRelease = new TreeMap<>((v1, v2) -> {
+            if (v1 == v2) return 0;
+            if (v1 == null) return -1;
+            if (v2 == null) return +1;
+            return v1.compareTo(v2);
+        });
+        filesetForRelease.put(version, new FileSet(directory));
+        if (!forceCreation && Files.isRegularFile(jarFile)) {
+            try {
+                existingJAR = new TimestampCheck(jarFile, directory, logger);
+            } catch (IOException e) {
+                // Ignore, we will regenerate the JAR file.
+                logger.warn(e);
+            }
+        }
+    }
+
+    /**
+     * {@return the files or directories to store in the <abbr>JAR</abbr> file for targeting the base Java release}
+     *
+     * @throws NoSuchElementException should not happen unless {@link #prune(boolean)} has been invoked
+     */
+    FileSet baseRelease() {
+        Map.Entry<Runtime.Version, FileSet> entry = filesetForRelease.firstEntry();
+        String message = null;
+        if (entry != null) {
+            Runtime.Version version = entry.getKey();
+            if (version == null) {
+                return entry.getValue();
+            }
+            message = "Expected base version but found version " + version;
+        }
+        throw new NoSuchElementException(message);
+    }
+
+    /**
+     * Returns the {@code module-info.class} files. Conceptually, there is at most once such file per module.

Review Comment:
   > one such
   
   Fixed, thanks.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3921945038


##########
src/main/java/org/apache/maven/plugins/jar/Archive.java:
##########
@@ -0,0 +1,655 @@
+/*
+ * 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.jar;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.TreeMap;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.Type;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.MojoException;
+
+/**
+ * Files or root directories to archive for a single module.
+ * A single instance of {@code Archive} can contain many directories for different target Java releases.
+ * Many instances of {@code Archive} can exist when archiving a multi-modules project.
+ */
+final class Archive {
+    /**
+     * Path to the <abbr>POM</abbr> file generated for this archive, or {@code null} if none.
+     * This is non-null only if module source hierarchy is used, in which case the dependencies
+     * declared in this file are the intersection of the project dependencies and the content of
+     * the {@code module-info.class} file.
+     */
+    @Nullable
+    Path pomFile;
+
+    /**
+     * The <var>JAR</var> file to create. Can be an existing file,
+     * in which case the file creation can be skipped if the file is still up-to-date.
+     */
+    @Nonnull
+    final Path jarFile;
+
+    /**
+     * A helper class for checking whether an existing <abbr>JAR</abbr> file is still up-to-date.
+     * This is null if there is no existing JAR file, or if we determined that the file is outdated.
+     */
+    private TimestampCheck existingJAR;
+
+    /**
+     * Name of the module being archived when the project is using module hierarchy.
+     * This is {@code null} if the project is using package hierarchy, either because it is a classical
+     * class-path project or because it is a single module compiled without using the module hierarchy.
+     * When using module source hierarchy, {@code javac} guarantees that the module name in the output
+     * directory is the name of the parent directory of {@code module-info.class}.
+     */
+    @Nullable
+    final String moduleName;
+
+    /**
+     * Path to {@code META-INF/MANIFEST.MF}, or {@code null} if none.
+     * If non-null, this value will be given to the {@code --manifest} option.
+     * The use of this option is preferable to adding {@code MANIFEST.MF} as an ordinary file.
+     *
+     * @see #setManifest(Path, boolean)
+     * @see #mergeManifest(Path, Manifest)
+     */
+    @Nullable
+    private Path manifest;
+
+    /**
+     * The Maven generated {@code pom.xml} and {@code pom.properties} files, or {@code null} if none.
+     * This first item must be the base directory where the files are located.
+     */
+    @Nullable
+    List<Path> mavenFiles;
+
+    /**
+     * Fully-qualified name of the main class, or {@code null} if none.
+     * This is the value to provide to the {@code --main-class} option.
+     */
+    private String mainClass;
+
+    /**
+     * Files or root directories to store in the <abbr>JAR</abbr> file for each target Java release
+     * other than the base release. Keys are the target Java release with {@code null} for the base
+     * release.
+     */
+    @Nonnull
+    private final NavigableMap<Runtime.Version, FileSet> filesetForRelease;
+
+    /**
+     * Files or root directories to archive for a single target Java release of a single module.
+     * The {@link Archive} enclosing must contain at least one instance of {@code FileSet} for
+     * the base release, and an arbitrary amount of other instances for other target releases.
+     */
+    final class FileSet {
+        /**
+         * The root directory of all files or directories to archive.
+         * This is the value to pass to the {@code -C} tool option.
+         */
+        @Nonnull
+        final Path directory;
+
+        /**
+         * The files or directories to include in the <var>JAR</var> file.
+         * Can be absolute paths or paths relative to {@link #directory}.
+         * It usually contains only the files or directories directly in
+         * the root {@linkplain #directory}, not in sub-directories.
+         */
+        @Nonnull
+        final List<Path> files;
+
+        /**
+         * Creates an initially empty set of files or directories for a specific target Java release.
+         *
+         * @param directory the base directory of the files or directories to archive
+         */
+        private FileSet(Path directory) {
+            this.directory = directory;
+            this.files = new ArrayList<>();
+        }
+
+        /**
+         * 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.
+         * The caller should use that common directory for logging a warning message.
+         *
+         * @param base base directory found by previous invocations of this method, or {@code null} if none
+         * @return common directory of discarded files
+         */
+        private Path discardAllFiles(Path base) {
+            for (Path file : files) {
+                if (base == null) {
+                    base = file.getParent();
+                } else {
+                    while (!file.startsWith(base)) {
+                        base = base.getParent();
+                        if (base == null) {
+                            break;
+                        }
+                    }
+                }
+            }
+            files.clear();
+            return base;
+        }
+
+        /**
+         * Adds the given path to the list of files or directories to archive.
+         * If the given path is a directory, then all children will be included.
+         * Children to exclude, if any, should be managed by {@link ExcludedFiles}.
+         *
+         * @param item a file or directory to archive
+         * @param attributes the file's basic attributes
+         * @param isDirectory whether the file is a directory
+         */
+        void add(Path item, BasicFileAttributes attributes, boolean isDirectory) {
+            TimestampCheck tc = existingJAR;
+            if (tc != null && tc.isUpdated(item, attributes, isDirectory)) {
+                existingJAR = null; // Signal that the existing file is outdated.
+            }
+            files.add(item);
+        }
+
+        /**
+         * Adds to the given list the arguments to provide to the "jar" tool for this version.
+         * The elements added to the list will be instances of {@link String} or {@link Path}.
+         *
+         * <h4>Note about the {@code -C} option</h4>
+         * This method repeats the {@code -C} option before each file.
+         * Our tests suggest that the first file after the directory specified by the {@code -C} option must
+         * be relative to that directory and all files after the first one must be prefixed by the directory
+         * which was specified in the {@code -C} option. This behavior is not very intuitive and replying on
+         * it can be fragile. Furthermore, it seems that the relativized file needs to be the shortest one,
+         * otherwise the {@code jar} tool rejects files after the first one with "names do not match".
+         * Which file is first depends on the unspecified directory-iteration order.
+         * Repeating the {@code -C} option for each file seems safer.
+         *
+         * @param addTo the list to add the arguments as {@link String} or {@link Path} instances to
+         * @param version the target Java release, or {@code null} for the base version of the <abbr>JAR</abbr> file
+         * @throws IllegalArgumentException if a path cannot be made relative to the base directory
+         */
+        private void arguments(List<Object> addTo, Runtime.Version version) {
+            if (files.isEmpty()) {
+                return;
+            }
+            if (version != null) {
+                addTo.add("--release");
+                addTo.add(version);
+            }
+            Path previous = null;
+            for (Path file : files) {
+                if (previous != null && file.startsWith(previous)) {
+                    // Already added a parent directory.
+                    continue;
+                }
+                previous = file;
+                file = directory.relativize(file);
+                if (file.getNameCount() <= 1 && file.toString().isEmpty()) {
+                    /*
+                     * The `-C` directory itself (e.g. a "META-INF/versions/<n>" directory added as a whole).
+                     * An empty file argument is invalid for the `jar` tool (some implementations reject it,
+                     * others silently misbehave), so archive the whole directory content with ".".
+                     */
+                    file = Path.of(".");
+                }
+                addTo.add("-C");
+                addTo.add(directory);
+                addTo.add(file);
+            }
+        }
+
+        /**
+         * {@return a string representation for debugging purposes}
+         */
+        @Override
+        public String toString() {
+            return getClass().getSimpleName() + '[' + directory.getFileName() + ": " + files.size() + " files]";
+        }
+    }
+
+    /**
+     * Creates an initially empty set of files or directories.
+     *
+     * @param jarFile path to the <abbr>JAR</abbr> file to create
+     * @param moduleName the module name if using module hierarchy, or {@code null} if using package hierarchy
+     * @param version the target Java release, or {@code null} for the base version
+     * @param directory the directory of the classes targeting the base Java release
+     * @param forceCreation whether to force a new <abbr>JAR</abbr> file even if the content seems unchanged
+     * @param logger where to send a warning if an error occurred while checking an existing <abbr>JAR</abbr> file
+     */
+    @SuppressWarnings("checkstyle:NeedBraces")
+    Archive(
+            final Path jarFile,
+            final String moduleName,
+            final Runtime.Version version,
+            final Path directory,
+            final boolean forceCreation,
+            final Log logger) {
+        this.jarFile = jarFile;
+        this.moduleName = moduleName;
+        filesetForRelease = new TreeMap<>((v1, v2) -> {
+            if (v1 == v2) return 0;
+            if (v1 == null) return -1;
+            if (v2 == null) return +1;
+            return v1.compareTo(v2);
+        });
+        filesetForRelease.put(version, new FileSet(directory));
+        if (!forceCreation && Files.isRegularFile(jarFile)) {
+            try {
+                existingJAR = new TimestampCheck(jarFile, directory, logger);
+            } catch (IOException e) {
+                // Ignore, we will regenerate the JAR file.
+                logger.warn(e);
+            }
+        }
+    }
+
+    /**
+     * {@return the files or directories to store in the <abbr>JAR</abbr> file for targeting the base Java release}
+     *
+     * @throws NoSuchElementException should not happen unless {@link #prune(boolean)} has been invoked
+     */
+    FileSet baseRelease() {
+        Map.Entry<Runtime.Version, FileSet> entry = filesetForRelease.firstEntry();
+        String message = null;
+        if (entry != null) {
+            Runtime.Version version = entry.getKey();
+            if (version == null) {
+                return entry.getValue();
+            }
+            message = "Expected base version but found version " + version;
+        }
+        throw new NoSuchElementException(message);
+    }
+
+    /**
+     * Returns the {@code module-info.class} files. Conceptually, there is at most once such file per module.
+     * However, more than one file can exist if additional files are provided for additional Java releases.
+     * This method returns only the files that exist.
+     *
+     * @return all {@code module-info.class} files found for all target Java releases
+     */
+    public List<Path> moduleInfoFiles() {
+        var files = new ArrayList<Path>();
+        filesetForRelease.values().forEach((release) -> {
+            Path file = release.directory.resolve(FileCollector.MODULE_DESCRIPTOR_FILE_NAME);
+            if (Files.isRegularFile(file)) {
+                files.add(file);
+            }
+        });
+        return files;
+    }
+
+    /**
+     * Discards all files in this archive, normally because those files are not in any module.
+     * This method returns a common parent directory for all the files that were discarded.
+     * The caller should use that common directory for logging a warning message.
+     *
+     * @return common directory of discarded files, or {@code null} if none
+     */
+    Path discardAllFiles() {
+        Path base = null;
+        for (FileSet release : filesetForRelease.values()) {
+            base = release.discardAllFiles(base);
+        }
+        filesetForRelease.clear();
+        return base;
+    }
+
+    /**
+     * Removes all empty file sets 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}, then this method ensures that at least one file set
+     * remains even if that file set is empty.
+     *
+     * @param skipIfEmpty value of {@link AbstractJarMojo#skipIfEmpty}
+     */
+    public void prune(final boolean skipIfEmpty) {
+        FileSet keep = (skipIfEmpty || isEmpty())
+                ? null
+                : filesetForRelease.firstEntry().getValue();
+        filesetForRelease.values().removeIf((fs) -> fs.files.isEmpty());
+        Iterator<Map.Entry<Runtime.Version, FileSet>> it =
+                filesetForRelease.entrySet().iterator();
+        if (it.hasNext()) {
+            Map.Entry<Runtime.Version, FileSet> first = it.next();
+            if (first.getKey() == null) {
+                return; // Already contains an entry for the base version, nothing to do.
+            }
+            keep = first.getValue();
+            it.remove();
+        }
+        if (keep != null) {
+            filesetForRelease.put(null, keep);
+        }
+    }
+
+    /**
+     * {@return whether this archive has nothing to archive}
+     * This method can return {@code false} even when there is zero file to archive.
+     * It can happen if {@link AbstractJarMojo#skipIfEmpty} is {@code false}. In such case, the
+     * "empty" <abbr>JAR</abbr> file will still contain at {@code META-INF/MANIFEST.MF} file.
+     *
+     * <h4>Prerequisites</h4>
+     * The {@link #prune(boolean)} method should be invoked before this method for accurate result.
+     */
+    public boolean isEmpty() {
+        return filesetForRelease.isEmpty();
+    }
+
+    /**
+     * Checks whether the <abbr>JAR</abbr> file already exists and can be reused.
+     * This method verifies that the <abbr>JAR</abbr> file contains all the files to archive,
+     * contains no extra file, and no file to archive is newer than the <abbr>JAR</abbr> file.
+     *
+     * <p>This method can be invoked only once.
+     * If invoked more often, it returns {@code false} on all subsequent invocations.</p>
+     *
+     * @return whether the <abbr>JAR</abbr> file already exists and can be reused
+     */
+    public boolean isUpToDateJAR() {
+        final TimestampCheck tc = existingJAR;
+        if (tc == null) {
+            return false;
+        }
+        existingJAR = null; // Let GC do its job.
+        return tc.isUpToDateJAR(filesetForRelease.values());
+    }
+
+    /**
+     * Returns an initially empty set of files or directories for the specified target Java release.
+     *
+     * @param directory the base directory of the files to archive
+     * @param version the target Java release, or {@code null} for the base version
+     * @return container where to declare files and directories to archive
+     */
+    FileSet newTargetRelease(Path directory, Runtime.Version version) {
+        return filesetForRelease.computeIfAbsent(version, (key) -> new FileSet(directory));
+    }
+
+    /**
+     * Sets the {@code --main-class} option to the value of the {@code Main-Class} entry of the given manifest.
+     * As an extension, this method accepts the {@code module/classname} syntax (a syntax already used in some
+     * Java tools). If a module is specified, the main class is kept only if the module match. The intent is to
+     * allow users to specify on which module the main class applies when they use plugin configuration.
+     *
+     * <p>This method may modify the {@code content} manifest. Caller must ensure that the given manifest
+     * is not a shared instance. This method returns whether a change has actually been done.</p>
+     *
+     * @param content combination of existing {@code MANIFEST.MF} and manifest inferred from configuration, or null
+     * @return whether the given manifest has been modified by this method
+     */
+    boolean setMainClass(Manifest content) {
+        if (content == null || mainClass != null) {
+            return false;
+        }
+        // We need to remove the attribute, otherwise it will conflict with `--main-class`.
+        mainClass = (String) content.getMainAttributes().remove(Attributes.Name.MAIN_CLASS);
+        if (mainClass != null) {
+            int s = mainClass.indexOf('/');
+            if (s >= 0) {
+                if (mainClass.substring(0, s).strip().equals(moduleName)) {
+                    mainClass = mainClass.substring(s + 1).strip();
+                } else {
+                    mainClass = null; // Main class is defined for another module.
+                }
+            }
+        }
+        return mainClass != null;
+    }
+
+    /**
+     * Sets the {@code --manifest} option to the given value if that option was not already set.
+     *
+     * @param file path to the manifest file
+     * @param force whether to set the manifest even if already set
+     * @return whether the manifest has been set
+     */
+    boolean setManifest(Path file, boolean force) {
+        if (manifest == null || force) {
+            manifest = file;
+            return true;
+        }
+        return false;
+    }
+
+    /**
+     * Merges the manifest of this module with the manifest specified in plugin configuration.
+     * If both {@code file} and {@code content} are non-null, then {@code content} must be the
+     * result of reading {@code file}.
+     *
+     * <p>This method never modifies the given {@code content} object. If manifest are merged,
+     * a new {@link Manifest} instance is created. Therefore, caller can check whether this
+     * method returned a new instance as a way to recognize that a merge occurred.</p>
+     *
+     * <p>If a merge occurs, the content specified to {@link #setManifest(Path)} has precedence.
+     * It should be the {@code target/classes/META-INF/MANIFEST.MF} file (or modular equivalent).</p>
+     *
+     * @param  file     an additional manifest file, or {@code null}
+     * @param  content  the content of {@code file}, or a standalone manifest produced at runtime
+     * @return the merged manifest as a new instance if some changes were necessary
+     * @throws IOException if an error occurred while reading a manifest file
+     */
+    Manifest mergeManifest(Path file, Manifest content) throws IOException {
+        if (manifest == null) {
+            manifest = file;
+        } else if (file != null && Files.isSameFile(file, manifest)) {
+            // Nothing to merge because of the constraint that `content` must be the content of `file`.
+        } else {
+            try (InputStream in = Files.newInputStream(manifest)) {
+                // No need to wrap in `BufferedInputStream`.
+                if (content != null) {
+                    content = new Manifest(content);
+                    content.read(in);
+                } else {
+                    content = new Manifest(in);
+                }
+            }
+        }
+        return content;
+    }
+
+    /**
+     * Adds to the given list the arguments to provide to the "jar" tool for each version.
+     * Elements added to the list must be instances of {@link String} or {@link Path}.
+     * Callers should have added the following options (if applicable) before to invoke this method:
+     *
+     * <ul>
+     *   <li>{@code --create}</li>
+     *   <li>{@code --no-compress}</li>
+     *   <li>{@code --date} followed by the output time stamp</li>
+     *   <li>{@code --module-version} followed by module version</li>
+     *   <li>{@code --hash-modules} followed by patters of module names</li>
+     *   <li>{@code --module-path} followed by module path</li>
+     * </ul>
+     *
+     * This method adds the following options:
+     *
+     * <ul>
+     *   <li>{@code --file} followed by the path to the <abbr>JAR</abbr> file</li>
+     *   <li>{@code --manifest} followed by path to the manifest file</li>
+     *   <li>{@code --main-class} followed by fully qualified name class</li>
+     *   <li>{@code --release} followed by Java target release</li>
+     *   <li>{@code -C} followed by directory</li>
+     *   <li>files or directories to archive</li>
+     * </ul>
+     *
+     * @param addTo the list where to add the arguments as {@link String} or {@link Path} instances
+     */
+    void arguments(final List<Object> addTo) {
+        addTo.add("--file");
+        addTo.add(jarFile);
+        if (manifest != null) {
+            addTo.add("--manifest");
+            addTo.add(manifest);
+        }
+        if (mainClass != null) {
+            addTo.add("--main-class");
+            addTo.add(mainClass);
+        }
+        if (mavenFiles != null) {
+            addTo.add("-C");
+            addTo.addAll(mavenFiles);
+        }
+        for (Map.Entry<Runtime.Version, FileSet> entry : filesetForRelease.entrySet()) {
+            entry.getValue().arguments(addTo, entry.getKey());
+        }
+    }
+
+    /**
+     * Adds to the given list the arguments to provide to the "jar" tool for validating the <abbr>JAR</abbr> file.
+     * The file is validated only if requested or, in automatic mode, if the validation was not done implicitly at
+     * <abbr>JAR</abbr> creation time. Implicit validation happens if some {@code --release} options were used.
+     * If {@code true}, this method adds the following options:
+     *
+     * <ul>
+     *   <li>{@code --validate} operation mode</li>
+     *   <li>{@code --file} followed by the path to the <abbr>JAR</abbr> file</li>
+     * </ul>
+     *
+     * @param  validate whether to validate, or {@code null} for automatic based on heuristic rules
+     * @param  addTo the list to add the arguments as {@link String} or {@link Path} instances to
+     * @return whether a validation should be run

Review Comment:
   Renamed `writeValidateArguments`



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3804717172


##########
src/main/java/org/apache/maven/plugins/jar/AbstractJarMojo.java:
##########
@@ -18,44 +18,44 @@
  */
 package org.apache.maven.plugins.jar;
 
-import java.io.File;
 import java.io.IOException;
 import java.nio.file.Files;
 import java.nio.file.Path;
+import java.time.Instant;
 import java.util.Arrays;
+import java.util.List;
 import java.util.Map;
-import java.util.Objects;
-import java.util.jar.Attributes;
-import java.util.stream.Stream;
+import java.util.spi.ToolProvider;
 
+import org.apache.maven.api.PathScope;
 import org.apache.maven.api.ProducedArtifact;
 import org.apache.maven.api.Project;
 import org.apache.maven.api.Session;
+import org.apache.maven.api.Type;
 import org.apache.maven.api.di.Inject;
 import org.apache.maven.api.plugin.Log;
 import org.apache.maven.api.plugin.MojoException;
 import org.apache.maven.api.plugin.annotations.Parameter;
+import org.apache.maven.api.services.PathMatcherFactory;
 import org.apache.maven.api.services.ProjectManager;
 import org.apache.maven.shared.archiver.MavenArchiveConfiguration;
 import org.apache.maven.shared.archiver.MavenArchiver;
-import org.apache.maven.shared.archiver.MavenArchiverException;
-import org.apache.maven.shared.model.fileset.FileSet;
-import org.apache.maven.shared.model.fileset.util.FileSetManager;
-import org.codehaus.plexus.archiver.Archiver;
-import org.codehaus.plexus.archiver.jar.JarArchiver;
 
 /**
  * Base class for creating a <abbr>JAR</abbr> file from project classes.
  *
  * @author <a href="evenisse@apache.org">Emmanuel Venisse</a>
+ * @author Martin Desruisseaux
  */
 public abstract class AbstractJarMojo implements org.apache.maven.api.plugin.Mojo {
-
-    private static final String[] DEFAULT_EXCLUDES = new String[] {"**/package.html"};
-
-    private static final String[] DEFAULT_INCLUDES = new String[] {"**/**"};
-
-    private static final String MODULE_DESCRIPTOR_FILE_NAME = "module-info.class";
+    /**
+     * Identifier of the tool to use. This identifier shall match the identifier of a tool

Review Comment:
   Note: "shall" is the term used in international standards such as ISO for meaning that a requirement is mandatory. They explicitly ask us to not use "must". See for example [Shall, Should, Can, May: What Does It Mean in ISO Standards?](https://www.assentriskmanagement.co.uk/shall-should-can-may-what-does-it-mean-in-iso-standards/)



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "jaikiran (via GitHub)" <gi...@apache.org>.
jaikiran commented on PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#issuecomment-5336812545

   I haven't followed this PR and came to know about this only through a mail in the OpenJDK mailing list. Just on the following part:
   
   > We may not be able to enable reproducible build at all with the jar tool at it stands today because the jar tool does not seem to be designed for an explicit enumeration of files to include. It seems to be designed for working on directories only, in which case the entry order may depend on the tool or the platform. 
   
   The JDK in recent times has tried to provide reproducibility in tools wherever feasible. If there are shortcomings in the `jar` tool that prevent reproducibility, then it would be good to bring those specific details in the core-libs-dev OpenJDK mailing list https://mail.openjdk.org/mail/lists/core-libs-dev.openjdk.org/ (a mailing list subscription is required to send/receive mails). It would be good to address any of those issues in the `jar` tool as much as feasible.
   


-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "ascheman (via GitHub)" <gi...@apache.org>.
ascheman commented on PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#issuecomment-5340038081

   > the `jar` tool does not seem to be designed for an explicit enumeration of files to include. It seems to be designed for working on directories only, in which case the entry order may depend on the tool or the platform.
   
   @desruisseaux, I dug into this, and I think the directory-based form is the way *out* here rather than a dead end — the tool's directory order is **not** platform-dependent. Since [JDK-8276764](https://bugs.openjdk.org/browse/JDK-8276764) (*"enable deterministic file content ordering for jar and jmod"*, in JDK 17), the `jar` tool **sorts entries by name** when handed a directory, independent of the filesystem's iteration order or file timestamps.
   
   Verified empirically — files created in a deliberately non-sorted order, then `jar -C dir .`:
   
   * macOS Temurin 17 & 21 and Linux Temurin 17 → **byte-identical, name-sorted** output every time.
   
   So handing a directory to the tool gives us **both** reproducible entry order **and** the intermediate directory entries (`com/`, `com/acme/`, …) — the ones @seregamorph reported missing, which break Spring Boot component scanning. Per-file enumeration is exactly what drops those directory entries; the directory form keeps them and lets the tool sort for us. This also sidesteps a post-generation rewrite of the JAR — the directory entries come straight from the tool, so the archive is correct as produced (no second read/rewrite pass, and nothing extra to keep reproducible).
   
   To make it concrete, I put together a branch on top of this PR — CI green on JDK 17 + 21 (full `-P run-its`, 3 OSes):
   
   **[`aschemaven/maven-jar-plugin` → `bugfix/508-preserve-directory-entries`](https://github.com/aschemaven/maven-jar-plugin/tree/bugfix/508-preserve-directory-entries)**
   
   * **Plain JARs** — hand the whole directory to the tool when unfiltered (base, non-modular, no physical `MANIFEST.MF`) instead of enumerating files. Fixes the missing-directory-entries regression. IT: `directory-entries`.
   * **Non-modular multi-release** — declare resource directories to the tool even in reproducible mode (the JDK 19+ tool sorts each, JDK-8276764), so base and versioned areas keep their directory entries. IT: `directory-entries-mr`.
   
   Include/exclude filters and modular archives still fall back to per-file enumeration (they need it); that's documented in the code.
   
   It's meant as a starting point — cherry-pick or adapt as you see fit; I didn't want to push commits onto your PR. Happy to open it as a PR against this branch if that's easier to review. And if any genuine `jar`-tool reproducibility gaps remain, @jaikiran's offer to take specifics to core-libs-dev is the right venue — but for entry ordering the tool already does what we need.
   


-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "ascheman (via GitHub)" <gi...@apache.org>.
ascheman commented on PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#issuecomment-5340097189

   @seregamorph — since you have the exact Spring Boot 4.1.0 reproduction, would you be willing to try the branch against your real sources? **Commit 1 alone** should already cover your case (a plain, single-classes-directory app) — that's the one that restores the missing directory entries.
   
   To test:
   
   ```
   git fetch https://github.com/aschemaven/maven-jar-plugin.git bugfix/508-preserve-directory-entries
   git checkout FETCH_HEAD
   mvn -DskipTests install        # builds & installs 4.0.0-beta-2-SNAPSHOT into your local repo (JDK 17+)
   ```
   
   Then rebuild your project (it already resolves `4.0.0-beta-2-SNAPSHOT`) and check that:
   
   * the Spring Boot application starts, and
   * `jar -tf <your-app>.jar` shows the `com/…` directory entries again.
   
   It would be great to confirm it resolves the blocker on real sources. The full `-P run-its` suite is green on JDK 17 + 21 with this change, but your application is the case that actually matters here.
   


-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3891941360


##########
src/main/java/org/apache/maven/plugins/jar/Archive.java:
##########
@@ -0,0 +1,692 @@
+/*
+ * 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.jar;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.TreeMap;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.Type;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.MojoException;
+
+/**
+ * Files or root directories to archive for a single module.
+ * A single instance of {@code Archive} may contain many directories for different target Java releases.
+ * Many instances of {@code Archive} may exist when archiving a multi-modules project.
+ */
+final class Archive {
+    /**
+     * Whether to repeat the {@code -C} option before each file.
+     * Doing so makes the command-line very verbose while the documentation of
+     * <a href="https://docs.oracle.com/en/java/javase/25/docs/specs/man/jar.html">The jar Command</a>
+     * gives the impression that this option can be provided only once.
+     * However, our tests suggest that the first file after the directory specified by the {@code -C} option
+     * must be relative to that directory and all files after the first one must be prefixed by the directory
+     * which was specified in the {@code -C} option. This behavior is not documented, but we couldn't get the
+     * {@code jar} tool to work otherwise (except by repeating {@code -C} before each file).
+     * Furthermore, it seems that the relativized file needs to be the shortest one,
+     * otherwise the {@code jar} tool rejects files after the first one with "names do not match".
+     * Which file is first depends on the unspecified directory-iteration order.
+     *
+     * <p>If this flag is {@code true}, the plugin repeats {@code -C} before each file.
+     * This flag should be set to {@code false} if a future version of the {@code jar}
+     * tool allows to specify {@code -C} only once.</p>
+     *
+     * <p><b>Historical note:</b> we also tried to relativize only the first file after {@code -C}
+     * and keep all subsequent files as absolute. It works, but because we have to repeat the directory
+     * in the file name, it saves only 3 or 4 characters per file compared to repeating {@code -C}.</p>
+     */
+    private static final boolean REPEAT_C = true;
+
+    /**
+     * Path to the <abbr>POM</abbr> file generated for this archive, or {@code null} if none.
+     * This is non-null only if module source hierarchy is used, in which case the dependencies
+     * declared in this file are the intersection of the project dependencies and the content of
+     * the {@code module-info.class} file.
+     */
+    @Nullable
+    Path pomFile;
+
+    /**
+     * The <var>JAR</var> file to create. May be an existing file,
+     * in which case the file creation may be skipped if the file is still up-to-date.
+     */
+    @Nonnull
+    final Path jarFile;
+
+    /**
+     * A helper class for checking whether an existing <abbr>JAR</abbr> file is still up-to-date.
+     * This is null if there is no existing JAR file, or if we determined that the file is outdated.
+     */
+    private TimestampCheck existingJAR;
+
+    /**
+     * Name of the module being archived when the project is using module hierarchy.
+     * This is {@code null} if the project is using package hierarchy, either because it is a classical
+     * class-path project or because it is a single module compiled without using the module hierarchy.
+     * When using module source hierarchy, {@code javac} guarantees that the module name in the output
+     * directory is the name of the parent directory of {@code module-info.class}.
+     */
+    @Nullable
+    final String moduleName;
+
+    /**
+     * Path to {@code META-INF/MANIFEST.MF}, or {@code null} if none.
+     * If non-null, this value will be given to the {@code --manifest} option.
+     * The use of this option is preferable to adding {@code MANIFEST.MF} as an ordinary file.
+     *
+     * @see #setManifest(Path, boolean)
+     * @see #mergeManifest(Path, Manifest)
+     */
+    @Nullable
+    private Path manifest;
+
+    /**
+     * The Maven generated {@code pom.xml} and {@code pom.properties} files, or {@code null} if none.
+     * This first item shall be the base directory where the files are located.
+     */
+    @Nullable
+    List<Path> mavenFiles;
+
+    /**
+     * Fully-qualified name of the main class, or {@code null} if none.
+     * This is the value to provide to the {@code --main-class} option.
+     */
+    private String mainClass;
+
+    /**
+     * Files or root directories to store in the <abbr>JAR</abbr> file for each target Java release
+     * other than the base release. Keys are the target Java release with {@code null} for the base
+     * release.
+     */
+    @Nonnull
+    private final NavigableMap<Runtime.Version, FileSet> filesetForRelease;
+
+    /**
+     * Files or root directories to archive for a single target Java release of a single module.
+     * The {@link Archive} enclosing shall contain at least one instance of {@code FileSet} for
+     * the base release, and an arbitrary amount of other instances for other target releases.
+     */
+    final class FileSet {
+        /**
+         * A comparator for sorting paths in a reproducible order.
+         * This comparator assumes that all paths are relative to the same base directory (this is not verified).
+         * Note: we do not use {@link Path#compareTo(Path)} because the Javadoc said that it is platform dependent.
+         */
+        private static final Comparator<Path> REPRODUCIBLE_ORDER = (p1, p2) -> {
+            final int c1 = p1.getNameCount();
+            final int c2 = p2.getNameCount();
+            final int c = Math.min(c1, c2);
+            for (int i = 0; i < c; i++) {
+                String n1 = p1.getName(i).toString();
+                String n2 = p2.getName(i).toString();
+                int r = n1.compareTo(n2); // Case-sensitive comparison on all platforms.
+                if (r != 0) {
+                    return r;
+                }
+            }
+            return c1 - c2;
+        };
+
+        /**
+         * The root directory of all files or directories to archive.
+         * This is the value to pass to the {@code -C} tool option.
+         */
+        @Nonnull
+        final Path directory;
+
+        /**
+         * The files or directories to include in the <var>JAR</var> file.
+         * May be absolute paths or paths relative to {@link #directory}.
+         */
+        @Nonnull
+        final List<Path> files;
+
+        /**
+         * Creates an initially empty set of files or directories for a specific target Java release.
+         *
+         * @param directory the base directory of the files or directories to archive
+         */
+        private FileSet(Path directory) {
+            this.directory = directory;
+            this.files = new ArrayList<>();
+        }
+
+        /**
+         * 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.
+         * The caller should use that common directory for logging a warning message.
+         *
+         * @param base base directory found by previous invocations of this method, or {@code null} if none
+         * @return common directory of discarded files
+         */
+        private Path discardAllFiles(Path base) {
+            for (Path file : files) {
+                file = directory.resolve(file);
+                if (base == null) {
+                    base = file.getParent();
+                } else {
+                    while (!file.startsWith(base)) {
+                        base = base.getParent();
+                        if (base == null) {
+                            break;
+                        }
+                    }
+                }
+            }
+            files.clear();
+            return base;
+        }
+
+        /**
+         * Adds the given path to the list of files or directories to archive.
+         * This method may store a relative path instead of the absolute path.
+         *
+         * @param item a file or directory to archive
+         * @param attributes the file's basic attributes
+         * @param isDirectory whether the file is a directory
+         * @throws IllegalArgumentException if the given path cannot be made relative to the base directory
+         */
+        void add(Path item, BasicFileAttributes attributes, boolean isDirectory) {
+            TimestampCheck tc = existingJAR;
+            if (tc != null && tc.isUpdated(item, attributes, isDirectory)) {
+                existingJAR = null; // Signal that the existing file is outdated.
+            }
+            item = directory.relativize(item);
+            if (item.getNameCount() <= 1 && item.toString().isEmpty()) {
+                /*
+                 * The item is the `-C` directory itself (e.g. a `META-INF/versions/<n>` directory
+                 * added as a whole). An empty file argument is invalid for the `jar` tool
+                 * (some implementations reject it, others silently misbehave),
+                 * so archive the whole directory content with ".".
+                 */
+                item = Path.of(".");
+            }
+            files.add(item);
+        }
+
+        /**
+         * Adds to the given list the arguments to provide to the "jar" tool for this version.
+         * Elements added to the list shall be instances of {@link String} or {@link Path}.
+         *
+         * @param addTo the list where to add the arguments as {@link String} or {@link Path} instances
+         * @param version the target Java release, or {@code null} for the base version of the <abbr>JAR</abbr> file
+         */
+        private void arguments(List<Object> addTo, Runtime.Version version) {
+            if (!files.isEmpty()) {
+                if (version != null) {
+                    addTo.add("--release");
+                    addTo.add(version);
+                }
+                if (isReproducible) {
+                    files.sort(REPRODUCIBLE_ORDER);
+                }
+                if (REPEAT_C) {
+                    for (Path file : files) {
+                        addTo.add("-C");
+                        addTo.add(directory);
+                        addTo.add(file);
+                    }
+                } else {
+                    addTo.add("-C");
+                    addTo.add(directory);
+                    addTo.addAll(files);
+                }
+            }
+        }
+
+        /**
+         * {@return a string representation for debugging purposes}
+         */
+        @Override
+        public String toString() {
+            return getClass().getSimpleName() + '[' + directory.getFileName() + ": " + files.size() + " files]";
+        }
+    }
+
+    /**
+     * Whether reproducible build was requested.
+     */
+    private final boolean isReproducible;
+
+    /**
+     * Creates an initially empty set of files or directories.
+     *
+     * @param jarFile path to the <abbr>JAR</abbr> file to create
+     * @param moduleName the module name if using module hierarchy, or {@code null} if using package hierarchy
+     * @param version the target Java release, or {@code null} for the base version
+     * @param directory the directory of the classes targeting the base Java release
+     * @param forceCreation whether to force a new <abbr>JAR</abbr> file even if the content seems unchanged
+     * @param isReproducible whether reproducible build was requested
+     * @param logger where to send a warning if an error occurred while checking an existing <abbr>JAR</abbr> file
+     */
+    @SuppressWarnings("checkstyle:NeedBraces")
+    Archive(
+            final Path jarFile,
+            final String moduleName,
+            final Runtime.Version version,
+            final Path directory,
+            final boolean forceCreation,
+            final boolean isReproducible,
+            final Log logger) {
+        this.jarFile = jarFile;
+        this.moduleName = moduleName;
+        this.isReproducible = isReproducible;
+        filesetForRelease = new TreeMap<>((v1, v2) -> {
+            if (v1 == v2) return 0;
+            if (v1 == null) return -1;
+            if (v2 == null) return +1;
+            return v1.compareTo(v2);
+        });
+        filesetForRelease.put(version, new FileSet(directory));
+        if (!forceCreation && Files.isRegularFile(jarFile)) {
+            try {
+                existingJAR = new TimestampCheck(jarFile, directory, logger);
+            } catch (IOException e) {
+                // Ignore, we will regenerate the JAR file.
+                logger.warn(e);
+            }
+        }
+    }
+
+    /**
+     * {@return the files or directories to store in the <abbr>JAR</abbr> file for targeting the base Java release}
+     *
+     * @throws NoSuchElementException should not happen unless {@link #prune(boolean)} has been invoked
+     */
+    FileSet baseRelease() {
+        Map.Entry<Runtime.Version, FileSet> entry = filesetForRelease.firstEntry();
+        String message = null;
+        if (entry != null) {
+            Runtime.Version version = entry.getKey();
+            if (version == null) {
+                return entry.getValue();
+            }
+            message = "Expected base version but found version " + version;
+        }
+        throw new NoSuchElementException(message);
+    }
+
+    /**
+     * Returns the {@code module-info.class} files. Conceptually, there is at most once such file per module.
+     * However, more than one file may exist if additional files are provided for additional Java releases.
+     * This method returns only the files that exist.
+     *
+     * @return all {@code module-info.class} files found for all target Java releases
+     */
+    public List<Path> moduleInfoFiles() {
+        var files = new ArrayList<Path>();
+        filesetForRelease.values().forEach((release) -> {
+            Path file = release.directory.resolve(FileCollector.MODULE_DESCRIPTOR_FILE_NAME);
+            if (Files.isRegularFile(file)) {
+                files.add(file);
+            }
+        });
+        return files;
+    }
+
+    /**
+     * Discards all files in this archive, normally because those files are not in any module.
+     * This method returns a common parent directory for all the files that were discarded.
+     * The caller should use that common directory for logging a warning message.
+     *
+     * @return common directory of discarded files, or {@code null} if none
+     */
+    Path discardAllFiles() {
+        Path base = null;
+        for (FileSet release : filesetForRelease.values()) {
+            base = release.discardAllFiles(base);
+        }
+        filesetForRelease.clear();
+        return base;
+    }
+
+    /**
+     * Removes all empty file sets 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}, then this method ensures that at least one file set
+     * remains even if that file set is empty.
+     *
+     * @param skipIfEmpty value of {@link AbstractJarMojo#skipIfEmpty}
+     */
+    public void prune(final boolean skipIfEmpty) {
+        FileSet keep = (skipIfEmpty || isEmpty())
+                ? null
+                : filesetForRelease.firstEntry().getValue();
+        filesetForRelease.values().removeIf((fs) -> fs.files.isEmpty());
+        Iterator<Map.Entry<Runtime.Version, FileSet>> it =
+                filesetForRelease.entrySet().iterator();
+        if (it.hasNext()) {
+            Map.Entry<Runtime.Version, FileSet> first = it.next();
+            if (first.getKey() == null) {
+                return; // Already contains an entry for the base version, nothing to do.
+            }
+            keep = first.getValue();
+            it.remove();
+        }
+        if (keep != null) {
+            filesetForRelease.put(null, keep);
+        }
+    }
+
+    /**
+     * {@return whether this archive has nothing to archive}
+     * Note that this method may return {@code false} even when there is zero file to archive.
+     * It may happen if {@link AbstractJarMojo#skipIfEmpty} is {@code false}. In such case, the
+     * "empty" <abbr>JAR</abbr> file will still contain at {@code META-INF/MANIFEST.MF} file.
+     *
+     * <h4>Prerequisites</h4>
+     * The {@link #prune(boolean)} method should be invoked before this method for accurate result.
+     */
+    public boolean isEmpty() {
+        return filesetForRelease.isEmpty();
+    }
+
+    /**
+     * Checks whether the <abbr>JAR</abbr> file already exists and can be reused.
+     * This method verifies that the <abbr>JAR</abbr> file contains all the files to archive,
+     * contains no extra file, and no file to archive is newer than the <abbr>JAR</abbr> file.
+     *
+     * <p>This method can be invoked only once.
+     * If invoked more often, it returns {@code false} on all subsequent invocations.</p>
+     *
+     * @return whether the <abbr>JAR</abbr> file already exists and can be reused
+     */
+    public boolean isUpToDateJAR() {
+        final TimestampCheck tc = existingJAR;
+        if (tc == null) {
+            return false;
+        }
+        existingJAR = null; // Let GC do its job.
+        return tc.isUpToDateJAR(filesetForRelease.values());
+    }
+
+    /**
+     * Returns an initially empty set of files or directories for the specified target Java release.
+     *
+     * @param directory the base directory of the files to archive
+     * @param version the target Java release, or {@code null} for the base version
+     * @return container where to declare files and directories to archive
+     */
+    FileSet newTargetRelease(Path directory, Runtime.Version version) {
+        return filesetForRelease.computeIfAbsent(version, (key) -> new FileSet(directory));
+    }
+
+    /**
+     * Sets the {@code --main-class} option to the value of the {@code Main-Class} entry of the given manifest.
+     * As an extension, this method accepts the {@code module/classname} syntax (a syntax already used in some
+     * Java tools). If a module is specified, the main class is kept only if the module match. The intent is to
+     * allow users to specify on which module the main class applies when they use plugin configuration.
+     *
+     * <p>This method may modify the {@code content} manifest. Caller shall ensure that the given manifest
+     * is not a shared instance. This method returns whether a change has actually been done.</p>
+     *
+     * @param content combination of existing {@code MANIFEST.MF} and manifest inferred from configuration, or null
+     * @return whether the given manifest has been modified by this method
+     */
+    boolean setMainClass(Manifest content) {
+        if (content == null || mainClass != null) {
+            return false;
+        }
+        // We need to remove the attribute, otherwise it will conflict with `--main-class`.
+        mainClass = (String) content.getMainAttributes().remove(Attributes.Name.MAIN_CLASS);
+        if (mainClass != null) {
+            int s = mainClass.indexOf('/');
+            if (s >= 0) {
+                if (mainClass.substring(0, s).strip().equals(moduleName)) {
+                    mainClass = mainClass.substring(s + 1).strip();
+                } else {
+                    mainClass = null; // Main class is defined for another module.
+                }
+            }
+        }
+        return mainClass != null;
+    }
+
+    /**
+     * Sets the {@code --manifest} option to the given value if that option was not already set.
+     *
+     * @param file path to the manifest file
+     * @param force whether to set the manifest even if already set
+     * @return whether the manifest has been set
+     */
+    boolean setManifest(Path file, boolean force) {
+        if (manifest == null || force) {
+            manifest = file;
+            return true;
+        }
+        return false;
+    }
+
+    /**
+     * Merges the manifest of this module with the manifest specified in plugin configuration.
+     * If both {@code file} and {@code content} are non-null, then {@code content} must be the
+     * result of reading {@code file}.
+     *
+     * <p>This method never modifies the given {@code content} object. If manifest are merged,
+     * a new {@link Manifest} instance is created. Therefore, caller can check whether this
+     * method returned a new instance as a way to recognize that a merge occurred.</p>
+     *
+     * <p>If a merge occurs, the content specified to {@link #setManifest(Path)} has precedence.
+     * It should be the {@code target/classes/META-INF/MANIFEST.MF} file (or modular equivalent).</p>
+     *
+     * @param  file     an additional manifest file, or {@code null}
+     * @param  content  the content of {@code file}, or a standalone manifest produced at runtime
+     * @return the merged manifest as a new instance if some changes were necessary
+     * @throws IOException if an error occurred while reading a manifest file
+     */
+    Manifest mergeManifest(Path file, Manifest content) throws IOException {
+        if (manifest == null) {
+            manifest = file;
+        } else if (file != null && Files.isSameFile(file, manifest)) {
+            // Nothing to merge because of the constraint that `content` must be the content of `file`.
+        } else {
+            try (InputStream in = Files.newInputStream(manifest)) {
+                // No need to wrap in `BufferedInputStream`.
+                if (content != null) {
+                    content = new Manifest(content);
+                    content.read(in);
+                } else {
+                    content = new Manifest(in);
+                }
+            }
+        }
+        return content;
+    }
+
+    /**
+     * Adds to the given list the arguments to provide to the "jar" tool for each version.
+     * Elements added to the list shall be instances of {@link String} or {@link Path}.
+     * Callers should have added the following options (if applicable) before to invoke this method:
+     *
+     * <ul>
+     *   <li>{@code --create}</li>
+     *   <li>{@code --no-compress}</li>
+     *   <li>{@code --date} followed by the output time stamp</li>
+     *   <li>{@code --module-version} followed by module version</li>
+     *   <li>{@code --hash-modules} followed by patters of module names</li>
+     *   <li>{@code --module-path} followed by module path</li>
+     * </ul>
+     *
+     * This method adds the following options:
+     *
+     * <ul>
+     *   <li>{@code --file} followed by the path to the <abbr>JAR</abbr> file</li>
+     *   <li>{@code --manifest} followed by path to the manifest file</li>
+     *   <li>{@code --main-class} followed by fully qualified name class</li>
+     *   <li>{@code --release} followed by Java target release</li>
+     *   <li>{@code -C} followed by directory</li>
+     *   <li>files or directories to archive</li>
+     * </ul>
+     *
+     * @param addTo the list where to add the arguments as {@link String} or {@link Path} instances
+     */
+    void arguments(final List<Object> addTo) {
+        addTo.add("--file");
+        addTo.add(jarFile);
+        if (manifest != null) {
+            addTo.add("--manifest");
+            addTo.add(manifest);
+        }
+        if (mainClass != null) {
+            addTo.add("--main-class");
+            addTo.add(mainClass);
+        }
+        if (mavenFiles != null) {
+            addTo.add("-C");
+            addTo.addAll(mavenFiles);
+        }
+        for (Map.Entry<Runtime.Version, FileSet> entry : filesetForRelease.entrySet()) {
+            entry.getValue().arguments(addTo, entry.getKey());
+        }
+    }
+
+    /**
+     * Adds to the given list the arguments to provide to the "jar" tool for validating the <abbr>JAR</abbr> file.

Review Comment:
   If we do not said "to the given list", the natural assumption is that it adds to `this`.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3892071566


##########
src/main/java/org/apache/maven/plugins/jar/PomDerivation.java:
##########
@@ -0,0 +1,525 @@
+/*
+ * 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.jar;
+
+import javax.xml.stream.XMLStreamException;
+
+import java.io.BufferedInputStream;
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.UncheckedIOException;
+import java.lang.module.ModuleDescriptor;
+import java.lang.module.ModuleFinder;
+import java.lang.module.ModuleReference;
+import java.net.URI;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.DependencyCoordinates;
+import org.apache.maven.api.JavaPathType;
+import org.apache.maven.api.Session;
+import org.apache.maven.api.Type;
+import org.apache.maven.api.model.Dependency;
+import org.apache.maven.api.model.Model;
+import org.apache.maven.api.model.Parent;
+import org.apache.maven.api.plugin.MojoException;
+import org.apache.maven.api.services.DependencyCoordinatesFactory;
+import org.apache.maven.api.services.DependencyCoordinatesFactoryRequest;
+import org.apache.maven.api.services.DependencyResolver;
+import org.apache.maven.api.services.DependencyResolverRequest;
+import org.apache.maven.api.services.DependencyResolverResult;
+import org.apache.maven.api.services.ModelBuilderException;
+import org.apache.maven.model.v4.MavenStaxWriter;
+
+/**
+ * A mapper from Maven model dependencies to Java module names.
+ * A single instance of this class is created for a Maven project,
+ * then shared by all {@link ForModule} instances (one per module to archive).
+ */
+final class PomDerivation {
+    /**
+     * Whether to expand the list of transitive dependencies in the generated <abbr>POM</abbr>.
+     */
+    private static final boolean EXPAND_TRANSITIVE = false;
+
+    /**
+     * Copy of {@link AbstractJarMojo#session}.
+     */
+    private final Session session;
+
+    /**
+     * The project model, which includes dependencies of all modules.
+     */
+    private final Model projectModel;
+
+    /**
+     * The factory to use for creating temporary {@link DependencyCoordinates} instances.
+     */
+    private final DependencyCoordinatesFactory coordinateFactory;
+
+    /**
+     * Provide module descriptors from module names.
+     * May be {@code null} if no {@code module-info} was found.
+     */
+    private final ModuleFinder moduleFinder;
+
+    /**
+     * Module references from paths to the <abbr>JAR</abbr> file or root directory.
+     */
+    private final Map<URI, ModuleReference> fromURI;
+
+    /**
+     * Module names associated to Maven dependencies.
+     * This map contains {@link DependencyCoordinates#getId()} as keys and module references as values.
+     * This is used for detecting which dependencies are really used according {@code module-info.class}.
+     *
+     * @todo The keys should be instances of {@link DependencyCoordinates}. Unfortunately, as of Maven 4.0.0-rc-5
+     *       that interface does not define the {@code equals} and {@code hashCode} contracts.
+     */
+    private final Map<String, ModuleReference> fromDependency;
+
+    /**
+     * Modules that are built by the project. Keys are module names.
+     */
+    private final Map<String, Dependency> builtModules;
+
+    /**
+     * Creates a new mapper from Maven dependency to module name.
+     *
+     * @param mojo the enclosing <abbr>MOJO</abbr>
+     * @param moduleRoots paths to root directories of each module to archive in a module hierarchy
+     * @throws IOException if an I/O error occurred while fetching dependencies
+     * @throws MavenException if an error occurred while fetching dependencies for a reason other than I/O.
+     */
+    PomDerivation(final AbstractJarMojo mojo, final List<Path> moduleRoots) throws IOException {
+        this.session = mojo.session;
+        projectModel = mojo.project.getModel();
+        coordinateFactory = session.getService(DependencyCoordinatesFactory.class);
+        DependencyResolver resolver = session.getService(DependencyResolver.class);
+        DependencyResolverResult result = resolver.resolve(DependencyResolverRequest.builder()
+                .session(session)
+                .project(mojo.project)
+                .requestType(DependencyResolverRequest.RequestType.RESOLVE)
+                .pathScope(mojo.getDependencyScope())
+                .pathTypeFilter(Set.of(JavaPathType.MODULES, JavaPathType.CLASSES))
+                .build());
+
+        rethrow(result);
+        final Map<org.apache.maven.api.Dependency, Path> dependencies = result.getDependencies();
+        final Path[] allModulePaths = toRealPaths(moduleRoots, dependencies.values());
+        fromURI = new HashMap<>(allModulePaths.length); // TODO: use newHashMap with JDK19.
+        moduleFinder = ModuleFinder.of(allModulePaths);
+        if (moduleFinder != null) {
+            for (ModuleReference reference : moduleFinder.findAll()) {
+                reference.location().ifPresent((location) -> fromURI.put(location, reference));
+            }
+        }
+        fromDependency = new HashMap<>(dependencies.size()); // TODO: use newHashMap with JDK19.
+        for (Map.Entry<org.apache.maven.api.Dependency, Path> entry : dependencies.entrySet()) {
+            Path modulePath = entry.getValue().toRealPath();
+            ModuleReference reference = fromURI.get(modulePath.toUri());
+            if (reference != null) {
+                DependencyCoordinates coordinates = entry.getKey().toCoordinates();
+                String id = coordinates.getId();
+                ModuleReference old = fromDependency.putIfAbsent(id, reference);
+                if (old == null) {
+                    coordinates = withoutVersion(coordinates);
+                    id = coordinates.getId();
+                    old = fromDependency.putIfAbsent(id, reference);
+                }
+                if (old != null && !old.equals(reference)) {
+                    mojo.log.warn("The \"" + id + "\" dependency is declared twice with different module names: \""
+                            + old.descriptor().name() + "\" and \""
+                            + reference.descriptor().name() + "\".");
+                }
+            }
+        }
+        builtModules = new HashMap<>(moduleRoots.size()); // TODO: use newHashMap with JDK19.
+        for (Path root : moduleRoots) {
+            ModuleDescriptor descriptor = fromURI.get(root.toUri()).descriptor();
+            builtModules.put(
+                    descriptor.name(),
+                    Dependency.newBuilder()
+                            .groupId(projectModel.getGroupId())
+                            .artifactId(descriptor.name())
+                            .version(projectModel.getVersion())
+                            .type(Type.MODULAR_JAR)
+                            .build());
+        }
+    }
+
+    /**
+     * Rebuilds the given dependency coordinates without version.
+     *
+     * Note: I'm not sure if it is necessary. This is done in case version numbers are not resolved
+     * in the dependencies of the model returned by {@code Project.getModel()}, or are not resolved
+     * in the same way as what we get from {@link DependencyResolver}.
+     */
+    private DependencyCoordinates withoutVersion(DependencyCoordinates coordinates) {
+        return coordinateFactory.create(DependencyCoordinatesFactoryRequest.builder()
+                .session(session)
+                .groupId(coordinates.getGroupId())
+                .artifactId(coordinates.getArtifactId())
+                .extension(coordinates.getExtension())
+                .classifier(coordinates.getClassifier())
+                .build());
+    }
+
+    /**
+     * If the resolver failed, propagates its exception.
+     *
+     * @param result the resolver result
+     * @throws IOException if the result contains an I/O error
+     */
+    private static void rethrow(DependencyResolverResult result) throws IOException {
+        Exception exception = null;
+        for (Exception cause : result.getExceptions()) {
+            if (cause instanceof UncheckedIOException e) {
+                cause = e.getCause();
+            }
+            if (exception != null) {
+                exception.addSuppressed(cause);
+            } else if (cause instanceof RuntimeException || cause instanceof IOException) {
+                exception = cause;
+            } else {
+                exception = new MojoException("Cannot collect the runtime dependencies.", cause);
+            }
+        }
+        if (exception != null) {
+            if (exception instanceof IOException e) {
+                throw e;
+            } else {
+                throw (RuntimeException) exception; // A ClassCastException here would be a bug in above loop.
+            }
+        }
+    }
+
+    /**
+     * Returns the real paths of the given collections, in iteration order and without duplicated values.
+     */
+    private static Path[] toRealPaths(Collection<Path> moduleRoots, Collection<Path> dependencies) throws IOException {
+        // TODO: use newLinkedHashSet(int) after we are allowed to compile for JDK19.
+        final var paths = new LinkedHashSet<Path>(moduleRoots.size() + dependencies.size());
+        for (Path path : moduleRoots) {
+            paths.add(path.toRealPath());
+        }
+        for (Path path : dependencies) {
+            paths.add(path.toRealPath());
+        }
+        return paths.toArray(Path[]::new);
+    }
+
+    /**
+     * Returns the module descriptor for the {@code module-info.class} at the given path.
+     *
+     * @param moduleInfo path to a {@code module-info.class} file
+     * @return module descriptor for the specified file
+     * @throws IOException if an error occurred while reading the file
+     */
+    private ModuleDescriptor findModuleDescriptor(Path moduleInfo) throws IOException {
+        Path directory = moduleInfo.toRealPath().getParent();
+        ModuleReference reference = fromURI.get(directory.toUri());
+        if (reference != null) {
+            return reference.descriptor();
+        }
+        try (InputStream in = new BufferedInputStream(Files.newInputStream(moduleInfo))) {
+            return ModuleDescriptor.read(in);
+        }
+    }
+
+    /**
+     * Returns the module descriptor for the specified Maven dependency.
+     *
+     * @param dependency dependency for which to get the module descriptor
+     * @return Java module descriptor for the given Maven dependency
+     */
+    private Optional<ModuleDescriptor> findModuleDescriptor(Dependency dependency) {
+        DependencyCoordinates coordinates = coordinateFactory.create(session, dependency);
+        ModuleReference reference = fromDependency.get(coordinates.getId());
+        if (reference == null) {
+            coordinates = withoutVersion(coordinates);
+            reference = fromDependency.get(coordinates.getId());
+            if (reference == null) {
+                return Optional.empty();
+            }
+        }
+        return Optional.of(reference.descriptor());
+    }
+
+    /**
+     * Returns the module descriptor for the specified module name.
+     *
+     * @param moduleName name of the module for which to get the descriptor
+     * @return module descriptor for the specified module name
+     */
+    private Optional<ModuleDescriptor> findModuleDescriptor(String moduleName) {
+        if (moduleFinder == null) {
+            return Optional.empty();
+        }
+        return moduleFinder.find(moduleName).map(ModuleReference::descriptor);
+    }
+
+    /**
+     * Derives a <abbr>POM</abbr> as the intersection of the consumer <abbr>POM</abbr>
+     * and the dependencies required by {@code module-info}.
+     */
+    final class ForModule {
+        /**
+         * Value of the {@code <name>} element in the derived <abbr>POM</abbr>, or {@code null} if none.
+         */
+        private String name;
+
+        /**
+         * Name of the module for which to derive a <abbr>POM</abbr> file.
+         */
+        private final String moduleName;
+
+        /**
+         * Whether a dependency is optional or required only at runtime.
+         */
+        private enum Modifier {
+            OPTIONAL,
+            RUNTIME
+        }
+
+        /**
+         * The required dependencies as Java module names, including transitive dependencies.
+         * Values tell whether the dependency is optional or should have runtime scope.
+         */
+        private final Map<String, EnumSet<Modifier>> requires;
+
+        /**
+         * Path to the <abbr>POM</abbr> file written by this class.
+         */
+        final Path pomFile;
+
+        /**
+         * Creates a new <abbr>POM</abbr> generator for the given archive.
+         *
+         * @param archive the archive for which to generate a <abbr>POM</abbr>
+         * @param manifest manifest to use for deriving project name, or {@code null} if none
+         * @throws IOException if an error occurred while reading the {@code module-info.class} file
+         */
+        ForModule(final Archive archive, final Manifest manifest) throws IOException {
+            moduleName = archive.moduleName;
+            pomFile = derivePathToPOM(archive.jarFile);
+            requires = new LinkedHashMap<>();
+            for (Path file : archive.moduleInfoFiles()) {
+                addDependencies(findModuleDescriptor(file), EnumSet.noneOf(Modifier.class));
+            }
+            if (manifest != null) {
+                name = (String) manifest.getMainAttributes().get(Attributes.Name.IMPLEMENTATION_TITLE);
+                if (name == null) {
+                    name = (String) manifest.getMainAttributes().get(Attributes.Name.SPECIFICATION_TITLE);
+                }
+            }
+        }
+
+        /**
+         * Add the dependencies of the given module, including transitive dependencies.
+         * If the same dependency is added twice with different optional flags,
+         * the {@code false} value (i.e., mandatory dependency) has precedence.
+         *
+         * @param descriptor description of the module for which to add dependencies
+         * @param parentModifiers modifiers of the parent module for which this method adds dependencies
+         */
+        private void addDependencies(final ModuleDescriptor descriptor, final EnumSet<Modifier> parentModifiers) {
+            for (ModuleDescriptor.Requires r : descriptor.requires()) {
+                final EnumSet<Modifier> modifiers = parentModifiers.clone();
+                if (r.modifiers().contains(ModuleDescriptor.Requires.Modifier.STATIC)) {
+                    modifiers.add(Modifier.OPTIONAL);
+                }
+                if (!r.modifiers().contains(ModuleDescriptor.Requires.Modifier.TRANSITIVE)) {
+                    modifiers.add(Modifier.RUNTIME);
+                }
+                EnumSet<Modifier> current = requires.computeIfAbsent(r.name(), (key) -> modifiers);
+                if (EXPAND_TRANSITIVE && (current == modifiers || current.retainAll(modifiers))) {
+                    // Transitive dependencies if not already added or if it needs to update modifiers.
+                    findModuleDescriptor(r.name()).ifPresent((td) -> addDependencies(td, modifiers));
+                }
+            }
+        }
+
+        /**
+         * Derives a <abbr>POM</abbr> file for the archive specified ad construction time.
+         *
+         * @throws IOException if an error occurred while writing the <abbr>POM</abbr> file
+         *
+         * @see #writeParentPOM(Archive)
+         */
+        void writeModulePOM() throws IOException {
+            try {
+                writePOM(deriveModulePOM(), pomFile);
+            } catch (ModelBuilderException | XMLStreamException e) {
+                throw new MojoException("Cannot derive a POM file for the \"" + moduleName + "\" module.", e);
+            }
+        }
+
+        /**
+         * Derives the module <abbr>POM</abbr> file as the intersection of the project <abbr>POM</abbr> and the archive.
+         *
+         * @return intersection of {@link #projectModel} and {@code module-info.class}
+         * @throws ModelBuilderException if an error occurred while building the model
+         */
+        private Model deriveModulePOM() throws ModelBuilderException {
+            Model.Builder builder = Model.newBuilder()
+                    .modelVersion("4.0.0")
+                    .groupId(projectModel.getGroupId())
+                    .artifactId(moduleName)
+                    .version(projectModel.getVersion())
+                    .parent(Parent.newBuilder()
+                            .groupId(projectModel.getGroupId())
+                            .artifactId(projectModel.getArtifactId())
+                            .version(projectModel.getVersion())
+                            .build());
+            if (name != null) {
+                builder = builder.name(name);
+            }
+            /*
+             * Filter the dependencies by keeping only the one declared in a `requires` statement of the
+             * `module-info.class` of the module that we are archiving. Also adjust the `<optional>` and
+             * `<scope>` values. The dependencies that we found are removed from the `requires` map as a
+             * way to make sure that we do not add them twice. In principle, the map should become empty
+             * at the end of this loop.
+             */
+            final List<Dependency> dependencies = projectModel.getDependencies();
+            if (dependencies != null) {
+                final var filteredDependencies = new ArrayList<Dependency>(dependencies.size());
+                for (var iterator = requires.entrySet().iterator(); iterator.hasNext(); ) {
+                    Map.Entry<String, EnumSet<Modifier>> entry = iterator.next();
+                    Dependency dependency = builtModules.get(entry.getKey());
+                    if (dependency != null) {
+                        filteredDependencies.add(amend(dependency, entry.getValue()));
+                        iterator.remove();
+                    }
+                }
+                for (Dependency dependency : dependencies) {
+                    String dependencyModuleName = findModuleDescriptor(dependency)
+                            .map(ModuleDescriptor::name)
+                            .orElse(null);
+                    /*
+                     * If `dependencyModuleName` is null, then the dependency scope is "test" or some other scope
+                     * that resolver has chosen to exclude. Note that this is true even for JAR on the classpath,
+                     * because we stored the automatic module name in `PomDerivation`. Next, if `modifiers` is null,
+                     * then the dependency has compile or runtime scope but is not used by the module to archive.
+                     */
+                    if (dependencyModuleName != null) {
+                        EnumSet<Modifier> modifiers = requires.remove(dependencyModuleName);
+                        if (modifiers != null) {
+                            filteredDependencies.add(amend(dependency, modifiers));
+                        }
+                    }
+                }
+                builder.dependencies(filteredDependencies);
+            }
+            /*
+             * Replace the `<name>` element by the equivalent value defined in MANIFEST.MF.
+             * We do this replacement because the `<name>` of the project model applies to all modules,
+             * while the MANIFEST.MF has more chances to be specific to the module that we are archiving.
+             */
+            return builder.build();
+        }
+
+        /**
+         * Modifies the optional and scope elements of the given dependency according the given modifiers.
+         *
+         * @param dependency the dependency to amend
+         * @param modifiers the modifiers to apply
+         * @return the amended dependency
+         */
+        private static Dependency amend(Dependency dependency, EnumSet<Modifier> modifiers) {
+            String scope = modifiers.contains(Modifier.RUNTIME) ? "runtime" : null;
+            if (!Objects.equals(scope, dependency.getScope())) {
+                dependency = dependency.withScope(scope);
+            }
+            boolean optional = modifiers.contains(Modifier.OPTIONAL);
+            if (Boolean.parseBoolean(dependency.getOptional()) != optional) {
+                dependency = dependency.withOptional(Boolean.toString(optional));
+            }
+            return dependency;
+        }
+    }
+
+    /**
+     * Writes the parent <abbr>POM</abbr> file as the project file but without the dependencies.
+     * The dependencies are removed because they will declared on a module-by-module basis.
+     *
+     * @param packageHierarchy value of {@link FileCollector#packageHierarchy}
+     * @return path to the file that has been written
+     * @throws IOException if an I/O error occurred while writing the model
+     *
+     * @see ForModule#writeModulePOM()
+     */
+    Path writeParentPOM(final Archive packageHierarchy) throws IOException {
+        Path pomFile = derivePathToPOM(packageHierarchy.jarFile);
+        Model.Builder builder = Model.newBuilder(projectModel, true);
+        builder = builder.root(false).modules(null).subprojects(null);
+        builder = builder.dependencies(null).build(null).reporting(null).distributionManagement(null);

Review Comment:
   Yes but we cannot remove it. `modules` and `subprojects` are two separated fields in the builder, I don't know why. We need to clear both of them.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3892050472


##########
src/main/java/org/apache/maven/plugins/jar/PomDerivation.java:
##########
@@ -0,0 +1,525 @@
+/*
+ * 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.jar;
+
+import javax.xml.stream.XMLStreamException;
+
+import java.io.BufferedInputStream;
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.UncheckedIOException;
+import java.lang.module.ModuleDescriptor;
+import java.lang.module.ModuleFinder;
+import java.lang.module.ModuleReference;
+import java.net.URI;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.DependencyCoordinates;
+import org.apache.maven.api.JavaPathType;
+import org.apache.maven.api.Session;
+import org.apache.maven.api.Type;
+import org.apache.maven.api.model.Dependency;
+import org.apache.maven.api.model.Model;
+import org.apache.maven.api.model.Parent;
+import org.apache.maven.api.plugin.MojoException;
+import org.apache.maven.api.services.DependencyCoordinatesFactory;
+import org.apache.maven.api.services.DependencyCoordinatesFactoryRequest;
+import org.apache.maven.api.services.DependencyResolver;
+import org.apache.maven.api.services.DependencyResolverRequest;
+import org.apache.maven.api.services.DependencyResolverResult;
+import org.apache.maven.api.services.ModelBuilderException;
+import org.apache.maven.model.v4.MavenStaxWriter;
+
+/**
+ * A mapper from Maven model dependencies to Java module names.
+ * A single instance of this class is created for a Maven project,
+ * then shared by all {@link ForModule} instances (one per module to archive).
+ */
+final class PomDerivation {
+    /**
+     * Whether to expand the list of transitive dependencies in the generated <abbr>POM</abbr>.
+     */
+    private static final boolean EXPAND_TRANSITIVE = false;
+
+    /**
+     * Copy of {@link AbstractJarMojo#session}.
+     */
+    private final Session session;
+
+    /**
+     * The project model, which includes dependencies of all modules.
+     */
+    private final Model projectModel;
+
+    /**
+     * The factory to use for creating temporary {@link DependencyCoordinates} instances.
+     */
+    private final DependencyCoordinatesFactory coordinateFactory;
+
+    /**
+     * Provide module descriptors from module names.
+     * May be {@code null} if no {@code module-info} was found.
+     */
+    private final ModuleFinder moduleFinder;
+
+    /**
+     * Module references from paths to the <abbr>JAR</abbr> file or root directory.
+     */
+    private final Map<URI, ModuleReference> fromURI;
+
+    /**
+     * Module names associated to Maven dependencies.

Review Comment:
   done



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3892080787


##########
src/main/java/org/apache/maven/plugins/jar/Providers.java:
##########
@@ -22,25 +22,13 @@
 import org.apache.maven.api.di.Named;
 import org.apache.maven.api.di.Provides;
 import org.apache.maven.api.services.ProjectManager;
-import org.codehaus.plexus.archiver.Archiver;
-import org.codehaus.plexus.archiver.jar.JarArchiver;
-import org.codehaus.plexus.archiver.jar.JarToolModularJarArchiver;
 
+/**
+ * For providing instances to fields annotated with {@code @Inject} if the MOJO.

Review Comment:
   Actually I don't really understand myself how these `Providers` classes are used, I'm not even sure if they are still needed. @gnodet would known better.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3891836317


##########
src/main/java/org/apache/maven/plugins/jar/AbstractJarMojo.java:
##########
@@ -207,167 +205,208 @@ protected final Log getLog() {
     protected abstract String getType();
 
     /**
-     * Returns the JAR file to generate, based on an optional classifier.
+     * {@return the scope of dependencies}
+     * It should be {@link PathScope#MAIN_COMPILE} or {@link PathScope#TEST_COMPILE}.
+     * Note that we use compile scope rather than runtime scope because dependencies
+     * cannot appear in {@code requires} statement if they didn't had compile scope.
+     */
+    protected abstract PathScope getDependencyScope();
+
+    /**
+     * {@return the JAR tool to use for archiving the code}
      *
-     * @param basedir the output directory
-     * @param resultFinalName the name of the JAR file
-     * @param classifier an optional classifier
-     * @return the file to generate
+     * @throws MojoException if no JAR tool was found
+     *
+     * @since 4.0.0-beta-2
      */
-    protected Path getJarFile(Path basedir, String resultFinalName, String classifier) {
-        Objects.requireNonNull(basedir, "basedir is not allowed to be null");
-        Objects.requireNonNull(resultFinalName, "finalName is not allowed to be null");
-        String fileName = resultFinalName + (hasClassifier(classifier) ? '-' + classifier : "") + ".jar";
-        return basedir.resolve(fileName);
+    protected ToolProvider getJarTool() throws MojoException {
+        return ToolProvider.findFirst(toolId).orElseThrow(() -> new MojoException("No such \"" + toolId + "\" tool."));
     }
 
     /**
-     * Generates the JAR.
+     * Returns the output time stamp or, as a fallback, the {@code SOURCE_DATE_EPOCH} environment variable.
+     * If the time stamp is expressed in seconds, it is converted to ISO 8601 format. Otherwise it is returned as-is.
      *
-     * @return the path to the created archive file
-     * @throws MojoException in case of an error
+     * @return the time stamp in presumed ISO 8601 format, or {@code null} if none
+     *
+     * @since 4.0.0-beta-2
      */
-    public Path createArchive() throws MojoException {
-        Path basedir = outputDirectory != null
-                ? outputDirectory
-                : Path.of(project.getBuild().getDirectory());
-        String resultFinalName =
-                finalName != null ? finalName : project.getBuild().getFinalName();
-        Path jarFile = getJarFile(basedir, resultFinalName, getClassifier());
-
-        FileSetManager fileSetManager = new FileSetManager();
-        FileSet jarContentFileSet = new FileSet();
-        jarContentFileSet.setDirectory(getClassesDirectory().toAbsolutePath().toString());
-        jarContentFileSet.setIncludes(Arrays.asList(getIncludes()));
-        jarContentFileSet.setExcludes(Arrays.asList(getExcludes()));
-
-        String[] includedFiles = fileSetManager.getIncludedFiles(jarContentFileSet);
-
-        if (detectMultiReleaseJar
-                && Arrays.stream(includedFiles)
-                        .anyMatch(
-                                p -> p.startsWith("META-INF" + File.separatorChar + "versions" + File.separatorChar))) {
-            getLog().debug("Adding 'Multi-Release: true' manifest entry.");
-            archive.addManifestEntry(Attributes.Name.MULTI_RELEASE.toString(), "true");
+    protected String getOutputTimestamp() {
+        String time = nullIfAbsent(outputTimestamp);
+        if (time == null) {
+            time = nullIfAbsent(System.getenv("SOURCE_DATE_EPOCH"));
+            if (time == null) {
+                return null;
+            }
         }
+        if (Runtime.version().feature() < ToolExecutor.JDK_SUPPORT_DATE) {

Review Comment:
   We tried, the consequence as massive. The problem is that it has been decided that a default timestamp should be provided in the super POM (I don't think that we should have done that, but it is done now). Consequently, almost all integration tests fail on Java 17 for example. The opt-out are not so easy, as they cause for example `IndexOutOfBoundsException` in old versions of the Maven compiler plugin.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3891921214


##########
src/main/java/org/apache/maven/plugins/jar/Archive.java:
##########
@@ -0,0 +1,692 @@
+/*
+ * 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.jar;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.TreeMap;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.apache.maven.api.Type;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.MojoException;
+
+/**
+ * Files or root directories to archive for a single module.
+ * A single instance of {@code Archive} may contain many directories for different target Java releases.
+ * Many instances of {@code Archive} may exist when archiving a multi-modules project.
+ */
+final class Archive {
+    /**
+     * Whether to repeat the {@code -C} option before each file.
+     * Doing so makes the command-line very verbose while the documentation of
+     * <a href="https://docs.oracle.com/en/java/javase/25/docs/specs/man/jar.html">The jar Command</a>
+     * gives the impression that this option can be provided only once.
+     * However, our tests suggest that the first file after the directory specified by the {@code -C} option
+     * must be relative to that directory and all files after the first one must be prefixed by the directory
+     * which was specified in the {@code -C} option. This behavior is not documented, but we couldn't get the
+     * {@code jar} tool to work otherwise (except by repeating {@code -C} before each file).
+     * Furthermore, it seems that the relativized file needs to be the shortest one,
+     * otherwise the {@code jar} tool rejects files after the first one with "names do not match".
+     * Which file is first depends on the unspecified directory-iteration order.
+     *
+     * <p>If this flag is {@code true}, the plugin repeats {@code -C} before each file.
+     * This flag should be set to {@code false} if a future version of the {@code jar}
+     * tool allows to specify {@code -C} only once.</p>
+     *
+     * <p><b>Historical note:</b> we also tried to relativize only the first file after {@code -C}
+     * and keep all subsequent files as absolute. It works, but because we have to repeat the directory
+     * in the file name, it saves only 3 or 4 characters per file compared to repeating {@code -C}.</p>
+     */
+    private static final boolean REPEAT_C = true;
+
+    /**
+     * Path to the <abbr>POM</abbr> file generated for this archive, or {@code null} if none.
+     * This is non-null only if module source hierarchy is used, in which case the dependencies
+     * declared in this file are the intersection of the project dependencies and the content of
+     * the {@code module-info.class} file.
+     */
+    @Nullable
+    Path pomFile;
+
+    /**
+     * The <var>JAR</var> file to create. May be an existing file,
+     * in which case the file creation may be skipped if the file is still up-to-date.
+     */
+    @Nonnull
+    final Path jarFile;
+
+    /**
+     * A helper class for checking whether an existing <abbr>JAR</abbr> file is still up-to-date.
+     * This is null if there is no existing JAR file, or if we determined that the file is outdated.
+     */
+    private TimestampCheck existingJAR;
+
+    /**
+     * Name of the module being archived when the project is using module hierarchy.
+     * This is {@code null} if the project is using package hierarchy, either because it is a classical
+     * class-path project or because it is a single module compiled without using the module hierarchy.
+     * When using module source hierarchy, {@code javac} guarantees that the module name in the output
+     * directory is the name of the parent directory of {@code module-info.class}.
+     */
+    @Nullable
+    final String moduleName;
+
+    /**
+     * Path to {@code META-INF/MANIFEST.MF}, or {@code null} if none.
+     * If non-null, this value will be given to the {@code --manifest} option.
+     * The use of this option is preferable to adding {@code MANIFEST.MF} as an ordinary file.
+     *
+     * @see #setManifest(Path, boolean)
+     * @see #mergeManifest(Path, Manifest)
+     */
+    @Nullable
+    private Path manifest;
+
+    /**
+     * The Maven generated {@code pom.xml} and {@code pom.properties} files, or {@code null} if none.
+     * This first item shall be the base directory where the files are located.
+     */
+    @Nullable
+    List<Path> mavenFiles;
+
+    /**
+     * Fully-qualified name of the main class, or {@code null} if none.
+     * This is the value to provide to the {@code --main-class} option.
+     */
+    private String mainClass;
+
+    /**
+     * Files or root directories to store in the <abbr>JAR</abbr> file for each target Java release
+     * other than the base release. Keys are the target Java release with {@code null} for the base
+     * release.
+     */
+    @Nonnull
+    private final NavigableMap<Runtime.Version, FileSet> filesetForRelease;
+
+    /**
+     * Files or root directories to archive for a single target Java release of a single module.
+     * The {@link Archive} enclosing shall contain at least one instance of {@code FileSet} for
+     * the base release, and an arbitrary amount of other instances for other target releases.
+     */
+    final class FileSet {
+        /**
+         * A comparator for sorting paths in a reproducible order.
+         * This comparator assumes that all paths are relative to the same base directory (this is not verified).
+         * Note: we do not use {@link Path#compareTo(Path)} because the Javadoc said that it is platform dependent.
+         */
+        private static final Comparator<Path> REPRODUCIBLE_ORDER = (p1, p2) -> {
+            final int c1 = p1.getNameCount();
+            final int c2 = p2.getNameCount();
+            final int c = Math.min(c1, c2);
+            for (int i = 0; i < c; i++) {
+                String n1 = p1.getName(i).toString();
+                String n2 = p2.getName(i).toString();
+                int r = n1.compareTo(n2); // Case-sensitive comparison on all platforms.
+                if (r != 0) {
+                    return r;
+                }
+            }
+            return c1 - c2;
+        };
+
+        /**
+         * The root directory of all files or directories to archive.
+         * This is the value to pass to the {@code -C} tool option.
+         */
+        @Nonnull
+        final Path directory;
+
+        /**
+         * The files or directories to include in the <var>JAR</var> file.
+         * May be absolute paths or paths relative to {@link #directory}.
+         */
+        @Nonnull
+        final List<Path> files;
+
+        /**
+         * Creates an initially empty set of files or directories for a specific target Java release.
+         *
+         * @param directory the base directory of the files or directories to archive
+         */
+        private FileSet(Path directory) {
+            this.directory = directory;
+            this.files = new ArrayList<>();
+        }
+
+        /**
+         * 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.
+         * The caller should use that common directory for logging a warning message.
+         *
+         * @param base base directory found by previous invocations of this method, or {@code null} if none
+         * @return common directory of discarded files
+         */
+        private Path discardAllFiles(Path base) {
+            for (Path file : files) {
+                file = directory.resolve(file);
+                if (base == null) {
+                    base = file.getParent();
+                } else {
+                    while (!file.startsWith(base)) {
+                        base = base.getParent();
+                        if (base == null) {
+                            break;
+                        }
+                    }
+                }
+            }
+            files.clear();
+            return base;
+        }
+
+        /**
+         * Adds the given path to the list of files or directories to archive.
+         * This method may store a relative path instead of the absolute path.
+         *
+         * @param item a file or directory to archive
+         * @param attributes the file's basic attributes
+         * @param isDirectory whether the file is a directory
+         * @throws IllegalArgumentException if the given path cannot be made relative to the base directory
+         */
+        void add(Path item, BasicFileAttributes attributes, boolean isDirectory) {
+            TimestampCheck tc = existingJAR;
+            if (tc != null && tc.isUpdated(item, attributes, isDirectory)) {
+                existingJAR = null; // Signal that the existing file is outdated.
+            }
+            item = directory.relativize(item);
+            if (item.getNameCount() <= 1 && item.toString().isEmpty()) {
+                /*
+                 * The item is the `-C` directory itself (e.g. a `META-INF/versions/<n>` directory
+                 * added as a whole). An empty file argument is invalid for the `jar` tool
+                 * (some implementations reject it, others silently misbehave),
+                 * so archive the whole directory content with ".".
+                 */
+                item = Path.of(".");
+            }
+            files.add(item);
+        }
+
+        /**
+         * Adds to the given list the arguments to provide to the "jar" tool for this version.
+         * Elements added to the list shall be instances of {@link String} or {@link Path}.
+         *
+         * @param addTo the list where to add the arguments as {@link String} or {@link Path} instances
+         * @param version the target Java release, or {@code null} for the base version of the <abbr>JAR</abbr> file
+         */
+        private void arguments(List<Object> addTo, Runtime.Version version) {
+            if (!files.isEmpty()) {
+                if (version != null) {
+                    addTo.add("--release");
+                    addTo.add(version);
+                }
+                if (isReproducible) {
+                    files.sort(REPRODUCIBLE_ORDER);
+                }
+                if (REPEAT_C) {
+                    for (Path file : files) {
+                        addTo.add("-C");
+                        addTo.add(directory);
+                        addTo.add(file);
+                    }
+                } else {
+                    addTo.add("-C");
+                    addTo.add(directory);
+                    addTo.addAll(files);
+                }
+            }
+        }
+
+        /**
+         * {@return a string representation for debugging purposes}
+         */
+        @Override
+        public String toString() {
+            return getClass().getSimpleName() + '[' + directory.getFileName() + ": " + files.size() + " files]";
+        }
+    }
+
+    /**
+     * Whether reproducible build was requested.
+     */
+    private final boolean isReproducible;
+
+    /**
+     * Creates an initially empty set of files or directories.
+     *
+     * @param jarFile path to the <abbr>JAR</abbr> file to create
+     * @param moduleName the module name if using module hierarchy, or {@code null} if using package hierarchy
+     * @param version the target Java release, or {@code null} for the base version
+     * @param directory the directory of the classes targeting the base Java release
+     * @param forceCreation whether to force a new <abbr>JAR</abbr> file even if the content seems unchanged
+     * @param isReproducible whether reproducible build was requested
+     * @param logger where to send a warning if an error occurred while checking an existing <abbr>JAR</abbr> file
+     */
+    @SuppressWarnings("checkstyle:NeedBraces")

Review Comment:
   Sometime strict compliance to those rules makes the code more difficult to read. This is a case where logical conditions can be aligned in a table. The brace rule (and also, to less extend, the space rule) break the tabular formatting. However I admit that in this case, the table is small. 



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3892020290


##########
src/main/java/org/apache/maven/plugins/jar/FileCollector.java:
##########
@@ -0,0 +1,496 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.PathMatcher;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayDeque;
+import java.util.Deque;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.services.PathMatcherFactory;
+
+/**
+ * Dispatch the files in the output directory into the <abbr>JAR</abbr> files to create.
+ * Instead of just archiving as-is the content of the output directory, this class separates
+ * the following subdirectories to the options listed below:
+ *
+ * <ul>
+ *   <li>The {@code META-INF/MANIFEST.MF} file will be given to the {@code --manifest} option.</li>
+ *   <li>Files in the following directories will be given to the {@code --release} option:
+ *     <ul>
+ *       <li>{@code META-INF/versions/}</li>
+ *       <li>{@code META-INF/versions-modular/<module>/}</li>
+ *       <li>{@code <module>/META-INF/versions/}</li>
+ *     </ul>
+ *   </li>
+ * </ul>
+ *
+ * The reason for using the options is that they allow the {@code jar} tool to perform additional verifications.
+ * For example, when using the {@code --release} option, {@code jar} verifies the <abbr>API</abbr> compatibility.
+ */
+final class FileCollector extends SimpleFileVisitor<Path> {
+    /**
+     * The file to check for deciding whether the <abbr>JAR</abbr> is modular.
+     */
+    static final String MODULE_DESCRIPTOR_FILE_NAME = "module-info.class";
+
+    /**
+     * The {@value} directory.
+     * This is part of <abbr>JAR</abbr> file specification.
+     */
+    private static final String VERSIONS = "versions";
+
+    /**
+     * The {@value} directory.
+     * This is Maven-specific.
+     */
+    private static final String VERSIONS_MODULAR = "versions-modular";
+
+    /**
+     * Context (logger, configuration) in which the <abbr>JAR</abbr> file are created.
+     */
+    private final ToolExecutor context;
+
+    /**
+     * Whether to detect multi-release <abbr>JAR</abbr> files.
+     * The default value is {@code true}.
+     *
+     * @see AbstractJarMojo#detectMultiReleaseJar
+     */
+    private final boolean detectMultiReleaseJar;
+
+    /**
+     * Combination of includes and excludes path matcher applied on files.
+     */
+    @Nonnull
+    private final PathMatcher fileMatcher;
+
+    /**
+     * Combination of includes and excludes path matcher applied on directories.
+     */
+    @Nonnull
+    private final PathMatcher directoryMatcher;
+
+    /**
+     * Whether the matchers accept all files and there is no need to sort the files.
+     * In such case, we can declare whole directories to the {@code jar} tool instead
+     * of scanning the directory tree ourselves.
+     */
+    private final boolean addDirectories;
+
+    /**
+     * Files found in the output directory when package hierarchy is used.
+     * At most one of {@code packageHierarchy} and {@link #moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Archive packageHierarchy;
+
+    /**
+     * Files found in the output directory when module hierarchy is used. Keys are module names.
+     * At most one of {@link #packageHierarchy} and {@code moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Map<String, Archive> moduleHierarchy;
+
+    /**
+     * The current module being archived. This field is updated every times that {@code FileCollector}
+     * enters in a new module directory.
+     */
+    @Nonnull
+    private Archive currentModule;
+
+    /**
+     * The module and target Java release currently being scanned. This field is updated every times that
+     * {@code FileCollector} enters in a new module directory or in a new target Java release for a given module.
+     */
+    @Nonnull
+    private Archive.FileSet currentFilesToArchive;
+
+    /**
+     * The current target Java release, or {@code null} if none.
+     */
+    @Nullable
+    private Runtime.Version currentTargetVersion;
+
+    /**
+     * Identification of the kinds of directories being traversed.
+     * The length of this list is the depth in the directory hierarchy.
+     * The last element identifies the type of the current directory.
+     */
+    private final Deque<DirectoryRole> directoryRoles;
+
+    /**
+     * Whether to check when a file is the {@code MANIFEST.MF} file.
+     * This is allowed only when scanning the content of a {@code META-INF} directory.
+     */
+    private boolean checkForManifest;
+
+    /**
+     * Creates a new file collector.
+     *
+     * @param mojo the <abbr>MOJO</abbr> from which to get the configuration
+     * @param context context (logger, configuration) in which the <abbr>JAR</abbr> file are created
+     * @param directory the base directory of the files to archive
+     */
+    FileCollector(AbstractJarMojo mojo, ToolExecutor context, Path directory, PathMatcherFactory matcherFactory) {
+        this.context = context;
+        detectMultiReleaseJar = mojo.detectMultiReleaseJar;
+        directoryRoles = new ArrayDeque<>();
+        fileMatcher = matcherFactory.createPathMatcher(directory, mojo.getIncludes(), mojo.getExcludes(), false);
+        directoryMatcher = matcherFactory.deriveDirectoryMatcher(fileMatcher);
+        addDirectories = !context.isReproducible()
+                && matcherFactory.isIncludesAll(fileMatcher)
+                && matcherFactory.isIncludesAll(directoryMatcher);
+        packageHierarchy = context.newArchive(null, null, directory);
+        moduleHierarchy = new LinkedHashMap<>();
+        resetToPackageHierarchy();
+    }
+
+    /**
+     * Resets this {@code FileCollector} to the state where a package hierarchy is presumed.
+     */
+    private void resetToPackageHierarchy() {
+        currentModule = packageHierarchy;
+        currentFilesToArchive = currentModule.baseRelease();
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a module.
+     * For an output generated by {@code javac} from a module source hierarchy,
+     * the directory name is guaranteed to be the module name.
+     *
+     * @param directory a {@code "<module>"} or {@code "META-INF/versions-modular/<module>"} directory
+     */
+    private void enterModuleDirectory(final Path directory) {
+        String moduleName = directory.getFileName().toString();
+        currentModule = moduleHierarchy.computeIfAbsent(
+                moduleName, (name) -> context.newArchive(name, currentTargetVersion, directory));
+        currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a target Java version.
+     * The {@code useDirectly} argument tells whether the content of this directory will be specified directly
+     * as the content to add in the <abbr>JAR</abbr> file. This argument should be {@code false} when there is
+     * another directory level (the module names) to process before to add content.
+     *
+     * @param directory a {@code "META-INF/versions/<n>"} or {@code "META-INF/versions-modular/<n>"} directory
+     * @param useDirectly whether the directory is {@code "META-INF/versions/<n>"}
+     * @return whether to skip the directory because of invalid version number
+     */
+    private boolean enterVersionDirectory(final Path directory, final boolean useDirectly) {
+        try {
+            currentTargetVersion = Runtime.Version.parse(directory.getFileName().toString());
+        } catch (IllegalArgumentException e) {
+            context.warnInvalidVersion(directory, e);
+            return true;
+        }
+        if (useDirectly) {
+            currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+        }
+        return false;
+    }
+
+    /**
+     * Determines if the given directory should be scanned for files to archive.
+     * This method may also update {@link #currentFilesToArchive} if it detects
+     * that we are entering in a new module or a new target Java release.
+     *
+     * @param directory the directory which will be traversed
+     * @param attributes the directory's basic attributes
+     */
+    @Override
+    @SuppressWarnings("checkstyle:MissingSwitchDefault")
+    public FileVisitResult preVisitDirectory(final Path directory, final BasicFileAttributes attributes)
+            throws IOException {
+        DirectoryRole role;
+        if (directoryRoles.isEmpty()) {
+            role = DirectoryRole.ROOT;
+        } else {
+            if (!directoryMatcher.matches(directory)) {
+                return FileVisitResult.SKIP_SUBTREE;
+            }
+            checkForManifest = false;
+            role = directoryRoles.getLast();
+            switch (role) {
+                case ROOT:
+                    /*
+                     * Entering in any subdirectory of `target/classes` (or other directory to archive).
+                     * We need to handle `META-INF` and modules in a special way, and archive the rest.
+                     */
+                    if (directory.endsWith(MetadataFiles.META_INF)) {
+                        role = DirectoryRole.META_INF;
+                        checkForManifest = true;
+                    } else if (Files.isRegularFile(directory.resolve(MODULE_DESCRIPTOR_FILE_NAME))) {
+                        role = DirectoryRole.NAMED_MODULE;
+                        enterModuleDirectory(directory);
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case META_INF:
+                    /*
+                     * Entering in a subdirectory of `META-INF` or `<module>/META-INF`. We will need to handle
+                     * `MANIFEST.MF`, `versions` and `versions-modular` in a special way, and archive the rest.
+                     */
+                    if (detectMultiReleaseJar && directory.endsWith(VERSIONS)) {
+                        role = DirectoryRole.VERSIONS;
+                    } else if (directory.endsWith(VERSIONS_MODULAR)) {
+                        if (!detectMultiReleaseJar) {
+                            // Used asked for no multi-release JAR.
+                            return FileVisitResult.SKIP_SUBTREE;
+                        }
+                        role = DirectoryRole.VERSIONS_MODULAR;
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case VERSIONS:
+                    /*
+                     * Entering in a `META-INF/versions/<n>/` directory for a specific target Java release.
+                     * May also be a `<module>/META-INF/versions/<n>/` directory, even if the latter is not
+                     * the layout generated by Maven Compiler Plugin.
+                     */
+                    if (enterVersionDirectory(directory, true)) {
+                        // An error occurred while parsing the version number.
+                        return FileVisitResult.SKIP_SUBTREE;
+                    }
+                    role = DirectoryRole.RESOURCES;
+                    break;
+
+                case VERSIONS_MODULAR:
+                    /*
+                     * Entering in a `META-INF/versions-modular/<n>/` directory for a specific target Java release.
+                     * That directory contains all modules for the version.
+                     */
+                    resetToPackageHierarchy(); // No module in particular yet.
+                    if (enterVersionDirectory(directory, false)) {
+                        // An error occurred while parsing the version number.
+                        return FileVisitResult.SKIP_SUBTREE;
+                    }
+                    role = DirectoryRole.MODULES;
+                    break;
+
+                case MODULES:
+                    /*
+                     * Entering in a `META-INF/versions-modular/<n>/<module>` directory.
+                     */
+                    enterModuleDirectory(directory);
+                    role = DirectoryRole.NAMED_MODULE;
+                    break;
+
+                case NAMED_MODULE:
+                    /*
+                     * Entering in a `<module>` or `META-INF/versions-modular/<n>/<module>` subdirectory.
+                     * A module could have its own `META-INF` subdirectory, so we need to check again.
+                     */
+                    if (directory.endsWith(MetadataFiles.META_INF)) {
+                        role = DirectoryRole.META_INF;
+                        checkForManifest = true;
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+            }
+        }
+        /*
+         * Do not move this condition inside the `switch` block because `role` may have been modified.
+         * The `role` value is now the role of `directory`, not anymore the role of parent directory.
+         */
+        if (addDirectories && role == DirectoryRole.RESOURCES) {
+            currentFilesToArchive.add(directory, attributes, true);
+            /*
+             * Since we are skipping the whole directory, `postVisitDirectory(…)` will not be invoked.
+             * We must reset `currentFilesToArchive` and `currentTargetVersion` by an explicit call.
+             * This is important mostly after we added a whole `META-INF/versions/<n>` directory,
+             * otherwise base files visited afterwards (directory iteration order is unspecified)
+             * would be added to this version's file set instead of the base release.
+             */
+            resetToParentDirectoryState();
+            return FileVisitResult.SKIP_SUBTREE;
+        } else {
+            directoryRoles.addLast(role);
+            return FileVisitResult.CONTINUE;
+        }
+    }
+
+    /**
+     * Updates the {@code FileCollector} state after we finished to scan the content of a directory.
+     * The fields to update depend on which directory has been visited (module, version, <i>etc.</i>).
+     *
+     * @param directory the directory which has been traversed
+     * @param error the error that occurred while traversing the directory, or {@code null} if none
+     */
+    @Override
+    public FileVisitResult postVisitDirectory(final Path directory, final IOException error) throws IOException {
+        if (error != null) {
+            throw error;
+        }
+        switch (directoryRoles.removeLast()) {
+            case NAMED_MODULE:
+                // Exited the directory of a single module.
+                resetToPackageHierarchy();
+                break;
+
+            case ROOT:
+                break;
+
+            default:
+                resetToParentDirectoryState();
+        }
+        return FileVisitResult.CONTINUE;
+    }
+
+    /**
+     * Updates {@code FileCollector} to a state suitable to the parent of the directory that we finished to scan.
+     * Contrarily to {@link #postVisitDirectory(Path, IOException)}, this method expects the last element of

Review Comment:
   Done



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3892010101


##########
src/main/java/org/apache/maven/plugins/jar/FileCollector.java:
##########
@@ -0,0 +1,496 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.PathMatcher;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayDeque;
+import java.util.Deque;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.services.PathMatcherFactory;
+
+/**
+ * Dispatch the files in the output directory into the <abbr>JAR</abbr> files to create.
+ * Instead of just archiving as-is the content of the output directory, this class separates
+ * the following subdirectories to the options listed below:
+ *
+ * <ul>
+ *   <li>The {@code META-INF/MANIFEST.MF} file will be given to the {@code --manifest} option.</li>
+ *   <li>Files in the following directories will be given to the {@code --release} option:
+ *     <ul>
+ *       <li>{@code META-INF/versions/}</li>
+ *       <li>{@code META-INF/versions-modular/<module>/}</li>
+ *       <li>{@code <module>/META-INF/versions/}</li>
+ *     </ul>
+ *   </li>
+ * </ul>
+ *
+ * The reason for using the options is that they allow the {@code jar} tool to perform additional verifications.
+ * For example, when using the {@code --release} option, {@code jar} verifies the <abbr>API</abbr> compatibility.
+ */
+final class FileCollector extends SimpleFileVisitor<Path> {
+    /**
+     * The file to check for deciding whether the <abbr>JAR</abbr> is modular.
+     */
+    static final String MODULE_DESCRIPTOR_FILE_NAME = "module-info.class";
+
+    /**
+     * The {@value} directory.
+     * This is part of <abbr>JAR</abbr> file specification.
+     */
+    private static final String VERSIONS = "versions";
+
+    /**
+     * The {@value} directory.
+     * This is Maven-specific.
+     */
+    private static final String VERSIONS_MODULAR = "versions-modular";
+
+    /**
+     * Context (logger, configuration) in which the <abbr>JAR</abbr> file are created.
+     */
+    private final ToolExecutor context;
+
+    /**
+     * Whether to detect multi-release <abbr>JAR</abbr> files.
+     * The default value is {@code true}.
+     *
+     * @see AbstractJarMojo#detectMultiReleaseJar
+     */
+    private final boolean detectMultiReleaseJar;
+
+    /**
+     * Combination of includes and excludes path matcher applied on files.
+     */
+    @Nonnull
+    private final PathMatcher fileMatcher;
+
+    /**
+     * Combination of includes and excludes path matcher applied on directories.
+     */
+    @Nonnull
+    private final PathMatcher directoryMatcher;
+
+    /**
+     * Whether the matchers accept all files and there is no need to sort the files.
+     * In such case, we can declare whole directories to the {@code jar} tool instead
+     * of scanning the directory tree ourselves.
+     */
+    private final boolean addDirectories;
+
+    /**
+     * Files found in the output directory when package hierarchy is used.
+     * At most one of {@code packageHierarchy} and {@link #moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Archive packageHierarchy;
+
+    /**
+     * Files found in the output directory when module hierarchy is used. Keys are module names.
+     * At most one of {@link #packageHierarchy} and {@code moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Map<String, Archive> moduleHierarchy;
+
+    /**
+     * The current module being archived. This field is updated every times that {@code FileCollector}
+     * enters in a new module directory.
+     */
+    @Nonnull
+    private Archive currentModule;
+
+    /**
+     * The module and target Java release currently being scanned. This field is updated every times that
+     * {@code FileCollector} enters in a new module directory or in a new target Java release for a given module.
+     */
+    @Nonnull
+    private Archive.FileSet currentFilesToArchive;
+
+    /**
+     * The current target Java release, or {@code null} if none.
+     */
+    @Nullable
+    private Runtime.Version currentTargetVersion;
+
+    /**
+     * Identification of the kinds of directories being traversed.
+     * The length of this list is the depth in the directory hierarchy.
+     * The last element identifies the type of the current directory.
+     */
+    private final Deque<DirectoryRole> directoryRoles;
+
+    /**
+     * Whether to check when a file is the {@code MANIFEST.MF} file.
+     * This is allowed only when scanning the content of a {@code META-INF} directory.
+     */
+    private boolean checkForManifest;
+
+    /**
+     * Creates a new file collector.
+     *
+     * @param mojo the <abbr>MOJO</abbr> from which to get the configuration
+     * @param context context (logger, configuration) in which the <abbr>JAR</abbr> file are created
+     * @param directory the base directory of the files to archive
+     */
+    FileCollector(AbstractJarMojo mojo, ToolExecutor context, Path directory, PathMatcherFactory matcherFactory) {
+        this.context = context;
+        detectMultiReleaseJar = mojo.detectMultiReleaseJar;
+        directoryRoles = new ArrayDeque<>();
+        fileMatcher = matcherFactory.createPathMatcher(directory, mojo.getIncludes(), mojo.getExcludes(), false);
+        directoryMatcher = matcherFactory.deriveDirectoryMatcher(fileMatcher);
+        addDirectories = !context.isReproducible()
+                && matcherFactory.isIncludesAll(fileMatcher)
+                && matcherFactory.isIncludesAll(directoryMatcher);
+        packageHierarchy = context.newArchive(null, null, directory);
+        moduleHierarchy = new LinkedHashMap<>();
+        resetToPackageHierarchy();
+    }
+
+    /**
+     * Resets this {@code FileCollector} to the state where a package hierarchy is presumed.
+     */
+    private void resetToPackageHierarchy() {
+        currentModule = packageHierarchy;
+        currentFilesToArchive = currentModule.baseRelease();
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a module.
+     * For an output generated by {@code javac} from a module source hierarchy,
+     * the directory name is guaranteed to be the module name.
+     *
+     * @param directory a {@code "<module>"} or {@code "META-INF/versions-modular/<module>"} directory
+     */
+    private void enterModuleDirectory(final Path directory) {
+        String moduleName = directory.getFileName().toString();
+        currentModule = moduleHierarchy.computeIfAbsent(
+                moduleName, (name) -> context.newArchive(name, currentTargetVersion, directory));
+        currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a target Java version.
+     * The {@code useDirectly} argument tells whether the content of this directory will be specified directly
+     * as the content to add in the <abbr>JAR</abbr> file. This argument should be {@code false} when there is
+     * another directory level (the module names) to process before to add content.
+     *
+     * @param directory a {@code "META-INF/versions/<n>"} or {@code "META-INF/versions-modular/<n>"} directory
+     * @param useDirectly whether the directory is {@code "META-INF/versions/<n>"}
+     * @return whether to skip the directory because of invalid version number
+     */
+    private boolean enterVersionDirectory(final Path directory, final boolean useDirectly) {
+        try {
+            currentTargetVersion = Runtime.Version.parse(directory.getFileName().toString());
+        } catch (IllegalArgumentException e) {
+            context.warnInvalidVersion(directory, e);
+            return true;
+        }
+        if (useDirectly) {
+            currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+        }
+        return false;
+    }
+
+    /**
+     * Determines if the given directory should be scanned for files to archive.
+     * This method may also update {@link #currentFilesToArchive} if it detects
+     * that we are entering in a new module or a new target Java release.
+     *
+     * @param directory the directory which will be traversed
+     * @param attributes the directory's basic attributes
+     */
+    @Override
+    @SuppressWarnings("checkstyle:MissingSwitchDefault")
+    public FileVisitResult preVisitDirectory(final Path directory, final BasicFileAttributes attributes)
+            throws IOException {
+        DirectoryRole role;
+        if (directoryRoles.isEmpty()) {
+            role = DirectoryRole.ROOT;
+        } else {
+            if (!directoryMatcher.matches(directory)) {
+                return FileVisitResult.SKIP_SUBTREE;
+            }
+            checkForManifest = false;
+            role = directoryRoles.getLast();
+            switch (role) {
+                case ROOT:
+                    /*
+                     * Entering in any subdirectory of `target/classes` (or other directory to archive).
+                     * We need to handle `META-INF` and modules in a special way, and archive the rest.
+                     */
+                    if (directory.endsWith(MetadataFiles.META_INF)) {
+                        role = DirectoryRole.META_INF;
+                        checkForManifest = true;
+                    } else if (Files.isRegularFile(directory.resolve(MODULE_DESCRIPTOR_FILE_NAME))) {
+                        role = DirectoryRole.NAMED_MODULE;
+                        enterModuleDirectory(directory);
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case META_INF:
+                    /*
+                     * Entering in a subdirectory of `META-INF` or `<module>/META-INF`. We will need to handle
+                     * `MANIFEST.MF`, `versions` and `versions-modular` in a special way, and archive the rest.
+                     */
+                    if (detectMultiReleaseJar && directory.endsWith(VERSIONS)) {
+                        role = DirectoryRole.VERSIONS;
+                    } else if (directory.endsWith(VERSIONS_MODULAR)) {
+                        if (!detectMultiReleaseJar) {
+                            // Used asked for no multi-release JAR.
+                            return FileVisitResult.SKIP_SUBTREE;
+                        }
+                        role = DirectoryRole.VERSIONS_MODULAR;
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+
+                case VERSIONS:
+                    /*
+                     * Entering in a `META-INF/versions/<n>/` directory for a specific target Java release.
+                     * May also be a `<module>/META-INF/versions/<n>/` directory, even if the latter is not
+                     * the layout generated by Maven Compiler Plugin.
+                     */
+                    if (enterVersionDirectory(directory, true)) {
+                        // An error occurred while parsing the version number.
+                        return FileVisitResult.SKIP_SUBTREE;
+                    }
+                    role = DirectoryRole.RESOURCES;
+                    break;
+
+                case VERSIONS_MODULAR:
+                    /*
+                     * Entering in a `META-INF/versions-modular/<n>/` directory for a specific target Java release.
+                     * That directory contains all modules for the version.
+                     */
+                    resetToPackageHierarchy(); // No module in particular yet.
+                    if (enterVersionDirectory(directory, false)) {
+                        // An error occurred while parsing the version number.
+                        return FileVisitResult.SKIP_SUBTREE;
+                    }
+                    role = DirectoryRole.MODULES;
+                    break;
+
+                case MODULES:
+                    /*
+                     * Entering in a `META-INF/versions-modular/<n>/<module>` directory.
+                     */
+                    enterModuleDirectory(directory);
+                    role = DirectoryRole.NAMED_MODULE;
+                    break;
+
+                case NAMED_MODULE:
+                    /*
+                     * Entering in a `<module>` or `META-INF/versions-modular/<n>/<module>` subdirectory.
+                     * A module could have its own `META-INF` subdirectory, so we need to check again.
+                     */
+                    if (directory.endsWith(MetadataFiles.META_INF)) {
+                        role = DirectoryRole.META_INF;
+                        checkForManifest = true;
+                    } else {
+                        role = DirectoryRole.RESOURCES;
+                    }
+                    break;
+            }
+        }
+        /*
+         * Do not move this condition inside the `switch` block because `role` may have been modified.
+         * The `role` value is now the role of `directory`, not anymore the role of parent directory.
+         */
+        if (addDirectories && role == DirectoryRole.RESOURCES) {
+            currentFilesToArchive.add(directory, attributes, true);
+            /*
+             * Since we are skipping the whole directory, `postVisitDirectory(…)` will not be invoked.
+             * We must reset `currentFilesToArchive` and `currentTargetVersion` by an explicit call.
+             * This is important mostly after we added a whole `META-INF/versions/<n>` directory,
+             * otherwise base files visited afterwards (directory iteration order is unspecified)
+             * would be added to this version's file set instead of the base release.
+             */
+            resetToParentDirectoryState();
+            return FileVisitResult.SKIP_SUBTREE;
+        } else {
+            directoryRoles.addLast(role);
+            return FileVisitResult.CONTINUE;
+        }
+    }
+
+    /**
+     * Updates the {@code FileCollector} state after we finished to scan the content of a directory.

Review Comment:
   Done



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3891996839


##########
src/main/java/org/apache/maven/plugins/jar/FileCollector.java:
##########
@@ -0,0 +1,496 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.PathMatcher;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayDeque;
+import java.util.Deque;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+import org.apache.maven.api.services.PathMatcherFactory;
+
+/**
+ * Dispatch the files in the output directory into the <abbr>JAR</abbr> files to create.
+ * Instead of just archiving as-is the content of the output directory, this class separates
+ * the following subdirectories to the options listed below:
+ *
+ * <ul>
+ *   <li>The {@code META-INF/MANIFEST.MF} file will be given to the {@code --manifest} option.</li>
+ *   <li>Files in the following directories will be given to the {@code --release} option:
+ *     <ul>
+ *       <li>{@code META-INF/versions/}</li>
+ *       <li>{@code META-INF/versions-modular/<module>/}</li>
+ *       <li>{@code <module>/META-INF/versions/}</li>
+ *     </ul>
+ *   </li>
+ * </ul>
+ *
+ * The reason for using the options is that they allow the {@code jar} tool to perform additional verifications.
+ * For example, when using the {@code --release} option, {@code jar} verifies the <abbr>API</abbr> compatibility.
+ */
+final class FileCollector extends SimpleFileVisitor<Path> {
+    /**
+     * The file to check for deciding whether the <abbr>JAR</abbr> is modular.
+     */
+    static final String MODULE_DESCRIPTOR_FILE_NAME = "module-info.class";
+
+    /**
+     * The {@value} directory.
+     * This is part of <abbr>JAR</abbr> file specification.
+     */
+    private static final String VERSIONS = "versions";
+
+    /**
+     * The {@value} directory.
+     * This is Maven-specific.
+     */
+    private static final String VERSIONS_MODULAR = "versions-modular";
+
+    /**
+     * Context (logger, configuration) in which the <abbr>JAR</abbr> file are created.
+     */
+    private final ToolExecutor context;
+
+    /**
+     * Whether to detect multi-release <abbr>JAR</abbr> files.
+     * The default value is {@code true}.
+     *
+     * @see AbstractJarMojo#detectMultiReleaseJar
+     */
+    private final boolean detectMultiReleaseJar;
+
+    /**
+     * Combination of includes and excludes path matcher applied on files.
+     */
+    @Nonnull
+    private final PathMatcher fileMatcher;
+
+    /**
+     * Combination of includes and excludes path matcher applied on directories.
+     */
+    @Nonnull
+    private final PathMatcher directoryMatcher;
+
+    /**
+     * Whether the matchers accept all files and there is no need to sort the files.
+     * In such case, we can declare whole directories to the {@code jar} tool instead
+     * of scanning the directory tree ourselves.
+     */
+    private final boolean addDirectories;
+
+    /**
+     * Files found in the output directory when package hierarchy is used.
+     * At most one of {@code packageHierarchy} and {@link #moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Archive packageHierarchy;
+
+    /**
+     * Files found in the output directory when module hierarchy is used. Keys are module names.
+     * At most one of {@link #packageHierarchy} and {@code moduleHierarchy} can be non-empty.
+     */
+    @Nonnull
+    private final Map<String, Archive> moduleHierarchy;
+
+    /**
+     * The current module being archived. This field is updated every times that {@code FileCollector}
+     * enters in a new module directory.
+     */
+    @Nonnull
+    private Archive currentModule;
+
+    /**
+     * The module and target Java release currently being scanned. This field is updated every times that
+     * {@code FileCollector} enters in a new module directory or in a new target Java release for a given module.
+     */
+    @Nonnull
+    private Archive.FileSet currentFilesToArchive;
+
+    /**
+     * The current target Java release, or {@code null} if none.
+     */
+    @Nullable
+    private Runtime.Version currentTargetVersion;
+
+    /**
+     * Identification of the kinds of directories being traversed.
+     * The length of this list is the depth in the directory hierarchy.
+     * The last element identifies the type of the current directory.
+     */
+    private final Deque<DirectoryRole> directoryRoles;
+
+    /**
+     * Whether to check when a file is the {@code MANIFEST.MF} file.
+     * This is allowed only when scanning the content of a {@code META-INF} directory.
+     */
+    private boolean checkForManifest;
+
+    /**
+     * Creates a new file collector.
+     *
+     * @param mojo the <abbr>MOJO</abbr> from which to get the configuration
+     * @param context context (logger, configuration) in which the <abbr>JAR</abbr> file are created
+     * @param directory the base directory of the files to archive
+     */
+    FileCollector(AbstractJarMojo mojo, ToolExecutor context, Path directory, PathMatcherFactory matcherFactory) {
+        this.context = context;
+        detectMultiReleaseJar = mojo.detectMultiReleaseJar;
+        directoryRoles = new ArrayDeque<>();
+        fileMatcher = matcherFactory.createPathMatcher(directory, mojo.getIncludes(), mojo.getExcludes(), false);
+        directoryMatcher = matcherFactory.deriveDirectoryMatcher(fileMatcher);
+        addDirectories = !context.isReproducible()
+                && matcherFactory.isIncludesAll(fileMatcher)
+                && matcherFactory.isIncludesAll(directoryMatcher);
+        packageHierarchy = context.newArchive(null, null, directory);
+        moduleHierarchy = new LinkedHashMap<>();
+        resetToPackageHierarchy();
+    }
+
+    /**
+     * Resets this {@code FileCollector} to the state where a package hierarchy is presumed.
+     */
+    private void resetToPackageHierarchy() {
+        currentModule = packageHierarchy;
+        currentFilesToArchive = currentModule.baseRelease();
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a module.
+     * For an output generated by {@code javac} from a module source hierarchy,
+     * the directory name is guaranteed to be the module name.
+     *
+     * @param directory a {@code "<module>"} or {@code "META-INF/versions-modular/<module>"} directory
+     */
+    private void enterModuleDirectory(final Path directory) {
+        String moduleName = directory.getFileName().toString();
+        currentModule = moduleHierarchy.computeIfAbsent(
+                moduleName, (name) -> context.newArchive(name, currentTargetVersion, directory));
+        currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+    }
+
+    /**
+     * Declares that the given directory is the base directory of a target Java version.
+     * The {@code useDirectly} argument tells whether the content of this directory will be specified directly
+     * as the content to add in the <abbr>JAR</abbr> file. This argument should be {@code false} when there is
+     * another directory level (the module names) to process before to add content.
+     *
+     * @param directory a {@code "META-INF/versions/<n>"} or {@code "META-INF/versions-modular/<n>"} directory
+     * @param useDirectly whether the directory is {@code "META-INF/versions/<n>"}
+     * @return whether to skip the directory because of invalid version number
+     */
+    private boolean enterVersionDirectory(final Path directory, final boolean useDirectly) {
+        try {
+            currentTargetVersion = Runtime.Version.parse(directory.getFileName().toString());
+        } catch (IllegalArgumentException e) {
+            context.warnInvalidVersion(directory, e);
+            return true;
+        }
+        if (useDirectly) {
+            currentFilesToArchive = currentModule.newTargetRelease(directory, currentTargetVersion);
+        }
+        return false;
+    }
+
+    /**
+     * Determines if the given directory should be scanned for files to archive.
+     * This method may also update {@link #currentFilesToArchive} if it detects
+     * that we are entering in a new module or a new target Java release.
+     *
+     * @param directory the directory which will be traversed
+     * @param attributes the directory's basic attributes
+     */
+    @Override
+    @SuppressWarnings("checkstyle:MissingSwitchDefault")
+    public FileVisitResult preVisitDirectory(final Path directory, final BasicFileAttributes attributes)
+            throws IOException {
+        DirectoryRole role;
+        if (directoryRoles.isEmpty()) {
+            role = DirectoryRole.ROOT;
+        } else {
+            if (!directoryMatcher.matches(directory)) {
+                return FileVisitResult.SKIP_SUBTREE;
+            }
+            checkForManifest = false;
+            role = directoryRoles.getLast();
+            switch (role) {
+                case ROOT:
+                    /*
+                     * Entering in any subdirectory of `target/classes` (or other directory to archive).

Review Comment:
   Replaced by "Visit".



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3892093642


##########
src/main/java/org/apache/maven/plugins/jar/TimestampCheck.java:
##########
@@ -0,0 +1,237 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.nio.file.attribute.FileTime;
+import java.util.Collection;
+import java.util.Enumeration;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+
+import org.apache.maven.api.plugin.Log;
+
+/**
+ * Checks file timestamps in order to determine if anything changed compared to an existing <abbr>JAR</abbr> file.
+ * This class may scan directories, but only if they have not already been visited by {@link FileCollector}.
+ * Note that the latter can occur only if {@link FileCollector} has no {@code PathMatcher}.
+ * Therefore, this class uses no {@code PathMatcher} neither.
+ *
+ * <h2>Ignore files</h2>
+ * The {@code META-INF/MANIFEST.MF} file and the {@code META-INF/maven/} directory are ignored.
+ * See {@link #isIgnored(Path)} for the rational.
+ */
+final class TimestampCheck extends SimpleFileVisitor<Path> {
+    /**
+     * The base directory of archived files.
+     */
+    private final Path classesDir;
+
+    /**
+     * Path to the existing <abbr>JAR</abbr> file.
+     */
+    private final Path jarFile;
+
+    /**
+     * The last modified time of the <abbr>JAR</abbr> file.
+     */
+    private final FileTime jarFileTime;
+
+    /**
+     * Where to send non-fatal error messages.
+     */
+    private final Log logger;
+
+    /**
+     * Entries of the <abbr>JAR</abbr> file. Note that getting elements from this enumeration can be costly.
+     * Therefore, we do not fetch all elements in advance but only when needed.
+     */
+    private Enumeration<? extends ZipEntry> entries;
+
+    /**
+     * Files found in the <abbr>JAR</abbr> file but not yet traversed by the file visitor.
+     * Files are added lazily only when needed, and removed as soon as they have been traversed.

Review Comment:
   Done.



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3892088671


##########
src/main/java/org/apache/maven/plugins/jar/TimestampCheck.java:
##########
@@ -0,0 +1,237 @@
+/*
+ * 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.jar;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.nio.file.attribute.FileTime;
+import java.util.Collection;
+import java.util.Enumeration;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+
+import org.apache.maven.api.plugin.Log;
+
+/**
+ * Checks file timestamps in order to determine if anything changed compared to an existing <abbr>JAR</abbr> file.
+ * This class may scan directories, but only if they have not already been visited by {@link FileCollector}.
+ * Note that the latter can occur only if {@link FileCollector} has no {@code PathMatcher}.
+ * Therefore, this class uses no {@code PathMatcher} neither.

Review Comment:
   Done



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3892137468


##########
src/test/java/org/apache/maven/plugins/jar/ArchiveTest.java:
##########
@@ -0,0 +1,264 @@
+/*
+ * 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.jar;
+
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Unit tests for {@link Archive}, focused on the two behaviours that are otherwise only
+ * exercised by integration tests whose outcome depends on the (unspecified) filesystem
+ * directory-iteration order, and therefore pass on some platforms while failing on others.
+ */
+class ArchiveTest {
+
+    /**
+     * Creates an {@code Archive} suitable for a unit test. {@code forceCreation = true} skips the
+     * existing-JAR timestamp check, so the (here {@code null}) logger is never dereferenced.
+     */
+    private static Archive archive(String moduleName, Runtime.Version version, Path directory, boolean isReproducible) {
+        return new Archive(directory.resolve("out.jar"), moduleName, version, directory, true, isReproducible, null);
+    }
+
+    /**
+     * Creates a manifest with the main class attribute set to the given value.
+     *
+     * @param value value of the main class attribute
+     * @return a new manifest with the given attribute value
+     */
+    private static Manifest manifestWithMainClass(String value) {
+        Manifest m = new Manifest();
+        Attributes attributes = m.getMainAttributes();
+        attributes.put(Attributes.Name.MANIFEST_VERSION, "1.0");
+        attributes.put(Attributes.Name.MAIN_CLASS, value);
+        return m;
+    }
+
+    /**
+     * Returns the value of the main class attribute.
+     *
+     * @param m the manifest from which to get the value
+     * @return the main class attribute value, or {@code null} if none
+     */
+    private static Object mainClassOf(Manifest m) {
+        return m.getMainAttributes().get(Attributes.Name.MAIN_CLASS);
+    }
+
+    /**
+     * Verifies that {@link Archive#setMainClass(Manifest)} takes ownership for a module-qualified
+     * {@code "module/Class"} main class.
+     *
+     * Note that the {@code "foo.bar/"} prefix in this test (the module name) is a Maven extension.
+     * The standard <abbr>JAR</abbr> specification accepts only the {@code "foo.MainFile"} class name.
+     */
+    @Test
+    void owningModuleClaimsMainClassAndRemovesItFromManifest() {
+        Archive owner = archive("foo.bar", null, Path.of("."), false);
+        Manifest m = manifestWithMainClass("foo.bar/foo.MainFile");
+        // The owner keeps the main class (emitted via --main-class) ...
+        assertTrue(owner.setMainClass(m));
+        // ... and the raw `module/Class` value is removed from the written manifest.
+        assertNull(mainClassOf(m));
+    }
+
+    /**
+     * Verifies that {@link Archive#setMainClass(Manifest)} does <em>not</em> take ownership fo
+     * a module-qualified {@code "module/Class"} main class when the module name does not match.
+     * Note that the {@code "foo.bar/"} prefix in this test (the module name) is a Maven extension.
+     * The standard <abbr>JAR</abbr> specification accepts only the {@code "foo.MainFile"} class name.
+     */
+    @Test
+    void nonOwningModuleRejectsMainClass() {
+        Archive nonOwner = archive("foo.bar.more", null, Path.of("."), false);
+        Manifest m = manifestWithMainClass("foo.bar/foo.MainFile");
+        assertFalse(nonOwner.setMainClass(m));
+        assertNull(mainClassOf(m));
+    }
+
+    /**
+     * Tests that which module keeps the main class must not depend on processing order.

Review Comment:
   Done



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "desruisseaux (via GitHub)" <gi...@apache.org>.
desruisseaux commented on PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#issuecomment-5394376902

   @seregamorph, @hboutemy: I'm almost done in fixing the issue raised last week, with the help of @ascheman commits (thanks!). I have made one change which I suspect will be highly controversial. If strictly reproducible builds has been requested, the JDK version in the `Created-By` attribute is replaced by `"Maven JAR plugin on unspecified JDK"`. The _"on unspecified JDK"_ is my addition. The intend is to remind users that strictly reproducible builds is causing harm here, and encouraging them to switch to semantically reproducible builds if Maven provides a way to run this verification easily. However, I'm not strongly attached to this addition. If there are objections, I will remove it.


-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Maven4] Migrate from Maven Archiver to standard `jar` tool [maven-jar-plugin]

Posted by "hboutemy (via GitHub)" <gi...@apache.org>.
hboutemy commented on code in PR #508:
URL: https://github.com/apache/maven-jar-plugin/pull/508#discussion_r3855035698


##########
src/main/java/org/apache/maven/plugins/jar/AbstractJarMojo.java:
##########
@@ -207,167 +206,209 @@ protected final Log getLog() {
     protected abstract String getType();
 
     /**
-     * Returns the JAR file to generate, based on an optional classifier.
+     * {@return the scope of dependencies}
+     * It should be {@link PathScope#MAIN_COMPILE} or {@link PathScope#TEST_COMPILE}.
+     * Note that we use compile scope rather than runtime scope because dependencies
+     * cannot appear in {@code requires} statement if they didn't had compile scope.
+     */
+    protected abstract PathScope getDependencyScope();
+
+    /**
+     * {@return the JAR tool to use for archiving the code}
      *
-     * @param basedir the output directory
-     * @param resultFinalName the name of the JAR file
-     * @param classifier an optional classifier
-     * @return the file to generate
+     * @throws MojoException if no JAR tool was found
+     *
+     * @since 4.0.0-beta-2
      */
-    protected Path getJarFile(Path basedir, String resultFinalName, String classifier) {
-        Objects.requireNonNull(basedir, "basedir is not allowed to be null");
-        Objects.requireNonNull(resultFinalName, "finalName is not allowed to be null");
-        String fileName = resultFinalName + (hasClassifier(classifier) ? '-' + classifier : "") + ".jar";
-        return basedir.resolve(fileName);
+    protected ToolProvider getJarTool() throws MojoException {
+        return ToolProvider.findFirst(toolId).orElseThrow(() -> new MojoException("No such \"" + toolId + "\" tool."));
     }
 
     /**
-     * Generates the JAR.
+     * Returns the output time stamp or, as a fallback, the {@code SOURCE_DATE_EPOCH} environment variable.
+     * If the time stamp is expressed in seconds, it is converted to ISO 8601 format. Otherwise it is returned as-is.
      *
-     * @return the path to the created archive file
-     * @throws MojoException in case of an error
+     * @return the time stamp in presumed ISO 8601 format, or {@code null} if none
+     * @throws MojoException if the timestamp looks like a number of seconds but cannot be parsed as such
+     *
+     * @since 4.0.0-beta-2
      */
-    public Path createArchive() throws MojoException {
-        Path basedir = outputDirectory != null
-                ? outputDirectory
-                : Path.of(project.getBuild().getDirectory());
-        String resultFinalName =
-                finalName != null ? finalName : project.getBuild().getFinalName();
-        Path jarFile = getJarFile(basedir, resultFinalName, getClassifier());
-
-        FileSetManager fileSetManager = new FileSetManager();
-        FileSet jarContentFileSet = new FileSet();
-        jarContentFileSet.setDirectory(getClassesDirectory().toAbsolutePath().toString());
-        jarContentFileSet.setIncludes(Arrays.asList(getIncludes()));
-        jarContentFileSet.setExcludes(Arrays.asList(getExcludes()));
-
-        String[] includedFiles = fileSetManager.getIncludedFiles(jarContentFileSet);
-
-        if (detectMultiReleaseJar
-                && Arrays.stream(includedFiles)
-                        .anyMatch(
-                                p -> p.startsWith("META-INF" + File.separatorChar + "versions" + File.separatorChar))) {
-            getLog().debug("Adding 'Multi-Release: true' manifest entry.");
-            archive.addManifestEntry(Attributes.Name.MULTI_RELEASE.toString(), "true");
+    protected String getOutputTimestamp() {

Review Comment:
   why copy/paste https://github.com/apache/maven-archiver/blob/master/src/main/java/org/apache/maven/shared/archiver/MavenArchiver.java#L691
   instead of just calling the existing method?



-- 
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: issues-unsubscribe@maven.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org