slawekjaranowski commented on code in PR #1080: URL: https://github.com/apache/maven-enforcer/pull/1080#discussion_r4726681971
########## enforcer-rules/src/main/java/org/apache/maven/enforcer/rules/modules/AbstractModuleInfoRule.java: ########## @@ -0,0 +1,370 @@ +/* + * 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.enforcer.rules.modules; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Optional; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Stream; + +import org.apache.maven.artifact.Artifact; +import org.apache.maven.artifact.handler.ArtifactHandler; +import org.apache.maven.enforcer.rule.api.EnforcerRuleException; +import org.apache.maven.enforcer.rules.AbstractStandardEnforcerRule; +import org.apache.maven.model.Plugin; +import org.apache.maven.model.PluginExecution; +import org.apache.maven.project.MavenProject; + +/** + * Base class for rules that inspect the {@code module-info.class} of the project's main output. + * Two output layouts are supported: + * + * <ul> + * <li><b>Classic</b>: the descriptor sits directly in {@code ${project.build.outputDirectory}} + * (one Maven project = one Java module);</li> + * <li><b>Module source hierarchy</b> (Maven 4, POM model 4.1.0): one Maven project compiles + * several modules, each to its own subdirectory + * {@code ${project.build.outputDirectory}/<module-name>/module-info.class}.</li> + * </ul> + * + * Subclasses call {@link #moduleOutputs()} and enforce a specific constraint on each returned + * {@link ModuleOutput}. + */ +public abstract class AbstractModuleInfoRule extends AbstractStandardEnforcerRule { + + /** Base URL of the published rule documentation, for pointing users at the phase binding advice. */ + private static final String DOCUMENTATION_BASE_URL = "https://maven.apache.org/enforcer/enforcer-rules/"; + + /** Descriptor of a multi-release JAR, as {@code META-INF/versions/<n>/module-info.class}. */ + private static final Pattern VERSIONED_MODULE_INFO = + Pattern.compile("META-INF/versions/(\\d+)/module-info\\.class"); + + /** + * Plugins known to inject a module descriptor into the packaged artifact after compilation, by + * {@code groupId:artifactId}. Used only to word a warning more precisely -- never to decide whether + * a rule passes -- so an injector missing from this list costs a less specific hint, nothing more. + */ + private static final List<String> DESCRIPTOR_INJECTING_PLUGINS = + Collections.singletonList("org.moditect:moditect-maven-plugin"); + + /** Goal of a descriptor-injecting plugin, matched alongside the coordinates so a fork is still recognised. */ + private static final String DESCRIPTOR_INJECTING_GOAL = "add-module-info"; + + protected final MavenProject project; + + protected AbstractModuleInfoRule(MavenProject project) { + this.project = project; + } + + /** One compiled output that may form a Java module. */ + protected static final class ModuleOutput { + private final File root; + private final JavaModuleInfo moduleInfo; + + private ModuleOutput(File root, JavaModuleInfo moduleInfo) { + this.root = root; + this.moduleInfo = moduleInfo; + } + + /** The directory the module's classes are compiled to. */ + File root() { + return root; + } + + /** The parsed module descriptor, or {@code null} if {@link #root()} has no {@code module-info.class}. */ + JavaModuleInfo moduleInfo() { + return moduleInfo; + } + } + + /** The directory the main classes (and any {@code module-info.class}) are compiled to. */ + protected File outputDirectory() { + return new File(project.getBuild().getOutputDirectory()); + } + + /** + * Discover the project's module outputs. + * + * <p>If the output directory itself holds a {@code module-info.class} (classic layout), exactly + * that one output is returned. Otherwise, if at least one first-level subdirectory holds a + * {@code module-info.class} (Maven 4 module source hierarchy), every first-level + * subdirectory is returned as one output each — including non-modular ones, whose + * {@link ModuleOutput#moduleInfo()} is {@code null}, so rules can flag them. Failing both, the + * output directory is returned as a single non-modular output. + * + * @throws EnforcerRuleException if a {@code module-info.class} exists but cannot be read + */ + protected List<ModuleOutput> moduleOutputs() throws EnforcerRuleException { + File outputDirectory = outputDirectory(); + JavaModuleInfo topLevel = readModuleInfo(outputDirectory); + if (topLevel != null) { + return Collections.singletonList(new ModuleOutput(outputDirectory, topLevel)); + } + File[] subdirectories = outputDirectory.listFiles(File::isDirectory); + if (subdirectories != null) { + Arrays.sort(subdirectories); + List<ModuleOutput> outputs = new ArrayList<>(); + boolean modular = false; + for (File subdirectory : subdirectories) { + JavaModuleInfo moduleInfo = readModuleInfo(subdirectory); + modular |= moduleInfo != null; + outputs.add(new ModuleOutput(subdirectory, moduleInfo)); + } + if (modular) { + getLog().debug("Detected module source hierarchy layout below " + outputDirectory + " (" + + outputs.size() + " module output(s))"); + return outputs; + } + } + // Nothing in the output directory. A plugin such as Moditect injects the descriptor into the + // packaged artifact and never writes target/classes, so the artifact is the only place left to + // look. Only reached for the classic one-module layout: a module source hierarchy returns above, + // since one main artifact cannot stand for several modules. + JavaModuleInfo packaged = readPackagedArtifactModuleInfo(); + if (packaged != null) { + getLog().debug("No module-info.class below " + outputDirectory + + ", using the descriptor carried by the packaged artifact"); + } + return Collections.singletonList(new ModuleOutput(outputDirectory, packaged)); + } + + /** + * Read the module descriptor from the project's packaged artifact, for projects whose descriptor is + * injected after compilation. Prefers the root {@code module-info.class} and otherwise takes the + * highest-versioned multi-release descriptor. + * + * @return the parsed descriptor, or {@code null} when there is no artifact to inspect (the rule runs + * before {@code package}), it carries no descriptor, or it cannot be read as an archive -- + * an unreadable artifact therefore keeps the stricter outcome + */ + private JavaModuleInfo readPackagedArtifactModuleInfo() throws EnforcerRuleException { + Artifact artifact = project.getArtifact(); + File file = artifact != null ? artifact.getFile() : null; + if (file == null || !file.isFile()) { + getLog().debug("No packaged artifact available to inspect for a module descriptor"); + return null; + } + try (JarFile jar = new JarFile(file)) { + JarEntry entry = descriptorEntry(jar); + if (entry == null) { + return null; + } + requireJava9Runtime(); + try (InputStream in = jar.getInputStream(entry)) { + return JavaModuleInfoReader.read(in); + } Review Comment: A descriptor in the packaged artifact that cannot be parsed is turned into `null` by the outer `catch`. Only `requireExplicitModules` fails on `null`. `requireMinimalExports` and `banUnjustifiedOpens` just pass, for example when the descriptor is newer than the running JVM. A descriptor in the output directory fails in `readModuleInfo()` instead. Suggest failing here the same way, and keeping the outer `catch` only for a file that cannot be opened as a JAR: ```suggestion try (InputStream in = jar.getInputStream(entry)) { return JavaModuleInfoReader.read(in); } catch (IOException e) { throw new EnforcerRuleException("Failed to read " + entry.getName() + " from " + file + ": " + e.getMessage(), e); } ``` -- 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]
