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: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
