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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to