This is an automated email from the ASF dual-hosted git repository.
gnodet pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/maven.git
The following commit(s) were added to refs/heads/master by this push:
new 6ebe1281ed feat: introduce maven-plugin-mixin for compile-time Maven 4
plugin descriptor generation
6ebe1281ed is described below
commit 6ebe1281eded2706aa048582ee29a1aae71b8638
Author: Guillaume Nodet <[email protected]>
AuthorDate: Thu Nov 12 17:00:52 2026 +0100
feat: introduce maven-plugin-mixin for compile-time Maven 4 plugin
descriptor generation
- Introduces `impl/maven-plugin-mixin`: a Maven 4 mixin that bundles a JSR
269 annotation processor (`MojoDescriptorProcessor`) generating plugin
descriptors at compile time, with no dependency on `maven-plugin-plugin` or
`maven-plugin-tools`
- Processor reads real `org.apache.maven.api.plugin.annotations.*` types
and generates: `META-INF/maven/plugin.xml` (via `PluginDescriptorStaxWriter`),
a DI factory class per mojo (picked up by `DiIndexProcessor`), and
`HelpMojo.java` with colored output support
- Mixin (`mixin.xml`, classifier `mixin`) configures
`maven-compiler-plugin` with `annotationProcessorPaths` and injects plugin
coordinates via `-A` options; consuming projects declare only the mixin, not
individual processor deps
- Handles incremental builds by merging mojos from a pre-existing
`plugin.xml` before rewriting, so partial recompiles produce a complete
descriptor
- Fixes `BuildPlanExecutor`: V4 mojo dependency ordering now reads from the
`resolutions` list in the plugin descriptor (populated via `@Resolution`)
rather than `dependencyResolution`, aligning with how V4 plugins express their
resolution needs
- 14 unit tests in `MojoDescriptorProcessorTest` using
`javax.tools.JavaCompiler` in-process; IT `MavenITgh13644PluginProcessorTest`
builds a plugin with the mixin, runs a consumer, and verifies `help` goal
colored output
Closes #13644
---
.../internal/concurrent/BuildPlanExecutor.java | 11 +-
impl/maven-plugin-mixin/pom.xml | 138 +++
.../src/main/java/module-info.java | 31 +
.../plugin/processor/MojoDescriptorProcessor.java | 856 ++++++++++++++++++
impl/maven-plugin-mixin/src/main/mixin/mixin.xml | 154 ++++
.../services/javax.annotation.processing.Processor | 17 +
impl/maven-plugin-mixin/src/site/markdown/index.md | 126 +++
impl/maven-plugin-mixin/src/site/markdown/usage.md | 121 +++
impl/maven-plugin-mixin/src/site/site.xml | 38 +
.../processor/MojoDescriptorProcessorTest.java | 999 +++++++++++++++++++++
impl/pom.xml | 1 +
.../it/MavenITgh13644PluginProcessorTest.java | 105 +++
.../gh-13644-plugin-processor/plugin/pom.xml | 23 +
.../gh-13644-plugin-processor/consumer/pom.xml | 29 +
.../org/apache/maven/its/gh13644/TouchMojo.java | 63 ++
src/graph/ReactorGraph.java | 2 +-
16 files changed, 2711 insertions(+), 3 deletions(-)
diff --git
a/impl/maven-core/src/main/java/org/apache/maven/lifecycle/internal/concurrent/BuildPlanExecutor.java
b/impl/maven-core/src/main/java/org/apache/maven/lifecycle/internal/concurrent/BuildPlanExecutor.java
index 36881a7bde..b950f9e1b2 100644
---
a/impl/maven-core/src/main/java/org/apache/maven/lifecycle/internal/concurrent/BuildPlanExecutor.java
+++
b/impl/maven-core/src/main/java/org/apache/maven/lifecycle/internal/concurrent/BuildPlanExecutor.java
@@ -219,6 +219,14 @@ private List<Lifecycle> processedLifecycles() {
return cached;
}
+ private static boolean requiresDependencyOrdering(MojoDescriptor
descriptor) {
+ if (descriptor.isV4Api()) {
+ return
!descriptor.getMojoDescriptorV4().getResolutions().isEmpty();
+ }
+ return descriptor.getDependencyCollectionRequired() != null
+ || descriptor.getDependencyResolutionRequired() != null;
+ }
+
public void execute(MavenSession session, ReactorContext reactorContext,
List<TaskSegment> taskSegments)
throws ExecutionException, InterruptedException {
try (BuildContext ctx = new BuildContext(session, reactorContext,
taskSegments)) {
@@ -790,8 +798,7 @@ private void plan() {
.filter(executionStep -> executionStep.phase !=
null)
.forEach(executionStep ->
executionStep.executions().forEach(execution -> {
MojoDescriptor descriptor =
execution.getMojoDescriptor();
- if
(descriptor.getDependencyCollectionRequired() != null
- ||
descriptor.getDependencyResolutionRequired() != null) {
+ if (requiresDependencyOrdering(descriptor)) {
for (MavenProject upstream :
plan.getAllProjects().get(step.project)) {
plan.step(upstream, AFTER +
PACKAGE).ifPresent(executionStep::executeAfter);
diff --git a/impl/maven-plugin-mixin/pom.xml b/impl/maven-plugin-mixin/pom.xml
new file mode 100644
index 0000000000..6f0c546126
--- /dev/null
+++ b/impl/maven-plugin-mixin/pom.xml
@@ -0,0 +1,138 @@
+<?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/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+
+ <parent>
+ <groupId>org.apache.maven</groupId>
+ <artifactId>maven-impl-modules</artifactId>
+ <version>4.2.0-SNAPSHOT</version>
+ </parent>
+
+ <artifactId>maven-plugin-mixin</artifactId>
+ <name>Maven Plugin Mixin</name>
+ <description>Mixin and annotation processor for Maven 4 plugin projects. The
mixin provides
+ zero-config plugin descriptor generation at compile time from
@Mojo-annotated classes.</description>
+
+ <properties>
+ <javaModuleName>org.apache.maven.plugin.processor</javaModuleName>
+ <maven.compiler.proc>none</maven.compiler.proc>
+ </properties>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.apache.maven</groupId>
+ <artifactId>maven-api-core</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.maven</groupId>
+ <artifactId>maven-api-plugin</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.maven</groupId>
+ <artifactId>maven-support</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
+
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-resources-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>filter-mixin</id>
+ <goals>
+ <goal>copy-resources</goal>
+ </goals>
+ <phase>process-resources</phase>
+ <configuration>
+
<outputDirectory>${project.build.directory}/mixin</outputDirectory>
+ <resources>
+ <resource>
+ <directory>src/main/mixin</directory>
+ <filtering>true</filtering>
+ </resource>
+ </resources>
+ <useDefaultDelimiters>false</useDefaultDelimiters>
+ <delimiters>
+ <delimiter>@</delimiter>
+ </delimiters>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-jar-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>jar-before-test</id>
+ <goals>
+ <goal>jar</goal>
+ </goals>
+ <phase>process-test-classes</phase>
+ </execution>
+ <execution>
+ <id>default-jar</id>
+ <phase>none</phase>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-surefire-plugin</artifactId>
+ <configuration>
+ <systemPropertyVariables>
+
<processor.worktree>${maven.multiModuleProjectDirectory}</processor.worktree>
+ <processor.version>${project.version}</processor.version>
+ </systemPropertyVariables>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>build-helper-maven-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>attach-mixin</id>
+ <goals>
+ <goal>attach-artifact</goal>
+ </goals>
+ <phase>package</phase>
+ <configuration>
+ <artifacts>
+ <artifact>
+ <file>${project.build.directory}/mixin/mixin.xml</file>
+ <type>pom</type>
+ <classifier>mixin</classifier>
+ </artifact>
+ </artifacts>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+ </build>
+</project>
diff --git a/impl/maven-plugin-mixin/src/main/java/module-info.java
b/impl/maven-plugin-mixin/src/main/java/module-info.java
new file mode 100644
index 0000000000..f81186bc9d
--- /dev/null
+++ b/impl/maven-plugin-mixin/src/main/java/module-info.java
@@ -0,0 +1,31 @@
+/*
+ * 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.
+ */
+
+module org.apache.maven.plugin.processor {
+ exports org.apache.maven.plugin.processor;
+
+ requires java.compiler;
+ requires java.xml;
+ requires org.apache.maven.api;
+ requires org.apache.maven.api.plugin.descriptor;
+ requires org.apache.maven.support;
+
+ provides javax.annotation.processing.Processor with
+ org.apache.maven.plugin.processor.MojoDescriptorProcessor;
+}
diff --git
a/impl/maven-plugin-mixin/src/main/java/org/apache/maven/plugin/processor/MojoDescriptorProcessor.java
b/impl/maven-plugin-mixin/src/main/java/org/apache/maven/plugin/processor/MojoDescriptorProcessor.java
new file mode 100644
index 0000000000..9114df4527
--- /dev/null
+++
b/impl/maven-plugin-mixin/src/main/java/org/apache/maven/plugin/processor/MojoDescriptorProcessor.java
@@ -0,0 +1,856 @@
+/*
+ * 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.plugin.processor;
+
+import javax.annotation.processing.AbstractProcessor;
+import javax.annotation.processing.RoundEnvironment;
+import javax.annotation.processing.SupportedAnnotationTypes;
+import javax.annotation.processing.SupportedOptions;
+import javax.lang.model.SourceVersion;
+import javax.lang.model.element.Element;
+import javax.lang.model.element.ElementKind;
+import javax.lang.model.element.ExecutableElement;
+import javax.lang.model.element.Modifier;
+import javax.lang.model.element.TypeElement;
+import javax.lang.model.element.VariableElement;
+import javax.lang.model.type.DeclaredType;
+import javax.lang.model.type.TypeKind;
+import javax.lang.model.type.TypeMirror;
+import javax.tools.Diagnostic;
+import javax.tools.StandardLocation;
+import javax.xml.stream.XMLStreamException;
+
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.io.Writer;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.function.Consumer;
+
+import org.apache.maven.api.plugin.annotations.After;
+import org.apache.maven.api.plugin.annotations.Execute;
+import org.apache.maven.api.plugin.annotations.Mojo;
+import org.apache.maven.api.plugin.annotations.Resolution;
+import org.apache.maven.api.plugin.descriptor.AfterLink;
+import org.apache.maven.api.plugin.descriptor.MojoDescriptor;
+import org.apache.maven.api.plugin.descriptor.PluginDescriptor;
+import org.apache.maven.plugin.descriptor.io.PluginDescriptorStaxReader;
+import org.apache.maven.plugin.descriptor.io.PluginDescriptorStaxWriter;
+
+/**
+ * JSR 269 annotation processor that generates Maven plugin descriptors
({@code META-INF/maven/plugin.xml})
+ * and DI factory classes at compile time from {@link Mojo @Mojo}-annotated
classes.
+ *
+ * <p>Plugin coordinates are read from compiler {@code -A} options, typically
provided by the
+ * {@code maven-plugin-mixin}.
+ *
+ * @since 4.2.0
+ */
+@SupportedAnnotationTypes("org.apache.maven.api.plugin.annotations.Mojo")
+@SupportedOptions({
+ MojoDescriptorProcessor.OPT_GROUP_ID,
+ MojoDescriptorProcessor.OPT_ARTIFACT_ID,
+ MojoDescriptorProcessor.OPT_VERSION,
+ MojoDescriptorProcessor.OPT_GOAL_PREFIX,
+ MojoDescriptorProcessor.OPT_NAME
+})
+public class MojoDescriptorProcessor extends AbstractProcessor {
+
+ static final String OPT_GROUP_ID = "maven.plugin.groupId";
+ static final String OPT_ARTIFACT_ID = "maven.plugin.artifactId";
+ static final String OPT_VERSION = "maven.plugin.version";
+ static final String OPT_GOAL_PREFIX = "maven.plugin.goalPrefix";
+ static final String OPT_NAME = "maven.plugin.name";
+
+ private final Map<String, TypeElement> mojoElements = new
LinkedHashMap<>();
+ private final Set<String> generatedFactoryNames = new LinkedHashSet<>();
+ private String[] resolvedCoordinates;
+ private boolean coordinateErrorEmitted = false;
+ /** Guards against re-generating {@code HelpMojo.java} in subsequent
processing rounds. */
+ private boolean helpMojoGenerated = false;
+ /** Guards against re-generating {@code plugin.xml} after HelpMojo
triggers a new round. */
+ private boolean pluginXmlGenerated = false;
+
+ @Override
+ public SourceVersion getSupportedSourceVersion() {
+ return SourceVersion.latestSupported();
+ }
+
+ @Override
+ public boolean process(Set<? extends TypeElement> annotations,
RoundEnvironment roundEnv) {
+ for (TypeElement annotation : annotations) {
+ for (Element element :
roundEnv.getElementsAnnotatedWith(annotation)) {
+ if (!(element instanceof TypeElement typeElement)) {
+ continue;
+ }
+ String fqn = typeElement.getQualifiedName().toString();
+ if (generatedFactoryNames.contains(fqn)) {
+ continue;
+ }
+ if (typeElement.getKind() == ElementKind.INTERFACE) {
+ error("@Mojo must not be placed on an interface", element);
+ continue;
+ }
+ if (typeElement.getModifiers().contains(Modifier.ABSTRACT)) {
+ error("@Mojo must not be placed on an abstract class",
element);
+ continue;
+ }
+ if (!mojoElements.containsKey(fqn)) {
+ mojoElements.put(fqn, typeElement);
+ String[] coords = resolveCoordinates();
+ if (coords != null) {
+ try {
+ generateFactory(typeElement, coords);
+ } catch (IOException e) {
+ error("Failed to generate factory for " + fqn, e);
+ }
+ }
+ }
+ }
+ }
+ // Generate HelpMojo eagerly (before processingOver) so that the next
annotation-
+ // processing round sees HelpMojoMojoFactory's @Named annotation and
DiIndexProcessor
+ // can index it before writing the DI index file in processingOver().
+ if (!roundEnv.processingOver() && !mojoElements.isEmpty()) {
+ String[] coords = resolveCoordinates();
+ if (coords != null) {
+ try {
+ generateHelpMojo(coords);
+ } catch (IOException e) {
+ error("Failed to generate HelpMojo", e);
+ }
+ }
+ }
+ if (roundEnv.processingOver() && !mojoElements.isEmpty()) {
+ String[] coords = resolveCoordinates();
+ if (coords != null) {
+ try {
+ writePluginXml(coords);
+ } catch (IOException e) {
+ error("Failed to generate plugin.xml", e);
+ }
+ }
+ }
+ return false;
+ }
+
+ String[] resolveCoordinates() {
+ if (resolvedCoordinates != null) {
+ return resolvedCoordinates;
+ }
+ String groupId = getOption(OPT_GROUP_ID);
+ String artifactId = getOption(OPT_ARTIFACT_ID);
+ String version = getOption(OPT_VERSION);
+ String goalPrefix = getOption(OPT_GOAL_PREFIX);
+ String name = getOption(OPT_NAME);
+ if (isBlank(goalPrefix)) {
+ goalPrefix = deriveGoalPrefix(artifactId);
+ }
+ if (isBlank(name)) {
+ name = artifactId;
+ }
+ if (isBlank(groupId) || isBlank(artifactId) || isBlank(version)) {
+ if (!coordinateErrorEmitted) {
+ coordinateErrorEmitted = true;
+ error("Could not determine plugin coordinates. "
+ + "Supply -Amaven.plugin.groupId,
-Amaven.plugin.artifactId and "
+ + "-Amaven.plugin.version via the
maven-plugin-mixin.");
+ }
+ return null;
+ }
+ resolvedCoordinates = new String[] {groupId, artifactId, version,
goalPrefix, name};
+ return resolvedCoordinates;
+ }
+
+ private String getOption(String key) {
+ return processingEnv.getOptions().get(key);
+ }
+
+ private void writePluginXml(String[] coords) throws IOException {
+ if (pluginXmlGenerated) {
+ return;
+ }
+ List<MojoDescriptor> mojos = new ArrayList<>();
+ for (TypeElement mojoType : mojoElements.values()) {
+ if (mojoType == null) {
+ // null sentinel marks generated classes (e.g. HelpMojo) that
have no TypeElement
+ continue;
+ }
+ MojoDescriptor mojo = buildMojoDescriptor(mojoType);
+ if (mojo != null) {
+ mojos.add(mojo);
+ }
+ }
+ mojos.add(buildHelpMojoDescriptor(coords));
+ // Merge with existing plugin.xml for incremental compilation support:
+ // keep mojos from a previous compilation that were not reprocessed in
this round.
+ Set<String> currentGoals = new LinkedHashSet<>();
+ for (MojoDescriptor m : mojos) {
+ currentGoals.add(m.getGoal());
+ }
+ try {
+ var existing = processingEnv
+ .getFiler()
+ .getResource(StandardLocation.CLASS_OUTPUT, "",
"META-INF/maven/plugin.xml");
+ try (var r = existing.openReader(false)) {
+ PluginDescriptor prev = new
PluginDescriptorStaxReader().read(r);
+ for (MojoDescriptor prevMojo : prev.getMojos()) {
+ if (!currentGoals.contains(prevMojo.getGoal())) {
+ mojos.add(prevMojo);
+ }
+ }
+ }
+ } catch (Exception ex) {
+ // No existing plugin.xml, read not supported, or parse error —
+ // expected during clean builds and in test harnesses
+ }
+ PluginDescriptor descriptor = PluginDescriptor.newBuilder(true)
+ .name(coords[4])
+ .groupId(coords[0])
+ .artifactId(coords[1])
+ .version(coords[2])
+ .goalPrefix(coords[3])
+ .mojos(mojos)
+ .build();
+ try (Writer w = processingEnv
+ .getFiler()
+ .createResource(StandardLocation.CLASS_OUTPUT, "",
"META-INF/maven/plugin.xml")
+ .openWriter()) {
+ PluginDescriptorStaxWriter writer = new
PluginDescriptorStaxWriter();
+ writer.setNamespace("http://maven.apache.org/PLUGIN/2.0.0");
+ writer.write(w, descriptor);
+ } catch (XMLStreamException e) {
+ throw new IOException("Failed to write plugin descriptor", e);
+ }
+ note("Generated META-INF/maven/plugin.xml with " + mojos.size() + "
mojo(s)");
+ pluginXmlGenerated = true;
+ }
+
+ /**
+ * Builds a synthetic {@link MojoDescriptor} for the generated {@code
HelpMojo}.
+ * Since {@code HelpMojo} is generated by this processor, it cannot be
built from a
+ * {@code TypeElement}. We therefore add its descriptor synthetically so
that {@code help}
+ * is registered in {@code plugin.xml} and Maven can find the goal at
runtime.
+ */
+ private MojoDescriptor buildHelpMojoDescriptor(String[] coords) {
+ String pkg = mojoElements.values().stream()
+ .filter(te -> te != null)
+ .map(this::getPackageName)
+ .findFirst()
+ .orElse("");
+ String impl = pkg.isEmpty() ? "HelpMojo" : pkg + ".HelpMojo";
+
+ List<org.apache.maven.api.plugin.descriptor.Parameter> params =
List.of(
+
org.apache.maven.api.plugin.descriptor.Parameter.newBuilder(true)
+ .name("detail")
+ .type("boolean")
+ .expression("${detail}")
+ .defaultValue("false")
+ .description("If true, display all settable properties
for each goal.")
+ .build(),
+
org.apache.maven.api.plugin.descriptor.Parameter.newBuilder(true)
+ .name("goal")
+ .type("java.lang.String")
+ .expression("${goal}")
+ .description(
+ "The name of the goal for which to show help.
If unspecified, all goals will be displayed.")
+ .build(),
+
org.apache.maven.api.plugin.descriptor.Parameter.newBuilder(true)
+ .name("indentSize")
+ .type("int")
+ .expression("${indentSize}")
+ .defaultValue("2")
+ .description("The number of spaces per indentation
level, should be positive.")
+ .build());
+
+ return MojoDescriptor.newBuilder(true)
+ .goal("help")
+ .implementation(impl)
+ .projectRequired(false)
+ .description("Display help information on " + coords[1] + ".
Call mvn " + coords[3]
+ + ":help -Ddetail=true -Dgoal=<goal-name> to display
parameter details.")
+ .parameters(params)
+ .build();
+ }
+
+ private MojoDescriptor buildMojoDescriptor(TypeElement mojoType) {
+ Mojo mojoAnn = mojoType.getAnnotation(Mojo.class);
+ if (mojoAnn == null || mojoAnn.name().isEmpty()) {
+ if (mojoAnn != null) {
+ error("@Mojo.name() must not be empty", mojoType);
+ }
+ return null;
+ }
+ JavadocInfo doc =
parseJavadoc(processingEnv.getElementUtils().getDocComment(mojoType));
+ MojoDescriptor.Builder b = MojoDescriptor.newBuilder(true)
+ .goal(mojoAnn.name())
+ .implementation(
+
processingEnv.getElementUtils().getBinaryName(mojoType).toString())
+ .projectRequired(mojoAnn.projectRequired())
+ .onlineRequired(mojoAnn.onlineRequired())
+ .aggregator(mojoAnn.aggregator());
+ set(b::phase, mojoAnn.defaultPhase());
+ set(b::configurator, mojoAnn.configurator());
+ set(b::dependencyResolution, mojoAnn.dependencyResolutionPathScopes());
+ if (mojoAnn.dependencyCollection()) {
+ b.dependencyCollection("true");
+ }
+ set(b::description, doc.description);
+ set(b::since, doc.since);
+ set(b::deprecated, doc.deprecated);
+ Execute exec = mojoType.getAnnotation(Execute.class);
+ if (exec != null) {
+ set(b::executePhase, exec.phase());
+ set(b::executeGoal, exec.goal());
+ set(b::executeLifecycle, exec.lifecycle());
+ }
+ b.parameters(collectParameters(mojoType));
+ b.resolutions(collectResolutions(mojoType));
+ b.afterLinks(collectAfterLinks(mojoType));
+ return b.build();
+ }
+
+ private List<org.apache.maven.api.plugin.descriptor.Parameter>
collectParameters(TypeElement mojoType) {
+ List<org.apache.maven.api.plugin.descriptor.Parameter> result = new
ArrayList<>();
+ Set<String> seen = new LinkedHashSet<>();
+ for (TypeElement cur = mojoType; cur != null && !isObject(cur); cur =
superType(cur)) {
+ for (Element enclosed : cur.getEnclosedElements()) {
+ if (enclosed.getKind() != ElementKind.FIELD &&
enclosed.getKind() != ElementKind.METHOD) {
+ continue;
+ }
+ org.apache.maven.api.plugin.annotations.Parameter ann =
+
enclosed.getAnnotation(org.apache.maven.api.plugin.annotations.Parameter.class);
+ if (ann == null) {
+ continue;
+ }
+ String name;
+ if (!ann.name().isEmpty()) {
+ name = ann.name();
+ } else if (enclosed.getKind() == ElementKind.METHOD) {
+ name =
deriveParameterName(enclosed.getSimpleName().toString());
+ } else {
+ name = enclosed.getSimpleName().toString();
+ }
+ if (!seen.add(name)) {
+ continue;
+ }
+ TypeMirror rawType;
+ if (enclosed.getKind() == ElementKind.FIELD) {
+ rawType = enclosed.asType();
+ } else {
+ ExecutableElement method = (ExecutableElement) enclosed;
+ rawType = method.getParameters().isEmpty()
+ ? method.getReturnType()
+ : method.getParameters().get(0).asType();
+ }
+ String type =
processingEnv.getTypeUtils().erasure(rawType).toString();
+ String expression = ann.property();
+ if (!expression.isEmpty() && !expression.startsWith("${")) {
+ expression = "${" + expression + "}";
+ }
+ JavadocInfo doc =
parseJavadoc(processingEnv.getElementUtils().getDocComment(enclosed));
+ org.apache.maven.api.plugin.descriptor.Parameter.Builder pb =
+
org.apache.maven.api.plugin.descriptor.Parameter.newBuilder(true)
+ .name(name)
+ .type(type)
+ .required(ann.required())
+ .editable(!ann.readonly());
+ set(pb::alias, ann.alias());
+ set(pb::expression, expression);
+ set(pb::defaultValue, ann.defaultValue());
+ set(pb::description, doc.description);
+ set(pb::since, doc.since);
+ set(pb::deprecated, doc.deprecated);
+ result.add(pb.build());
+ }
+ }
+ return result;
+ }
+
+ private List<org.apache.maven.api.plugin.descriptor.Resolution>
collectResolutions(TypeElement mojoType) {
+ List<org.apache.maven.api.plugin.descriptor.Resolution> result = new
ArrayList<>();
+ Set<String> seen = new LinkedHashSet<>();
+ for (TypeElement cur = mojoType; cur != null && !isObject(cur); cur =
superType(cur)) {
+ for (Element enclosed : cur.getEnclosedElements()) {
+ if (enclosed.getKind() != ElementKind.FIELD) {
+ continue;
+ }
+ Resolution ann = enclosed.getAnnotation(Resolution.class);
+ if (ann == null) {
+ continue;
+ }
+ String fieldName = enclosed.getSimpleName().toString();
+ if (!seen.add(fieldName)) {
+ continue;
+ }
+ org.apache.maven.api.plugin.descriptor.Resolution.Builder rb =
+
org.apache.maven.api.plugin.descriptor.Resolution.newBuilder(true)
+ .field(fieldName);
+ set(rb::pathScope, ann.pathScope());
+ set(rb::requestType, ann.requestType());
+ result.add(rb.build());
+ }
+ }
+ return result;
+ }
+
+ private List<AfterLink> collectAfterLinks(TypeElement mojoType) {
+ After[] afters = mojoType.getAnnotationsByType(After.class);
+ if (afters.length == 0) {
+ return List.of();
+ }
+ List<AfterLink> result = new ArrayList<>(afters.length);
+ for (After a : afters) {
+ AfterLink.Builder ab =
+
AfterLink.newBuilder(true).phase(a.phase()).type(a.type().name());
+ set(ab::scope, a.scope());
+ result.add(ab.build());
+ }
+ return result;
+ }
+
+ private void generateFactory(TypeElement mojoType, String[] coords) throws
IOException {
+ Mojo mojoAnn = mojoType.getAnnotation(Mojo.class);
+ if (mojoAnn == null || mojoAnn.name().isEmpty()) {
+ return;
+ }
+ String fqn = mojoType.getQualifiedName().toString();
+ String pkg = getPackageName(mojoType);
+ String simpleName = mojoType.getSimpleName().toString();
+ // For nested classes, compute the relative class name within the
package (e.g. "Mojos.TouchMojo")
+ String relativeClassName = pkg.isEmpty() ? fqn :
fqn.substring(pkg.length() + 1);
+ String factoryName = simpleName + "MojoFactory";
+ String factoryFqn = pkg.isEmpty() ? factoryName : pkg + "." +
factoryName;
+ String roleHint = coords[0] + ":" + coords[1] + ":" + coords[2] + ":"
+ mojoAnn.name();
+
+ List<ExecutableElement> ctors = mojoType.getEnclosedElements().stream()
+ .filter(e -> e.getKind() == ElementKind.CONSTRUCTOR)
+ .map(ExecutableElement.class::cast)
+ .filter(c -> !c.getModifiers().contains(Modifier.PRIVATE))
+ .toList();
+
+ try (PrintWriter pw = new PrintWriter(
+ processingEnv.getFiler().createSourceFile(factoryFqn,
mojoType).openWriter())) {
+ if (!pkg.isEmpty()) {
+ pw.println("package " + pkg + ";");
+ pw.println();
+ }
+ pw.println("@org.apache.maven.api.di.Named(\"" + roleHint + "\")");
+ pw.println("public class " + factoryName + " extends " +
relativeClassName + " {");
+ for (ExecutableElement ctor : ctors) {
+ if (ctor.getParameters().isEmpty()) {
+ continue;
+ }
+ pw.print(" public " + factoryName + "(");
+ StringBuilder args = new StringBuilder();
+ for (int i = 0; i < ctor.getParameters().size(); i++) {
+ VariableElement p = ctor.getParameters().get(i);
+ if (i > 0) {
+ pw.print(", ");
+ args.append(", ");
+ }
+ pw.print(p.asType() + " " + p.getSimpleName());
+ args.append(p.getSimpleName());
+ }
+ List<? extends TypeMirror> thrown = ctor.getThrownTypes();
+ if (!thrown.isEmpty()) {
+ pw.print(") throws ");
+ pw.print(thrown.stream()
+ .map(Object::toString)
+ .reduce((a, b) -> a + ", " + b)
+ .orElse(""));
+ pw.println(" { super(" + args + "); }");
+ } else {
+ pw.println(") { super(" + args + "); }");
+ }
+ }
+ pw.println("}");
+ }
+ generatedFactoryNames.add(factoryFqn);
+ note("Generated factory " + factoryFqn);
+ }
+
+ // @formatter:off
+ private static final String HELP_MOJO_TEMPLATE = """
+ %1$simport org.apache.maven.api.Session;
+ 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.Mojo;
+ import org.apache.maven.api.plugin.annotations.Parameter;
+ import org.apache.maven.api.plugin.descriptor.MojoDescriptor;
+ import org.apache.maven.api.plugin.descriptor.PluginDescriptor;
+ import org.apache.maven.api.services.MessageBuilder;
+ import org.apache.maven.api.services.MessageBuilderFactory;
+ import org.apache.maven.api.services.xml.PluginXmlFactory;
+ import org.apache.maven.api.services.xml.XmlReaderException;
+ import java.io.IOException;
+ import java.io.InputStream;
+ import java.util.List;
+
+ /**
+ * Display help information on %2$s.<br>
+ * Call <code>mvn %3$s:help -Ddetail=true
-Dgoal=<goal-name></code>
+ * to display parameter details.
+ *
+ * @since %4$s
+ */
+ @Mojo(name = "help", projectRequired = false)
+ public class HelpMojo implements org.apache.maven.api.plugin.Mojo {
+
+ @Inject
+ private Session session;
+
+ @Inject
+ private Log logger;
+
+ /** If {@code true}, display all settable properties for each
goal. */
+ @Parameter(property = "detail", defaultValue = "false")
+ private boolean detail;
+
+ /** The name of the goal for which to show help. If
unspecified, all goals will be displayed. */
+ @Parameter(property = "goal")
+ private String goal;
+
+ /** The number of spaces per indentation level, should be
positive. */
+ @Parameter(property = "indentSize", defaultValue = "2")
+ private int indentSize;
+
+ private static final String PLUGIN_XML_PATH =
"/META-INF/maven/plugin.xml";
+
+ @Override
+ public void execute() throws MojoException {
+ if (indentSize <= 0) {
+ logger.warn("The parameter 'indentSize' should be
positive, using '2' as default.");
+ indentSize = 2;
+ }
+ MessageBuilderFactory mbf =
session.getService(MessageBuilderFactory.class);
+ int lineLength = mbf.getTerminalWidth();
+ if (lineLength <= 0) {
+ lineLength = 80;
+ }
+ PluginDescriptor descriptor = loadDescriptor();
+ MessageBuilder mb = mbf.builder();
+ String name = descriptor.getName();
+ String ver = descriptor.getVersion();
+ String id = descriptor.getGroupId() + ":" +
descriptor.getArtifactId() + ":" + ver;
+ String title = (name != null && !name.isEmpty() &&
!name.contains(id))
+ ? name + " " + ver : (name != null &&
!name.isEmpty() ? name : id);
+ mb.strong(title).newline();
+ if (descriptor.getDescription() != null) {
+ appendWrapped(mb, descriptor.getDescription(), 1,
lineLength);
+ }
+ mb.newline();
+ List<MojoDescriptor> mojos = descriptor.getMojos();
+ if (goal == null || goal.isEmpty()) {
+ mb.a("This plugin has
").strong(String.valueOf(mojos.size()))
+ .a(mojos.size() > 1 ? " goals:" : "
goal:").newline();
+ mb.newline();
+ }
+ for (MojoDescriptor mojo : mojos) {
+ writeGoal(mb, descriptor.getGoalPrefix(), mojo,
lineLength);
+ }
+ if (logger.isInfoEnabled()) {
+ logger.info(mb.build());
+ }
+ }
+
+ private PluginDescriptor loadDescriptor() throws MojoException
{
+ try (InputStream is =
getClass().getResourceAsStream(PLUGIN_XML_PATH)) {
+ if (is == null) {
+ throw new MojoException("Could not find plugin
descriptor at " + PLUGIN_XML_PATH);
+ }
+ return
session.getService(PluginXmlFactory.class).read(is);
+ } catch (IOException | XmlReaderException e) {
+ throw new MojoException("Failed to parse " +
PLUGIN_XML_PATH + ": " + e.getMessage(), e);
+ }
+ }
+
+ private void writeGoal(MessageBuilder mb, String gp,
MojoDescriptor mojo, int lineLength) {
+ if (goal != null && !goal.isEmpty() &&
!goal.equals(mojo.getGoal())) {
+ return;
+ }
+ mb.mojo(gp + ":" + mojo.getGoal()).newline();
+ if (mojo.getDeprecated() != null &&
!mojo.getDeprecated().isEmpty()) {
+ mb.a(indent(1)).warning("Deprecated.").a("
").a(mojo.getDeprecated()).newline();
+ if (detail && mojo.getDescription() != null) {
+ mb.newline();
+ appendWrapped(mb, mojo.getDescription(), 1,
lineLength);
+ }
+ } else if (mojo.getDescription() != null) {
+ appendWrapped(mb, mojo.getDescription(), 1,
lineLength);
+ }
+ mb.newline();
+ if (detail) {
+ List<org.apache.maven.api.plugin.descriptor.Parameter>
params = mojo.getParameters()
+ .stream()
+
.filter(org.apache.maven.api.plugin.descriptor.Parameter::isEditable)
+ .toList();
+ if (!params.isEmpty()) {
+ mb.a(indent(1)).strong("Available
parameters:").newline();
+ mb.newline();
+ params.forEach(p -> writeParameter(mb, p,
lineLength));
+ }
+ }
+ }
+
+ private void writeParameter(
+ MessageBuilder mb,
org.apache.maven.api.plugin.descriptor.Parameter p, int lineLength) {
+ String suffix = (p.getDefaultValue() != null &&
!p.getDefaultValue().isEmpty())
+ ? " (Default: " + p.getDefaultValue() + ")" : "";
+ mb.a(indent(2)).strong(p.getName()).a(suffix).newline();
+ if (p.getDeprecated() != null &&
!p.getDeprecated().isEmpty()) {
+ mb.a(indent(3)).warning("Deprecated.").a("
").a(p.getDeprecated()).newline();
+ mb.newline();
+ }
+ if (p.getDescription() != null &&
!p.getDescription().isEmpty()) {
+ appendWrapped(mb, p.getDescription(), 3, lineLength);
+ }
+ if (p.isRequired()) {
+ mb.a(indent(3)).a("Required:
").strong("Yes").newline();
+ }
+ String expression = p.getExpression();
+ if (expression != null && !expression.isEmpty()
+ && expression.startsWith("${") &&
expression.endsWith("}")
+ && !expression.substring(2).contains("${")) {
+ mb.a(indent(3)).a("User property: ")
+ .info(expression.substring(2,
expression.length() - 1)).newline();
+ }
+ mb.newline();
+ }
+
+ private String indent(int level) {
+ return " ".repeat(level * indentSize);
+ }
+
+ private void appendWrapped(MessageBuilder mb, String text, int
indent, int lineLength) {
+ String pad = indent(indent);
+ for (String rawLine : text.split("(\\r\\n)|(\\r)|(\\n)")) {
+ // strip basic HTML tags and entities from javadoc
descriptions
+ String plain = rawLine
+ .replaceAll("<[^>]+>", "")
+ .replace("<", "<").replace(">",
">").replace("&", "&")
+ .replace(" ", " ").replace('\\u00A0', '
').trim();
+ if (plain.isEmpty()) {
+ mb.newline();
+ continue;
+ }
+ StringBuilder line = new StringBuilder(pad);
+ for (String token : plain.split(" +")) {
+ if (line.length() > pad.length() && line.length()
+ token.length() + 1 > lineLength) {
+ mb.a(line).newline();
+ line = new StringBuilder(pad);
+ } else if (line.length() > pad.length()) {
+ line.append(' ');
+ }
+ line.append(token);
+ }
+ if (line.length() > pad.length()) {
+ mb.a(line).newline();
+ }
+ }
+ }
+ }
+ """;
+ // @formatter:on
+
+ private void generateHelpMojo(String[] coords) throws IOException {
+ // Use the first discovered mojo's package for the generated HelpMojo.
+ String pkg = mojoElements.values().stream()
+ .filter(te -> te != null)
+ .map(this::getPackageName)
+ .findFirst()
+ .orElse("");
+
+ String helpFqn = pkg.isEmpty() ? "HelpMojo" : pkg + ".HelpMojo";
+ // Idempotency guard: JSR 269 fires a final round with
processingOver()==true
+ // even when no new files were generated; without this guard,
createSourceFile()
+ // would throw FilerException on the second call.
+ if (helpMojoGenerated) {
+ return;
+ }
+
+ String packageDecl = pkg.isEmpty() ? "" : "package " + pkg + ";\n\n";
+ String source = HELP_MOJO_TEMPLATE.formatted(packageDecl, coords[1],
coords[3], coords[2]);
+
+ try (Writer w =
processingEnv.getFiler().createSourceFile(helpFqn).openWriter()) {
+ w.write(source);
+ }
+ helpMojoGenerated = true;
+ note("Generated " + helpFqn);
+
+ // Mark HelpMojo as known so that if Round 2 (triggered by this new
source file)
+ // presents HelpMojo's @Mojo annotation, the process() loop treats it
as already
+ // processed and does not try to call generateFactory() on it again.
+ // We use a sentinel null value since we have no TypeElement for a
generated class.
+ mojoElements.put(helpFqn, null);
+
+ // Generate HelpMojoMojoFactory in the same round so DiIndexProcessor
picks up its
+ // @Named annotation in the follow-up round (Round 2) before writing
the DI index.
+ generateHelpMojoFactory(pkg, coords);
+ }
+
+ private void generateHelpMojoFactory(String pkg, String[] coords) throws
IOException {
+ String roleHint = coords[0] + ":" + coords[1] + ":" + coords[2] +
":help";
+ String factoryName = "HelpMojoMojoFactory";
+ String factoryFqn = pkg.isEmpty() ? factoryName : pkg + "." +
factoryName;
+
+ try (PrintWriter pw = new PrintWriter(
+
processingEnv.getFiler().createSourceFile(factoryFqn).openWriter())) {
+ if (!pkg.isEmpty()) {
+ pw.println("package " + pkg + ";");
+ pw.println();
+ }
+ pw.println("@org.apache.maven.api.di.Named(\"" + roleHint + "\")");
+ pw.println("public class " + factoryName + " extends HelpMojo {");
+ pw.println("}");
+ }
+ generatedFactoryNames.add(factoryFqn);
+ note("Generated factory " + factoryFqn);
+ }
+
+ static JavadocInfo parseJavadoc(String raw) {
+ if (raw == null || raw.isBlank()) {
+ return new JavadocInfo(null, null, null);
+ }
+ String[] parts = raw.split(
+
"(?m)^\\s*@(?=param|return|throws|exception|since|deprecated|see|author|version|serial|serialField|serialData)\\b");
+ String body = parts[0].replaceAll("\\{@\\w+\\s+([^}]*)}", "$1")
+ .replaceAll("<[^>]+>", "")
+ .strip()
+ .replaceAll("\\s+", " ");
+ String since = null, deprecated = null;
+ for (int i = 1; i < parts.length; i++) {
+ String tag = parts[i].trim();
+ if (tag.startsWith("since")) {
+ since = tag.substring(5).trim().replaceAll("\\s+", " ");
+ } else if (tag.startsWith("deprecated")) {
+ deprecated = tag.substring(10).trim().replaceAll("\\s+", " ");
+ }
+ }
+ return new JavadocInfo(body.isEmpty() ? null : body, since,
deprecated);
+ }
+
+ private TypeElement superType(TypeElement te) {
+ TypeMirror sup = te.getSuperclass();
+ return sup.getKind() != TypeKind.NONE
+ && sup instanceof DeclaredType dt
+ && dt.asElement() instanceof TypeElement st
+ && !isObject(st)
+ ? st
+ : null;
+ }
+
+ private static boolean isObject(TypeElement te) {
+ return "java.lang.Object".equals(te.getQualifiedName().toString());
+ }
+
+ static String deriveGoalPrefix(String artifactId) {
+ if (artifactId == null || artifactId.isEmpty()) {
+ return "";
+ }
+ String s = artifactId;
+ if (s.startsWith("maven-")) {
+ s = s.substring(6);
+ }
+ if (s.endsWith("-maven-plugin")) {
+ s = s.substring(0, s.length() - 13);
+ } else if (s.endsWith("-plugin")) {
+ s = s.substring(0, s.length() - 7);
+ }
+ return s;
+ }
+
+ private static void set(Consumer<String> setter, String value) {
+ if (value != null && !value.isEmpty()) {
+ setter.accept(value);
+ }
+ }
+
+ private static boolean isBlank(String s) {
+ return s == null || s.isEmpty();
+ }
+
+ /**
+ * Returns the package name for the given type element, using the
annotation
+ * processing API to correctly handle nested classes.
+ */
+ private String getPackageName(TypeElement typeElement) {
+ return processingEnv
+ .getElementUtils()
+ .getPackageOf(typeElement)
+ .getQualifiedName()
+ .toString();
+ }
+
+ /**
+ * Derives a parameter name from a getter/setter method name by stripping
the
+ * "set"/"get"/"is" prefix and decapitalizing, following JavaBeans
conventions.
+ */
+ static String deriveParameterName(String methodName) {
+ String stripped = methodName;
+ if (methodName.startsWith("set") && methodName.length() > 3) {
+ stripped = methodName.substring(3);
+ } else if (methodName.startsWith("get") && methodName.length() > 3) {
+ stripped = methodName.substring(3);
+ } else if (methodName.startsWith("is") && methodName.length() > 2) {
+ stripped = methodName.substring(2);
+ }
+ return decapitalize(stripped);
+ }
+
+ /**
+ * Decapitalizes a name following JavaBeans conventions: if the first two
characters
+ * are both uppercase, the name is returned unchanged (e.g. "URL" stays
"URL").
+ */
+ static String decapitalize(String name) {
+ if (name == null || name.isEmpty()) {
+ return name;
+ }
+ if (name.length() > 1 && Character.isUpperCase(name.charAt(1)) &&
Character.isUpperCase(name.charAt(0))) {
+ return name;
+ }
+ return Character.toLowerCase(name.charAt(0)) + name.substring(1);
+ }
+
+ private void note(String msg) {
+ processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, msg);
+ }
+
+ private void error(String msg) {
+ processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, msg);
+ }
+
+ private void error(String msg, Element element) {
+ processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, msg,
element);
+ }
+
+ private void error(String msg, Exception e) {
+ StringWriter sw = new StringWriter();
+ e.printStackTrace(new PrintWriter(sw));
+ error(msg + "\n" + e.getClass().getName() + ": " + e.getMessage() +
"\n" + sw);
+ }
+
+ record JavadocInfo(String description, String since, String deprecated) {}
+}
diff --git a/impl/maven-plugin-mixin/src/main/mixin/mixin.xml
b/impl/maven-plugin-mixin/src/main/mixin/mixin.xml
new file mode 100644
index 0000000000..99e835577d
--- /dev/null
+++ b/impl/maven-plugin-mixin/src/main/mixin/mixin.xml
@@ -0,0 +1,154 @@
+<?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.
+-->
+<!--
+ Mixin POM for Maven 4 plugin projects.
+ Use this as a mixin to get zero-config plugin descriptor generation:
+
+ <mixins>
+ <mixin>
+ <groupId>org.apache.maven</groupId>
+ <artifactId>maven-plugin-mixin</artifactId>
+ <version>4.2.0-SNAPSHOT</version>
+ <classifier>mixin</classifier>
+ </mixin>
+ </mixins>
+
+ This configures the compiler plugin to run the annotation processor
+ and pass the project coordinates as -A options automatically.
+-->
+<project xmlns="http://maven.apache.org/POM/4.2.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.2.0
https://maven.apache.org/xsd/maven-4.2.0.xsd">
+ <groupId>org.apache.maven</groupId>
+ <artifactId>maven-plugin-mixin</artifactId>
+ <version>@project.version@</version>
+ <packaging>pom</packaging>
+
+ <properties>
+ <maven.api.version>@project.version@</maven.api.version>
+ </properties>
+
+ <dependencyManagement>
+ <dependencies>
+ <dependency>
+ <groupId>org.apache.maven</groupId>
+ <artifactId>maven-api-annotations</artifactId>
+ <version>${maven.api.version}</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.maven</groupId>
+ <artifactId>maven-api-core</artifactId>
+ <version>${maven.api.version}</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.maven</groupId>
+ <artifactId>maven-api-di</artifactId>
+ <version>${maven.api.version}</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.maven</groupId>
+ <artifactId>maven-api-model</artifactId>
+ <version>${maven.api.version}</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.maven</groupId>
+ <artifactId>maven-api-metadata</artifactId>
+ <version>${maven.api.version}</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.maven</groupId>
+ <artifactId>maven-api-plugin</artifactId>
+ <version>${maven.api.version}</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.maven</groupId>
+ <artifactId>maven-api-settings</artifactId>
+ <version>${maven.api.version}</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.maven</groupId>
+ <artifactId>maven-api-spi</artifactId>
+ <version>${maven.api.version}</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.maven</groupId>
+ <artifactId>maven-api-toolchain</artifactId>
+ <version>${maven.api.version}</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.maven</groupId>
+ <artifactId>maven-api-xml</artifactId>
+ <version>${maven.api.version}</version>
+ <scope>provided</scope>
+ </dependency>
+ </dependencies>
+ </dependencyManagement>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.apache.maven</groupId>
+ <artifactId>maven-api-core</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.maven</groupId>
+ <artifactId>maven-api-di</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ </dependencies>
+
+ <build>
+ <pluginManagement>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <configuration>
+ <annotationProcessorPaths>
+ <path>
+ <groupId>org.apache.maven</groupId>
+ <artifactId>maven-plugin-mixin</artifactId>
+ <version>${maven.api.version}</version>
+ </path>
+ <path>
+ <groupId>org.apache.maven</groupId>
+ <artifactId>maven-api-di</artifactId>
+ <version>${maven.api.version}</version>
+ </path>
+ </annotationProcessorPaths>
+ <compilerArgs>
+ <arg>-Amaven.plugin.groupId=${project.groupId}</arg>
+ <arg>-Amaven.plugin.artifactId=${project.artifactId}</arg>
+ <arg>-Amaven.plugin.version=${project.version}</arg>
+ <arg>-Amaven.plugin.name=${project.name}</arg>
+ </compilerArgs>
+ </configuration>
+ </plugin>
+ </plugins>
+ </pluginManagement>
+ </build>
+</project>
diff --git
a/impl/maven-plugin-mixin/src/main/resources/META-INF/services/javax.annotation.processing.Processor
b/impl/maven-plugin-mixin/src/main/resources/META-INF/services/javax.annotation.processing.Processor
new file mode 100644
index 0000000000..bcfed864ba
--- /dev/null
+++
b/impl/maven-plugin-mixin/src/main/resources/META-INF/services/javax.annotation.processing.Processor
@@ -0,0 +1,17 @@
+# 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.
+org.apache.maven.plugin.processor.MojoDescriptorProcessor
diff --git a/impl/maven-plugin-mixin/src/site/markdown/index.md
b/impl/maven-plugin-mixin/src/site/markdown/index.md
new file mode 100644
index 0000000000..0f510a0326
--- /dev/null
+++ b/impl/maven-plugin-mixin/src/site/markdown/index.md
@@ -0,0 +1,126 @@
+title: Maven Plugin Mixin
+author: Maven Team
+date: ${project.version}
+
+<!--
+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.
+-->
+
+# Maven Plugin Mixin
+
+`maven-plugin-mixin` is a mixin for Maven 4 plugin projects. It bundles a JSR
269
+annotation processor that generates Maven 4 plugin descriptors
+(`META-INF/maven/plugin.xml`) and DI factory classes at compile time — with
+**no dependency on `maven-plugin-plugin`** or `maven-plugin-tools`.
+
+## Overview
+
+When you annotate a class with `@org.apache.maven.api.plugin.annotations.Mojo`,
+the processor fires during `javac` and produces:
+
+1. **`META-INF/maven/plugin.xml`** — the plugin descriptor in v2.0.0 format,
+ describing every mojo's goal name, default phase, parameters, dependency
+ resolution requirements, `@After` ordering constraints, and more.
+
+2. **One factory class per mojo** — e.g. `TouchMojoMojoFactory`, annotated with
+ `@Named("groupId:artifactId:version:goal")`. The DI index processor
+ (from `maven-api-di`) picks these up automatically and registers them in
+ `META-INF/maven/org.apache.maven.api.di.Inject`.
+
+## Usage
+
+Add the mixin to your plugin's POM (requires model version 4.2.0):
+
+```xml
+<project xmlns="http://maven.apache.org/POM/4.2.0" ...>
+
+ <groupId>com.example</groupId>
+ <artifactId>my-maven-plugin</artifactId>
+ <version>1.0-SNAPSHOT</version>
+ <packaging>jar</packaging>
+
+ <mixins>
+ <mixin>
+ <groupId>org.apache.maven</groupId>
+ <artifactId>maven-plugin-mixin</artifactId>
+ <version>${maven.version}</version>
+ </mixin>
+ </mixins>
+</project>
+```
+
+The mixin automatically configures the compiler plugin with the annotation
+processor and passes the resolved project coordinates (`groupId`, `artifactId`,
+`version`) as `-A` options. No manual compiler configuration required.
+
+## Why factories?
+
+`DefaultMavenPluginManager.loadV4Mojo()` looks up mojos by
+`Key.of(implementationClass, roleHint)` where `roleHint = "g:a:v:goal"`.
+The `@Named` qualifier on the factory class matches this key so the DI
container
+can locate and instantiate the mojo.
+
+## Supported annotations
+
+| Annotation | Extracted information |
+|------------|----------------------|
+| `@Mojo` | goal name, default phase, projectRequired, aggregator,
onlineRequired, configurator, dependencyCollection,
dependencyResolutionPathScopes |
+| `@Execute` | executePhase, executeGoal, executeLifecycle |
+| `@After` / `@Afters` | afterLink phase, type
(PROJECT/DEPENDENCIES/CHILDREN), scope |
+| `@Parameter` (field/method) | name, alias, type, required, editable
(inverted from `readonly`), expression (`${property}`), defaultValue, Javadoc
description |
+| `@Resolution` (field) | field name, pathScope, requestType |
+| Javadoc | mojo description, `@since`, `@deprecated`; inline tags like
`{@code}` and `{@link}` are stripped |
+
+## Type hierarchy
+
+`@Parameter` and `@Resolution` annotations are collected from the full class
+hierarchy — including fields declared in superclasses from dependency JARs.
+Subclass fields shadow parent fields with the same effective name.
+
+Note: `Elements.getDocComment()` only works for source elements. Parameters
+inherited from binary (compiled) parent classes will have empty descriptions,
+which is the same limitation as `maven-plugin-tools` when source JARs are
+unavailable.
+
+## Design principles
+
+- **Maven API dependencies** — the processor depends on `maven-api-core` and
`maven-api-plugin`
+ for direct annotation and descriptor access. Plugin authors who use
`annotationProcessorPaths`
+ will need these on the processor classpath; since Maven plugin projects
always declare them as
+ `provided`, this is automatic in practice.
+- **Self-processing disabled** —
`<maven.compiler.proc>none</maven.compiler.proc>`
+ prevents the processor from attempting to process itself.
+- **Non-claiming** — the processor returns `false` from `process()`, so other
+ processors and IDEs can still observe `@Mojo` annotations.
+- **Factories generated in normal rounds** — factory source files are emitted
+ during the round in which the mojo is first seen (not in `processingOver()`),
+ ensuring that `DiIndexProcessor` can process `@Named` in a subsequent round.
+
+## Processor options
+
+The following `-A` options are recognised. The mixin wires the first four
automatically
+from the Maven project coordinates; only `maven.plugin.name` and
`maven.plugin.goalPrefix`
+can be overridden manually if needed.
+
+| Option | Required | Description |
+|--------|----------|-------------|
+| `maven.plugin.groupId` | yes | Plugin group ID |
+| `maven.plugin.artifactId` | yes | Plugin artifact ID |
+| `maven.plugin.version` | yes | Plugin version |
+| `maven.plugin.name` | no | Human-readable plugin name (defaults to
`artifactId`). The mixin passes `${project.name}`. |
+| `maven.plugin.goalPrefix` | no | Goal prefix (auto-derived from `artifactId`
if omitted) |
diff --git a/impl/maven-plugin-mixin/src/site/markdown/usage.md
b/impl/maven-plugin-mixin/src/site/markdown/usage.md
new file mode 100644
index 0000000000..b399a999b8
--- /dev/null
+++ b/impl/maven-plugin-mixin/src/site/markdown/usage.md
@@ -0,0 +1,121 @@
+title: Usage
+author: Maven Team
+date: ${project.version}
+
+<!--
+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.
+-->
+
+# Usage
+
+## Minimal Maven 4 plugin
+
+A complete, functional Maven 4 plugin with one mojo and one `@Parameter`:
+
+```java
+package com.example;
+
+import org.apache.maven.api.plugin.annotations.Mojo;
+import org.apache.maven.api.plugin.annotations.Parameter;
+
+/**
+ * Prints a greeting.
+ *
+ * @since 1.0.0
+ */
+@Mojo(name = "greet", defaultPhase = "compile")
+public class GreetMojo implements org.apache.maven.api.plugin.Mojo {
+
+ /**
+ * The name to greet.
+ *
+ * @since 1.0.0
+ */
+ @Parameter(property = "greet.name", defaultValue = "World")
+ private String name;
+
+ @Override
+ public void execute() {
+ System.out.println("Hello, " + name + "!");
+ }
+}
+```
+
+POM configuration (model version 4.2.0, using the mixin):
+
+```xml
+<project xmlns="http://maven.apache.org/POM/4.2.0" ...>
+
+ <groupId>com.example</groupId>
+ <artifactId>greet-maven-plugin</artifactId>
+ <version>1.0-SNAPSHOT</version>
+ <packaging>jar</packaging>
+
+ <mixins>
+ <mixin>
+ <groupId>org.apache.maven</groupId>
+ <artifactId>maven-plugin-mixin</artifactId>
+ <version>${maven.version}</version>
+ </mixin>
+ </mixins>
+</project>
+```
+
+The mixin configures the compiler plugin automatically — no
+`annotationProcessorPaths` or `-A` options to set up manually.
+
+At compile time, the processor generates:
+
+- `target/classes/META-INF/maven/plugin.xml` — the plugin descriptor
+- `target/generated-sources/annotations/com/example/GreetMojoMojoFactory.java`
+ — the DI factory, compiled and registered in the DI index automatically
+
+## Using `@After` ordering constraints
+
+```java
+@Mojo(name = "touch", defaultPhase = "compile")
+@After(phase = "resources")
+public class TouchMojo implements Mojo { ... }
+```
+
+Generates an `<afterLink>` element in the descriptor, which the Maven 4
+concurrent builder uses to enforce ordering within the lifecycle DAG.
+
+## Dependency resolution
+
+```java
+@Mojo(name = "list-deps", defaultPhase = "compile")
+public class ListDepsMojo implements Mojo {
+
+ @Resolution(pathScope = "main", requestType = "resolve")
+ private DependencyResolverResult deps;
+ ...
+}
+```
+
+The processor emits a `<resolution>` element in the plugin descriptor.
+The build planner uses these `<resolution>` entries directly to determine
+dependency ordering — no `<dependencyResolution>` inference is needed.
+
+## Packaging note
+
+Because `maven-plugin-mixin` generates the plugin descriptor at compile
+time, the plugin does **not** use `<packaging>maven-plugin</packaging>`. Use
+standard `<packaging>jar</packaging>` (or omit packaging, which defaults to
+`jar`). Maven 4 loads the plugin from the descriptor in the JAR, not from the
+packaging lifecycle.
diff --git a/impl/maven-plugin-mixin/src/site/site.xml
b/impl/maven-plugin-mixin/src/site/site.xml
new file mode 100644
index 0000000000..2ea494edd3
--- /dev/null
+++ b/impl/maven-plugin-mixin/src/site/site.xml
@@ -0,0 +1,38 @@
+<?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.
+-->
+
+<site xmlns="http://maven.apache.org/SITE/2.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/SITE/2.0.0
https://maven.apache.org/xsd/site-2.0.0.xsd">
+
+ <edit>${project.scm.url}</edit>
+
+ <body>
+ <menu name="Overview">
+ <item name="Introduction" href="index.html"/>
+ <item name="Usage" href="usage.html"/>
+ <item name="Javadocs" href="apidocs/index.html"/>
+ <item name="Source Xref" href="xref/index.html"/>
+ </menu>
+
+ <menu ref="parent"/>
+ <menu ref="reports"/>
+ </body>
+</site>
diff --git
a/impl/maven-plugin-mixin/src/test/java/org/apache/maven/plugin/processor/MojoDescriptorProcessorTest.java
b/impl/maven-plugin-mixin/src/test/java/org/apache/maven/plugin/processor/MojoDescriptorProcessorTest.java
new file mode 100644
index 0000000000..0faf1c1e2c
--- /dev/null
+++
b/impl/maven-plugin-mixin/src/test/java/org/apache/maven/plugin/processor/MojoDescriptorProcessorTest.java
@@ -0,0 +1,999 @@
+/*
+ * 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.plugin.processor;
+
+import javax.tools.Diagnostic;
+import javax.tools.DiagnosticCollector;
+import javax.tools.FileObject;
+import javax.tools.ForwardingJavaFileManager;
+import javax.tools.JavaCompiler;
+import javax.tools.JavaFileManager;
+import javax.tools.JavaFileObject;
+import javax.tools.SimpleJavaFileObject;
+import javax.tools.StandardJavaFileManager;
+import javax.tools.StandardLocation;
+import javax.tools.ToolProvider;
+
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.StringWriter;
+import java.net.URI;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+
+/**
+ * Unit tests for {@link MojoDescriptorProcessor} using the JDK in-process
compiler.
+ *
+ * <p>Each test compiles a small in-memory source file that uses the Maven
plugin
+ * annotations ({@code @Mojo}, {@code @Parameter}, etc.) from maven-api-core on
+ * the classpath, with the processor JAR on the processor path. Generated
+ * resources (plugin.xml) and source files (factory classes) are intercepted by
+ * a {@link CapturingFileManager} and asserted in-memory — no disk I/O.</p>
+ */
+class MojoDescriptorProcessorTest {
+
+ /** Resolved classpath jars needed for compiling test sources. */
+ private static List<File> classpathJars;
+
+ /** The processor JAR (contains the compiled MojoDescriptorProcessor). */
+ private static File processorJar;
+
+ @BeforeAll
+ static void resolveClasspath() {
+ String version = System.getProperty("processor.version",
"4.2.0-SNAPSHOT");
+
+ // Processor JAR — built from this module
+ processorJar = resolveFile(
+ "impl/maven-plugin-mixin/target/maven-plugin-mixin-" + version
+ ".jar",
+ "maven-plugin-mixin/" + version + "/maven-plugin-mixin-" +
version + ".jar");
+
+ // Annotation JARs needed on the compilation classpath
+ File apiCore = resolveFile(
+ "api/maven-api-core/target/maven-api-core-" + version + ".jar",
+ "maven-api-core/" + version + "/maven-api-core-" + version +
".jar");
+ File apiAnnotations = resolveFile(
+ "api/maven-api-annotations/target/maven-api-annotations-" +
version + ".jar",
+ "maven-api-annotations/" + version + "/maven-api-annotations-"
+ version + ".jar");
+
+ classpathJars = List.of(apiCore, apiAnnotations);
+ }
+
+ /**
+ * Try to resolve a JAR first from the Maven multi-module project build
output, then from the local Maven repo.
+ *
+ * <p>In a Maven build, {@code maven.multiModuleProjectDirectory} points
to the project root, so
+ * {@code worktreeRelative} is resolved against that directory to find
freshly-compiled JARs.
+ * The {@code processor.worktree} system property can override the root
for IDE / manual runs.</p>
+ */
+ private static File resolveFile(String worktreeRelative, String
m2Relative) {
+ // Prefer the Maven multi-module project directory (set by Maven
during build)
+ String worktreeBase =
+ System.getProperty("processor.worktree",
System.getProperty("maven.multiModuleProjectDirectory", ""));
+ String m2Base = System.getProperty(
+ "processor.m2", System.getProperty("user.home") +
"/.m2/repository/org/apache/maven");
+
+ if (worktreeRelative != null && !worktreeBase.isEmpty()) {
+ File f = new File(worktreeBase, worktreeRelative);
+ if (f.isFile()) {
+ return f;
+ }
+ }
+ if (m2Relative != null) {
+ File f = new File(m2Base, m2Relative);
+ if (f.isFile()) {
+ return f;
+ }
+ }
+ fail("Cannot resolve JAR: worktree=" + worktreeRelative + " m2=" +
m2Relative);
+ return null; // unreachable
+ }
+
+ //
-------------------------------------------------------------------------
+ // Test 1: Minimal @Mojo → plugin.xml + factory
+ //
-------------------------------------------------------------------------
+
+ @Test
+ void minimalMojoGeneratesPluginXmlAndFactory() {
+ String source = """
+ package com.example;
+ import org.apache.maven.api.plugin.annotations.Mojo;
+ @Mojo(name = "greet")
+ public class GreetMojo {
+ public void execute() {}
+ }
+ """;
+
+ CompilationResult result = compile(
+ List.of(inMemorySource("com.example.GreetMojo", source)),
+ Map.of(
+ "maven.plugin.groupId", "com.example",
+ "maven.plugin.artifactId", "example-maven-plugin",
+ "maven.plugin.version", "1.0.0"));
+
+ assertTrue(result.success, () -> "Compilation failed:\n" +
result.diagnosticsToString());
+
+ // plugin.xml assertions
+ String pluginXml = result.getResource("META-INF/maven/plugin.xml");
+ assertNotNull(pluginXml, "plugin.xml must be generated");
+ assertContains(pluginXml, "<goal>greet</goal>");
+ assertContains(pluginXml,
"<implementation>com.example.GreetMojo</implementation>");
+ assertContains(pluginXml, "<groupId>com.example</groupId>");
+ assertContains(pluginXml,
"<artifactId>example-maven-plugin</artifactId>");
+ assertContains(pluginXml, "<version>1.0.0</version>");
+ // goalPrefix derived from "example-maven-plugin": strips
"-maven-plugin" suffix → "example"
+ assertContains(pluginXml, "<goalPrefix>example</goalPrefix>");
+ // language="java" and projectRequired=true are default values and are
NOT written to plugin.xml
+ assertFalse(
+ pluginXml.contains("<language>java</language>"),
"language=java is the default and must be omitted");
+ assertFalse(
+ pluginXml.contains("<projectRequired>true</projectRequired>"),
+ "projectRequired=true is the default and must be omitted");
+
+ // Factory class assertion
+ String factorySource =
result.getGeneratedSource("com.example.GreetMojoMojoFactory");
+ assertNotNull(factorySource, "Factory source must be generated");
+ assertContains(
+ factorySource,
"@org.apache.maven.api.di.Named(\"com.example:example-maven-plugin:1.0.0:greet\")");
+ assertContains(factorySource, "public class GreetMojoMojoFactory
extends GreetMojo");
+ }
+
+ //
-------------------------------------------------------------------------
+ // Test 2: @Mojo with @Parameter fields (readonly → editable inversion)
+ //
-------------------------------------------------------------------------
+
+ @Test
+ void mojoWithParametersGeneratesParametersBlock() {
+ String source = """
+ package com.example;
+ import org.apache.maven.api.plugin.annotations.Mojo;
+ import org.apache.maven.api.plugin.annotations.Parameter;
+ @Mojo(name = "compile", defaultPhase = "compile")
+ public class CompileMojo {
+ @Parameter(property = "source", defaultValue = "17",
required = true)
+ private String sourceVersion;
+
+ @Parameter(readonly = true, property = "project.basedir")
+ private java.io.File basedir;
+
+ @Parameter(name = "customName", alias = "alt")
+ private int threshold;
+
+ public void execute() {}
+ }
+ """;
+
+ CompilationResult result = compile(
+ List.of(inMemorySource("com.example.CompileMojo", source)),
+ Map.of(
+ "maven.plugin.groupId", "org.apache.maven.plugins",
+ "maven.plugin.artifactId", "maven-compiler-plugin",
+ "maven.plugin.version", "4.0.0"));
+
+ assertTrue(result.success, () -> "Compilation failed:\n" +
result.diagnosticsToString());
+
+ String pluginXml = result.getResource("META-INF/maven/plugin.xml");
+ assertNotNull(pluginXml, "plugin.xml must be generated");
+
+ // defaultPhase
+ assertContains(pluginXml, "<phase>compile</phase>");
+
+ // goalPrefix derived from "maven-compiler-plugin" → "compiler"
+ assertContains(pluginXml, "<goalPrefix>compiler</goalPrefix>");
+
+ // <parameters> block
+ assertContains(pluginXml, "<parameters>");
+
+ // sourceVersion parameter
+ assertContains(pluginXml, "<name>sourceVersion</name>");
+ assertContains(pluginXml, "<type>java.lang.String</type>");
+ assertContains(pluginXml, "<required>true</required>");
+ assertContains(pluginXml, "<expression>${source}</expression>");
+ assertContains(pluginXml, "<defaultValue>17</defaultValue>");
+
+ // basedir: readonly=true → editable=false
+ assertContains(pluginXml, "<name>basedir</name>");
+ // The readonly param should generate editable=false
+ assertTrue(
+ pluginXml.contains("<editable>false</editable>"),
+ "readonly=true should produce editable=false in plugin.xml");
+ assertContains(pluginXml,
"<expression>${project.basedir}</expression>");
+
+ // customName / alias
+ assertContains(pluginXml, "<name>customName</name>");
+ assertContains(pluginXml, "<alias>alt</alias>");
+
+ // sourceVersion: readonly defaults to false → editable=true is the
DEFAULT and omitted
+ // Verify that editable=false appears exactly once (only for the
readonly basedir param)
+ int editableFalseCount = pluginXml.split("<editable>false</editable>",
-1).length - 1;
+ assertEquals(1, editableFalseCount, "Only the readonly basedir param
should have editable=false");
+ assertFalse(
+ pluginXml.contains("<editable>true</editable>"),
+ "editable=true is the default value and must be omitted from
plugin.xml");
+ }
+
+ //
-------------------------------------------------------------------------
+ // Test 3: @Mojo with @After → afterLinks block
+ //
-------------------------------------------------------------------------
+
+ @Test
+ void mojoWithAfterGeneratesAfterLinksBlock() {
+ String source = """
+ package com.example;
+ import org.apache.maven.api.plugin.annotations.Mojo;
+ import org.apache.maven.api.plugin.annotations.After;
+ @Mojo(name = "post-compile")
+ @After(phase = "compile")
+ public class PostCompileMojo {
+ public void execute() {}
+ }
+ """;
+
+ CompilationResult result = compile(
+ List.of(inMemorySource("com.example.PostCompileMojo", source)),
+ Map.of(
+ "maven.plugin.groupId", "com.example",
+ "maven.plugin.artifactId", "example-plugin",
+ "maven.plugin.version", "1.0.0"));
+
+ assertTrue(result.success, () -> "Compilation failed:\n" +
result.diagnosticsToString());
+
+ String pluginXml = result.getResource("META-INF/maven/plugin.xml");
+ assertNotNull(pluginXml, "plugin.xml must be generated");
+ assertContains(pluginXml, "<afterLinks>");
+ assertContains(pluginXml, "<afterLink>");
+ assertContains(pluginXml, "<phase>compile</phase>");
+ // default type is PROJECT
+ assertContains(pluginXml, "<type>PROJECT</type>");
+ }
+
+ //
-------------------------------------------------------------------------
+ // Test 4: @Mojo with @Execute → executePhase/executeGoal
+ //
-------------------------------------------------------------------------
+
+ @Test
+ void mojoWithExecuteGeneratesExecuteFields() {
+ String source = """
+ package com.example;
+ import org.apache.maven.api.plugin.annotations.Mojo;
+ import org.apache.maven.api.plugin.annotations.Execute;
+ @Mojo(name = "report")
+ @Execute(phase = "test-compile", lifecycle = "custom")
+ public class ReportMojo {
+ public void execute() {}
+ }
+ """;
+
+ CompilationResult result = compile(
+ List.of(inMemorySource("com.example.ReportMojo", source)),
+ Map.of(
+ "maven.plugin.groupId", "com.example",
+ "maven.plugin.artifactId", "example-plugin",
+ "maven.plugin.version", "2.0.0"));
+
+ assertTrue(result.success, () -> "Compilation failed:\n" +
result.diagnosticsToString());
+
+ String pluginXml = result.getResource("META-INF/maven/plugin.xml");
+ assertNotNull(pluginXml, "plugin.xml must be generated");
+ assertContains(pluginXml, "<executePhase>test-compile</executePhase>");
+ assertContains(pluginXml,
"<executeLifecycle>custom</executeLifecycle>");
+ }
+
+ //
-------------------------------------------------------------------------
+ // Test 5: Missing required -A options → ERROR diagnostic
+ //
-------------------------------------------------------------------------
+
+ @Test
+ void missingRequiredOptionsEmitsErrorDiagnostic() {
+ String source = """
+ package com.example;
+ import org.apache.maven.api.plugin.annotations.Mojo;
+ @Mojo(name = "noop")
+ public class NoopMojo {
+ public void execute() {}
+ }
+ """;
+
+ // Omit all required -A options
+ CompilationResult result =
compile(List.of(inMemorySource("com.example.NoopMojo", source)), Map.of());
+
+ // The processor emits one combined error diagnostic naming all three
required options
+ assertFalse(result.success, "Compilation should fail when required -A
options are missing");
+
+ String errors = result.diagnosticsToString();
+ assertContains(errors, "maven.plugin.groupId");
+ assertContains(errors, "maven.plugin.artifactId");
+ assertContains(errors, "maven.plugin.version");
+ }
+
+ //
-------------------------------------------------------------------------
+ // Test 6: @Mojo on abstract class → ERROR diagnostic
+ //
-------------------------------------------------------------------------
+
+ @Test
+ void mojoOnAbstractClassEmitsErrorDiagnostic() {
+ String source = """
+ package com.example;
+ import org.apache.maven.api.plugin.annotations.Mojo;
+ @Mojo(name = "bad")
+ public abstract class AbstractBadMojo {
+ public abstract void execute();
+ }
+ """;
+
+ CompilationResult result = compile(
+ List.of(inMemorySource("com.example.AbstractBadMojo", source)),
+ Map.of(
+ "maven.plugin.groupId", "com.example",
+ "maven.plugin.artifactId", "example-plugin",
+ "maven.plugin.version", "1.0.0"));
+
+ assertFalse(result.success, "Compilation should fail for @Mojo on
abstract class");
+ String errors = result.diagnosticsToString();
+ assertContains(errors, "abstract");
+ }
+
+ //
-------------------------------------------------------------------------
+ // Test 7: deriveGoalPrefix() — direct static method test
+ //
-------------------------------------------------------------------------
+
+ @Test
+ void deriveGoalPrefixMavenXxxPlugin() {
+ assertEquals("compiler",
MojoDescriptorProcessor.deriveGoalPrefix("maven-compiler-plugin"));
+ }
+
+ @Test
+ void deriveGoalPrefixXxxMavenPlugin() {
+ // "my-maven-plugin": longer suffix "-maven-plugin" matched first →
"my"
+ assertEquals("my",
MojoDescriptorProcessor.deriveGoalPrefix("my-maven-plugin"));
+ }
+
+ @Test
+ void deriveGoalPrefixSimpleArtifactId() {
+ assertEquals("simple",
MojoDescriptorProcessor.deriveGoalPrefix("simple"));
+ }
+
+ @Test
+ void deriveGoalPrefixPluginSuffix() {
+ assertEquals("spotbugs",
MojoDescriptorProcessor.deriveGoalPrefix("spotbugs-plugin"));
+ }
+
+ @Test
+ void deriveGoalPrefixNullOrEmpty() {
+ assertEquals("", MojoDescriptorProcessor.deriveGoalPrefix(null));
+ assertEquals("", MojoDescriptorProcessor.deriveGoalPrefix(""));
+ }
+
+ @Test
+ void deriveGoalPrefixMavenPluginOnly() {
+ // "maven-plugin" → strip "maven-" → "plugin" → strip "-plugin" suffix
→ ""
+ // Actually: "maven-plugin" → strip "maven-" → "plugin" → strip
"-plugin" suffix → not applicable
+ // (ends with "-plugin" but the remaining after stripping "maven-" is
"plugin",
+ // which doesn't end with "-plugin" but IS "plugin" — no further
strip)
+ // Wait, let's check: s = "plugin", s.endsWith("-plugin") → false
+ assertEquals("plugin",
MojoDescriptorProcessor.deriveGoalPrefix("maven-plugin"));
+ }
+
+ //
-------------------------------------------------------------------------
+ // Test 8: deriveParameterName() — direct static method tests
+ //
-------------------------------------------------------------------------
+
+ @Test
+ void deriveParameterNameFromSetter() {
+ assertEquals("outputDir",
MojoDescriptorProcessor.deriveParameterName("setOutputDir"));
+ }
+
+ @Test
+ void deriveParameterNameFromGetter() {
+ assertEquals("outputDir",
MojoDescriptorProcessor.deriveParameterName("getOutputDir"));
+ }
+
+ @Test
+ void deriveParameterNameFromIsMethod() {
+ assertEquals("enabled",
MojoDescriptorProcessor.deriveParameterName("isEnabled"));
+ }
+
+ @Test
+ void deriveParameterNamePreservesConsecutiveUppercase() {
+ // JavaBeans convention: "URL" stays "URL" when first two chars are
uppercase
+ assertEquals("URL",
MojoDescriptorProcessor.deriveParameterName("setURL"));
+ }
+
+ @Test
+ void deriveParameterNameNoPrefix() {
+ // Method without set/get/is prefix is returned as-is (decapitalized)
+ assertEquals("doWork",
MojoDescriptorProcessor.deriveParameterName("doWork"));
+ }
+
+ @Test
+ void decapitalizeBasic() {
+ assertEquals("hello", MojoDescriptorProcessor.decapitalize("Hello"));
+ }
+
+ @Test
+ void decapitalizeConsecutiveUppercase() {
+ assertEquals("URL", MojoDescriptorProcessor.decapitalize("URL"));
+ }
+
+ @Test
+ void decapitalizeEmpty() {
+ assertEquals("", MojoDescriptorProcessor.decapitalize(""));
+ }
+
+ //
-------------------------------------------------------------------------
+ // Test 9: Nested @Mojo class generates correct package and implementation
+ //
-------------------------------------------------------------------------
+
+ @Test
+ void nestedMojoClassGeneratesCorrectPackageAndBinaryName() {
+ // Outer class containing the nested @Mojo
+ String outerSource = """
+ package com.example;
+ import org.apache.maven.api.plugin.annotations.Mojo;
+ public class Mojos {
+ @Mojo(name = "touch")
+ public static class TouchMojo {
+ public void execute() {}
+ }
+ }
+ """;
+
+ CompilationResult result = compile(
+ List.of(inMemorySource("com.example.Mojos", outerSource)),
+ Map.of(
+ "maven.plugin.groupId", "com.example",
+ "maven.plugin.artifactId", "example-plugin",
+ "maven.plugin.version", "1.0.0"));
+
+ assertTrue(result.success, () -> "Compilation failed:\n" +
result.diagnosticsToString());
+
+ // plugin.xml: implementation must use '$' for nested class (binary
name)
+ String pluginXml = result.getResource("META-INF/maven/plugin.xml");
+ assertNotNull(pluginXml, "plugin.xml must be generated");
+ assertContains(pluginXml, "<goal>touch</goal>");
+ assertContains(pluginXml,
"<implementation>com.example.Mojos$TouchMojo</implementation>");
+
+ // Factory must be in the correct package (com.example, NOT
com.example.Mojos)
+ String factorySource =
result.getGeneratedSource("com.example.TouchMojoMojoFactory");
+ assertNotNull(factorySource, "Factory source must be generated for
nested mojo");
+ assertContains(factorySource, "package com.example;");
+ // Factory extends the nested class using its relative name within the
package
+ assertContains(factorySource, "extends Mojos.TouchMojo");
+ }
+
+ //
-------------------------------------------------------------------------
+ // Test 10: @Parameter on setter methods derives correct name
+ //
-------------------------------------------------------------------------
+
+ @Test
+ void parameterOnSetterDerivesNameFromMethodName() {
+ String source = """
+ package com.example;
+ import org.apache.maven.api.plugin.annotations.Mojo;
+ import org.apache.maven.api.plugin.annotations.Parameter;
+ @Mojo(name = "build")
+ public class BuildMojo {
+ private java.io.File outputDir;
+
+ @Parameter(property = "output")
+ public void setOutputDir(java.io.File dir) {
+ this.outputDir = dir;
+ }
+
+ public void execute() {}
+ }
+ """;
+
+ CompilationResult result = compile(
+ List.of(inMemorySource("com.example.BuildMojo", source)),
+ Map.of(
+ "maven.plugin.groupId", "com.example",
+ "maven.plugin.artifactId", "example-plugin",
+ "maven.plugin.version", "1.0.0"));
+
+ assertTrue(result.success, () -> "Compilation failed:\n" +
result.diagnosticsToString());
+
+ String pluginXml = result.getResource("META-INF/maven/plugin.xml");
+ assertNotNull(pluginXml, "plugin.xml must be generated");
+ // Name should be "outputDir", not "setOutputDir"
+ assertContains(pluginXml, "<name>outputDir</name>");
+ assertFalse(
+ pluginXml.contains("<name>setOutputDir</name>"),
+ "Setter prefix should be stripped from parameter name");
+ }
+
+ //
-------------------------------------------------------------------------
+ // Test 11: Generic type parameters use erasure
+ //
-------------------------------------------------------------------------
+
+ @Test
+ void genericTypeParameterUsesErasure() {
+ String source = """
+ package com.example;
+ import org.apache.maven.api.plugin.annotations.Mojo;
+ import org.apache.maven.api.plugin.annotations.Parameter;
+ import java.util.List;
+ @Mojo(name = "process")
+ public class ProcessMojo {
+ @Parameter
+ private List<String> includes;
+
+ public void execute() {}
+ }
+ """;
+
+ CompilationResult result = compile(
+ List.of(inMemorySource("com.example.ProcessMojo", source)),
+ Map.of(
+ "maven.plugin.groupId", "com.example",
+ "maven.plugin.artifactId", "example-plugin",
+ "maven.plugin.version", "1.0.0"));
+
+ assertTrue(result.success, () -> "Compilation failed:\n" +
result.diagnosticsToString());
+
+ String pluginXml = result.getResource("META-INF/maven/plugin.xml");
+ assertNotNull(pluginXml, "plugin.xml must be generated");
+ assertContains(pluginXml, "<name>includes</name>");
+ // Type should be erased to raw type, not
"java.util.List<java.lang.String>"
+ assertContains(pluginXml, "<type>java.util.List</type>");
+ // In XML, angle brackets are escaped; check that no "<" appears
after "List"
+ assertFalse(
+ pluginXml.contains("List<"),
+ "Generic type parameters should be erased (found List< in
plugin.xml)");
+ }
+
+ //
-------------------------------------------------------------------------
+ // Test 12: @Resolution fields appear in resolutions list (not
dependencyResolution)
+ //
-------------------------------------------------------------------------
+
+ @Test
+ void resolutionFieldAppearsInResolutionsList() {
+ String source = """
+ package com.example;
+ import org.apache.maven.api.plugin.annotations.Mojo;
+ import org.apache.maven.api.plugin.annotations.Resolution;
+ @Mojo(name = "list-deps")
+ public class ListDepsMojo {
+ @Resolution(pathScope = "main", requestType = "resolve")
+ private Object deps;
+
+ public void execute() {}
+ }
+ """;
+
+ CompilationResult result = compile(
+ List.of(inMemorySource("com.example.ListDepsMojo", source)),
+ Map.of(
+ "maven.plugin.groupId", "com.example",
+ "maven.plugin.artifactId", "example-plugin",
+ "maven.plugin.version", "1.0.0"));
+
+ assertTrue(result.success, () -> "Compilation failed:\n" +
result.diagnosticsToString());
+
+ String pluginXml = result.getResource("META-INF/maven/plugin.xml");
+ assertNotNull(pluginXml, "plugin.xml must be generated");
+ // @Resolution fields should appear in the resolutions list, not as
dependencyResolution
+ assertContains(pluginXml, "<pathScope>main</pathScope>");
+ assertContains(pluginXml, "<requestType>resolve</requestType>");
+ assertFalse(
+
pluginXml.contains("<dependencyResolution>main</dependencyResolution>"),
+ "dependencyResolution should not be inferred from @Resolution;
the build planner uses resolutions directly");
+ }
+
+ //
-------------------------------------------------------------------------
+ // Test: explicit goalPrefix option overrides derivation
+ //
-------------------------------------------------------------------------
+
+ @Test
+ void explicitGoalPrefixOverridesDerived() {
+ String source = """
+ package com.example;
+ import org.apache.maven.api.plugin.annotations.Mojo;
+ @Mojo(name = "run")
+ public class RunMojo {
+ public void execute() {}
+ }
+ """;
+
+ CompilationResult result = compile(
+ List.of(inMemorySource("com.example.RunMojo", source)),
+ Map.of(
+ "maven.plugin.groupId", "com.example",
+ "maven.plugin.artifactId", "maven-compiler-plugin",
+ "maven.plugin.version", "1.0.0",
+ "maven.plugin.goalPrefix", "custom-prefix"));
+
+ assertTrue(result.success, () -> "Compilation failed:\n" +
result.diagnosticsToString());
+
+ String pluginXml = result.getResource("META-INF/maven/plugin.xml");
+ assertNotNull(pluginXml, "plugin.xml must be generated");
+ assertContains(pluginXml, "<goalPrefix>custom-prefix</goalPrefix>");
+ // Should NOT contain the derived prefix
+ assertFalse(pluginXml.contains("<goalPrefix>compiler</goalPrefix>"));
+ }
+
+ //
-------------------------------------------------------------------------
+ // Test: HelpMojo generation
+ //
-------------------------------------------------------------------------
+
+ @Test
+ void helpMojoIsGeneratedWithCorrectContent() {
+ String source = """
+ package com.example;
+ import org.apache.maven.api.plugin.annotations.Mojo;
+ import org.apache.maven.api.plugin.annotations.Parameter;
+ /** Greets the user. */
+ @Mojo(name = "greet")
+ public class GreetMojo {
+ /** The greeting message. */
+ @Parameter(property = "greet.message", defaultValue =
"Hello")
+ private String message;
+
+ /** Internal project basedir — not user-settable. */
+ @Parameter(readonly = true, property = "project.basedir")
+ private java.io.File basedir;
+
+ public void execute() {}
+ }
+ """;
+
+ CompilationResult result = compile(
+ List.of(inMemorySource("com.example.GreetMojo", source)),
+ Map.of(
+ "maven.plugin.groupId", "com.example",
+ "maven.plugin.artifactId", "greet-maven-plugin",
+ "maven.plugin.version", "1.0.0"));
+
+ assertTrue(result.success, () -> "Compilation failed:\n" +
result.diagnosticsToString());
+
+ // HelpMojo source assertions
+ String helpMojo = result.getGeneratedSource("com.example.HelpMojo");
+ assertNotNull(helpMojo, "HelpMojo source must be generated");
+
+ // Package and annotation
+ assertContains(helpMojo, "package com.example;");
+ assertContains(helpMojo, "@Mojo(name = \"help\", projectRequired =
false)");
+ assertContains(helpMojo, "public class HelpMojo implements
org.apache.maven.api.plugin.Mojo");
+
+ // Reads plugin.xml (not plugin-help.xml)
+ assertContains(helpMojo, "PLUGIN_XML_PATH =
\"/META-INF/maven/plugin.xml\"");
+
+ // Goal prefix from artifactId "greet-maven-plugin" → "greet"
+ assertContains(helpMojo, "greet:help");
+
+ // Uses PluginXmlFactory service (no raw DOM parsing)
+ assertContains(helpMojo, "PluginXmlFactory");
+ assertContains(helpMojo, "session.getService(PluginXmlFactory.class)");
+
+ // Session injected to access services
+ assertContains(helpMojo, "Session session");
+
+ // Uses MessageBuilderFactory for colored output
+ assertContains(helpMojo, "MessageBuilderFactory");
+ assertContains(helpMojo,
"session.getService(MessageBuilderFactory.class)");
+ assertContains(helpMojo, "mbf.getTerminalWidth()");
+
+ // Styled output: goal in mojo style, deprecated in warning style
+ assertContains(helpMojo, "mb.mojo(");
+ assertContains(helpMojo, ".warning(");
+ assertContains(helpMojo, ".strong(");
+
+ // Readonly parameter filter uses typed isEditable()
+ assertContains(helpMojo, "isEditable");
+
+ // HelpMojo should also get a factory generated for it (it has @Mojo)
+ // HelpMojoMojoFactory is now generated in the same round as HelpMojo
by
+ // generateHelpMojoFactory(), so DiIndexProcessor picks it up
correctly.
+ assertFalse(helpMojo.isEmpty());
+
+ // HelpMojoMojoFactory must also be generated in the same processing
round
+ String helpFactory =
result.getGeneratedSource("com.example.HelpMojoMojoFactory");
+ assertNotNull(helpFactory, "HelpMojoMojoFactory source must be
generated");
+ assertContains(helpFactory,
"@org.apache.maven.api.di.Named(\"com.example:greet-maven-plugin:1.0.0:help\")");
+ assertContains(helpFactory, "public class HelpMojoMojoFactory extends
HelpMojo {");
+
+ // plugin.xml must include the help goal so Maven can resolve it at
runtime
+ String pluginXml = result.getResource("META-INF/maven/plugin.xml");
+ assertNotNull(pluginXml, "plugin.xml must be generated");
+ assertContains(pluginXml, "<goal>help</goal>");
+ assertContains(pluginXml,
"<implementation>com.example.HelpMojo</implementation>");
+ // help mojo must have projectRequired=false
+ assertContains(pluginXml, "<projectRequired>false</projectRequired>");
+ // detail parameter must be in descriptor
+ assertContains(pluginXml, "<name>detail</name>");
+ // greet goal from GreetMojo must still be present alongside help
+ assertContains(pluginXml, "<goal>greet</goal>");
+ }
+
+ //
=========================================================================
+ // Compilation harness
+ //
=========================================================================
+
+ /**
+ * Compiles the given in-memory sources with the MojoDescriptorProcessor on
+ * the processor path and the maven-api-core annotations on the classpath.
+ */
+ private CompilationResult compile(List<JavaFileObject> sources,
Map<String, String> processorOptions) {
+ JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
+ assertNotNull(compiler, "No system Java compiler available (run tests
with a JDK, not a JRE)");
+
+ DiagnosticCollector<JavaFileObject> diagnostics = new
DiagnosticCollector<>();
+ StandardJavaFileManager stdFm =
compiler.getStandardFileManager(diagnostics, null, null);
+
+ try {
+ // Build classpath: maven-api-core + maven-api-annotations for the
test sources
+ stdFm.setLocation(StandardLocation.CLASS_PATH, classpathJars);
+
+ // Processor path: the processor JAR
+ stdFm.setLocation(StandardLocation.ANNOTATION_PROCESSOR_PATH,
List.of(processorJar));
+
+ } catch (IOException e) {
+ fail("Failed to configure file manager locations: " +
e.getMessage());
+ }
+
+ // Wrap in a CapturingFileManager to intercept generated outputs
+ CapturingFileManager capturingFm = new CapturingFileManager(stdFm);
+
+ // Build compiler options
+ List<String> options = new ArrayList<>();
+ // Processor options as -Akey=value
+ for (Map.Entry<String, String> opt : processorOptions.entrySet()) {
+ options.add("-A" + opt.getKey() + "=" + opt.getValue());
+ }
+ // Explicitly name the processor to use
+ options.add("-processor");
+
options.add("org.apache.maven.plugin.processor.MojoDescriptorProcessor");
+ // Ensure annotation processing is not suppressed
+ // (--proc-full requires JDK 23+; -proc:full is JDK 21-compatible for
enabling processing)
+
+ StringWriter compilerOutput = new StringWriter();
+
+ JavaCompiler.CompilationTask task =
+ compiler.getTask(compilerOutput, capturingFm, diagnostics,
options, null, sources);
+ boolean success = task.call();
+
+ return new CompilationResult(success, diagnostics, capturingFm);
+ }
+
+ //
=========================================================================
+ // In-memory source file
+ //
=========================================================================
+
+ private static JavaFileObject inMemorySource(String className, String
code) {
+ return new SimpleJavaFileObject(
+ URI.create("mem:///" + className.replace('.', '/') + ".java"),
JavaFileObject.Kind.SOURCE) {
+ @Override
+ public CharSequence getCharContent(boolean ignoreEncodingErrors) {
+ return code;
+ }
+ };
+ }
+
+ //
=========================================================================
+ // CapturingFileManager — intercepts generated sources and resources
+ //
=========================================================================
+
+ /**
+ * A {@link ForwardingJavaFileManager} that captures source files generated
+ * via {@code Filer.createSourceFile()} and resources via {@code
Filer.createResource()}.
+ */
+ private static class CapturingFileManager extends
ForwardingJavaFileManager<StandardJavaFileManager> {
+ /** Generated source files keyed by class name. */
+ final Map<String, String> generatedSources = new HashMap<>();
+ /** Generated resource files keyed by relative path (e.g.
"META-INF/maven/plugin.xml"). */
+ final Map<String, String> generatedResources = new HashMap<>();
+
+ CapturingFileManager(StandardJavaFileManager delegate) {
+ super(delegate);
+ }
+
+ @Override
+ public JavaFileObject getJavaFileForOutput(
+ JavaFileManager.Location location, String className,
JavaFileObject.Kind kind, FileObject sibling)
+ throws IOException {
+ if (kind == JavaFileObject.Kind.SOURCE) {
+ // This is a generated source file
+ return new InMemoryJavaFileObject(className, kind, content ->
generatedSources.put(className, content));
+ }
+ if (kind == JavaFileObject.Kind.CLASS) {
+ // We don't need the compiled class bytes, but we must provide
a valid output
+ return new InMemoryJavaFileObject(className, kind, content ->
{});
+ }
+ return super.getJavaFileForOutput(location, className, kind,
sibling);
+ }
+
+ @Override
+ public FileObject getFileForOutput(
+ JavaFileManager.Location location, String packageName, String
relativeName, FileObject sibling)
+ throws IOException {
+ String key = packageName.isEmpty() ? relativeName :
packageName.replace('.', '/') + "/" + relativeName;
+ return new InMemoryFileObject(key, content ->
generatedResources.put(key, content));
+ }
+
+ @Override
+ public FileObject getFileForInput(JavaFileManager.Location location,
String packageName, String relativeName)
+ throws IOException {
+ throw new java.io.FileNotFoundException("No input resource: " +
relativeName);
+ }
+ }
+
+ /** Callback interface for capturing written content. */
+ @FunctionalInterface
+ private interface ContentSink {
+ void accept(String content);
+ }
+
+ /**
+ * In-memory JavaFileObject that captures content written to its output
stream.
+ */
+ private static class InMemoryJavaFileObject extends SimpleJavaFileObject {
+ private final ContentSink sink;
+ private final ByteArrayOutputStream baos = new ByteArrayOutputStream();
+
+ InMemoryJavaFileObject(String className, Kind kind, ContentSink sink) {
+ super(URI.create("mem:///" + className.replace('.', '/') +
kind.extension), kind);
+ this.sink = sink;
+ }
+
+ @Override
+ public OutputStream openOutputStream() {
+ return new OutputStream() {
+ @Override
+ public void write(int b) {
+ baos.write(b);
+ }
+
+ @Override
+ public void write(byte[] b, int off, int len) {
+ baos.write(b, off, len);
+ }
+
+ @Override
+ public void close() throws IOException {
+ super.close();
+
sink.accept(baos.toString(java.nio.charset.StandardCharsets.UTF_8));
+ }
+ };
+ }
+
+ @Override
+ public java.io.Writer openWriter() {
+ return new StringWriter() {
+ @Override
+ public void close() throws IOException {
+ super.close();
+ sink.accept(this.toString());
+ }
+ };
+ }
+
+ @Override
+ public CharSequence getCharContent(boolean ignoreEncodingErrors) {
+ return baos.toString(java.nio.charset.StandardCharsets.UTF_8);
+ }
+ }
+
+ /**
+ * In-memory FileObject for resource files (e.g. plugin.xml).
+ */
+ private static class InMemoryFileObject extends SimpleJavaFileObject {
+ private final ContentSink sink;
+
+ InMemoryFileObject(String path, ContentSink sink) {
+ super(URI.create("mem:///" + path), Kind.OTHER);
+ this.sink = sink;
+ }
+
+ @Override
+ public OutputStream openOutputStream() {
+ return new OutputStream() {
+ private final ByteArrayOutputStream baos = new
ByteArrayOutputStream();
+
+ @Override
+ public void write(int b) {
+ baos.write(b);
+ }
+
+ @Override
+ public void write(byte[] b, int off, int len) {
+ baos.write(b, off, len);
+ }
+
+ @Override
+ public void close() throws IOException {
+ super.close();
+
sink.accept(baos.toString(java.nio.charset.StandardCharsets.UTF_8));
+ }
+ };
+ }
+
+ @Override
+ public java.io.Writer openWriter() {
+ return new StringWriter() {
+ @Override
+ public void close() throws IOException {
+ super.close();
+ sink.accept(this.toString());
+ }
+ };
+ }
+ }
+
+ //
=========================================================================
+ // CompilationResult
+ //
=========================================================================
+
+ private static class CompilationResult {
+ final boolean success;
+ final DiagnosticCollector<JavaFileObject> diagnostics;
+ final CapturingFileManager fileManager;
+
+ CompilationResult(
+ boolean success, DiagnosticCollector<JavaFileObject>
diagnostics, CapturingFileManager fileManager) {
+ this.success = success;
+ this.diagnostics = diagnostics;
+ this.fileManager = fileManager;
+ }
+
+ /** Returns generated resource content by relative path, or null if
not found. */
+ String getResource(String path) {
+ return fileManager.generatedResources.get(path);
+ }
+
+ /** Returns generated source content by fully-qualified class name, or
null. */
+ String getGeneratedSource(String className) {
+ return fileManager.generatedSources.get(className);
+ }
+
+ String diagnosticsToString() {
+ StringBuilder sb = new StringBuilder();
+ for (Diagnostic<? extends JavaFileObject> d :
diagnostics.getDiagnostics()) {
+ sb.append(d.getKind()).append(":
").append(d.getMessage(null)).append("\n");
+ }
+ return sb.toString();
+ }
+ }
+
+ //
=========================================================================
+ // Assertion helpers
+ //
=========================================================================
+
+ private static void assertContains(String text, String substring) {
+ assertTrue(text.contains(substring), () -> "Expected to find '" +
substring + "' in:\n" + truncate(text, 2000));
+ }
+
+ private static String truncate(String s, int maxLen) {
+ if (s.length() <= maxLen) {
+ return s;
+ }
+ return s.substring(0, maxLen) + "\n... [truncated at " + maxLen + " of
" + s.length() + " chars]";
+ }
+}
diff --git a/impl/pom.xml b/impl/pom.xml
index 9595fe81a0..7b0287c98a 100644
--- a/impl/pom.xml
+++ b/impl/pom.xml
@@ -42,6 +42,7 @@ under the License.
<module>maven-core</module>
<module>maven-cli</module>
<module>maven-testing</module>
+ <module>maven-plugin-mixin</module>
</modules>
<properties>
diff --git
a/its/core-it-suite/src/test/java/org/apache/maven/it/MavenITgh13644PluginProcessorTest.java
b/its/core-it-suite/src/test/java/org/apache/maven/it/MavenITgh13644PluginProcessorTest.java
new file mode 100644
index 0000000000..92ad9e58ce
--- /dev/null
+++
b/its/core-it-suite/src/test/java/org/apache/maven/it/MavenITgh13644PluginProcessorTest.java
@@ -0,0 +1,105 @@
+/*
+ * 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.it;
+
+import java.nio.file.Path;
+
+import org.junit.jupiter.api.Test;
+
+/**
+ * Integration test for
+ * <a href="https://github.com/apache/maven/issues/13644">GH-13644</a>.
+ * <p>
+ * Verifies that {@code maven-plugin-mixin} can generate a complete,
+ * functional plugin descriptor ({@code META-INF/maven/plugin.xml}) and the
+ * required DI factory classes at compile time — with no dependency on
+ * {@code maven-plugin-plugin} or {@code maven-plugin-tools}.
+ * <p>
+ * The test builds a minimal V4 plugin that uses the annotation processor,
+ * installs it, then runs a consumer project that invokes the generated mojo
+ * and also exercises the generated {@code help} mojo.
+ */
+class MavenITgh13644PluginProcessorTest extends
AbstractMavenIntegrationTestCase {
+
+ /**
+ * Verify that a plugin built with {@code maven-plugin-mixin}:
+ * <ul>
+ * <li>generates a valid {@code META-INF/maven/plugin.xml} at compile
time</li>
+ * <li>generates a {@code MojoFactory} class picked up by {@code
DiIndexProcessor}</li>
+ * <li>produces a plugin JAR that Maven can load and execute at
runtime</li>
+ * <li>correctly wires {@code @Parameter} injection (goal prefix,
default value, property)</li>
+ * <li>generates a working {@code help} mojo that lists goals and
parameters</li>
+ * </ul>
+ */
+ @Test
+ void testPluginProcessorGeneratesWorkingPlugin() throws Exception {
+ Path testDir = extractResources("/gh-13644-plugin-processor");
+
+ // Step 1: build and install the plugin (descriptor generated by
annotation processor)
+ // Maven 4 plugins require JDK 17+; override the global release=8
default set by the
+ // IT harness so the annotation processor and module-info compilation
succeed.
+ Verifier pluginVerifier = newVerifier(testDir.resolve("plugin"));
+ pluginVerifier.getSystemProperties().put("maven.compiler.release",
"17");
+ pluginVerifier.getSystemProperties().remove("maven.compiler.source");
+ pluginVerifier.getSystemProperties().remove("maven.compiler.target");
+ pluginVerifier.addCliArgument("install");
+ pluginVerifier.execute();
+ pluginVerifier.verifyErrorFreeLog();
+
+ // Verify descriptor was generated (not hand-written)
+
pluginVerifier.verifyFilePresent("target/classes/META-INF/maven/plugin.xml");
+ // Verify DI index was populated (DiIndexProcessor picked up the
factory)
+
pluginVerifier.verifyFilePresent("target/classes/META-INF/maven/org.apache.maven.api.di.Inject");
+ // Verify HelpMojo was generated and compiled
+
pluginVerifier.verifyFilePresent("target/classes/org/apache/maven/its/gh13644/HelpMojo.class");
+ // Verify HelpMojoMojoFactory was generated (needed by DI to resolve
the help goal)
+ pluginVerifier.verifyFilePresent(
+
"target/classes/org/apache/maven/its/gh13644/HelpMojoMojoFactory.class");
+
+ // Step 2: run the consumer project — exercises the touch mojo
+ Verifier consumerVerifier = newVerifier(testDir.resolve("consumer"));
+ consumerVerifier.getSystemProperties().put("maven.compiler.release",
"17");
+ consumerVerifier.getSystemProperties().remove("maven.compiler.source");
+ consumerVerifier.getSystemProperties().remove("maven.compiler.target");
+ consumerVerifier.addCliArgument("compile");
+ consumerVerifier.execute();
+ consumerVerifier.verifyErrorFreeLog();
+
+ // Mojo must have executed and created the touch file
+ consumerVerifier.verifyTextInLog(
+ "[GH-13644] touch goal executed via
annotation-processor-generated descriptor");
+ consumerVerifier.verifyFilePresent("target/touch.txt");
+
+ // Step 3: invoke the generated help mojo — verifies it was compiled
and can run
+ Verifier helpVerifier = newVerifier(testDir.resolve("consumer"));
+ helpVerifier.getSystemProperties().put("maven.compiler.release", "17");
+ helpVerifier.getSystemProperties().remove("maven.compiler.source");
+ helpVerifier.getSystemProperties().remove("maven.compiler.target");
+ helpVerifier.addCliArgument("gh13644:help");
+ helpVerifier.addCliArgument("-Ddetail=true");
+ helpVerifier.execute();
+ helpVerifier.verifyErrorFreeLog();
+
+ // help output must list the touch goal and its parameter
+ helpVerifier.verifyTextInLog("gh13644:touch");
+ helpVerifier.verifyTextInLog("outputFile");
+ // detail mode must show the user property
+ helpVerifier.verifyTextInLog("gh13644.outputFile");
+ }
+}
diff --git
a/its/core-it-suite/src/test/resources-filtered/gh-13644-plugin-processor/plugin/pom.xml
b/its/core-it-suite/src/test/resources-filtered/gh-13644-plugin-processor/plugin/pom.xml
new file mode 100644
index 0000000000..91ecd03ac6
--- /dev/null
+++
b/its/core-it-suite/src/test/resources-filtered/gh-13644-plugin-processor/plugin/pom.xml
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns="http://maven.apache.org/POM/4.2.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" root="true"
preserve.model.version="true"
xsi:schemaLocation="http://maven.apache.org/POM/4.2.0
https://maven.apache.org/xsd/maven-4.2.0.xsd">
+ <modelVersion>4.2.0</modelVersion>
+
+ <groupId>org.apache.maven.its.gh13644</groupId>
+ <artifactId>gh13644-plugin</artifactId>
+ <version>1.0-SNAPSHOT</version>
+ <packaging>jar</packaging>
+ <name>GH-13644 Test Plugin — uses maven-plugin-mixin</name>
+
+ <properties>
+ <javaVersion>17</javaVersion>
+ </properties>
+
+ <mixins>
+ <mixin>
+ <groupId>org.apache.maven</groupId>
+ <artifactId>maven-plugin-mixin</artifactId>
+ <version>${maven-version}</version>
+ <classifier>mixin</classifier>
+ </mixin>
+ </mixins>
+</project>
diff --git
a/its/core-it-suite/src/test/resources/gh-13644-plugin-processor/consumer/pom.xml
b/its/core-it-suite/src/test/resources/gh-13644-plugin-processor/consumer/pom.xml
new file mode 100644
index 0000000000..186eeaab2d
--- /dev/null
+++
b/its/core-it-suite/src/test/resources/gh-13644-plugin-processor/consumer/pom.xml
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<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.its.gh13644</groupId>
+ <artifactId>consumer</artifactId>
+ <version>1.0-SNAPSHOT</version>
+
+ <name>GH-13644 Consumer</name>
+ <description>Consumes the plugin whose descriptor was generated by
maven-plugin-mixin</description>
+
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.its.gh13644</groupId>
+ <artifactId>gh13644-plugin</artifactId>
+ <version>1.0-SNAPSHOT</version>
+ <executions>
+ <execution>
+ <id>touch</id>
+ <goals>
+ <goal>touch</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+ </build>
+</project>
diff --git
a/its/core-it-suite/src/test/resources/gh-13644-plugin-processor/plugin/src/main/java/org/apache/maven/its/gh13644/TouchMojo.java
b/its/core-it-suite/src/test/resources/gh-13644-plugin-processor/plugin/src/main/java/org/apache/maven/its/gh13644/TouchMojo.java
new file mode 100644
index 0000000000..15451a4a96
--- /dev/null
+++
b/its/core-it-suite/src/test/resources/gh-13644-plugin-processor/plugin/src/main/java/org/apache/maven/its/gh13644/TouchMojo.java
@@ -0,0 +1,63 @@
+/*
+ * 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.its.gh13644;
+
+import java.nio.file.Files;
+import java.nio.file.Path;
+
+import org.apache.maven.api.Project;
+import org.apache.maven.api.di.Inject;
+import org.apache.maven.api.plugin.Log;
+import org.apache.maven.api.plugin.annotations.Mojo;
+import org.apache.maven.api.plugin.annotations.Parameter;
+
+/**
+ * A minimal V4 mojo whose descriptor is generated entirely by
+ * {@code maven-plugin-mixin} — no {@code maven-plugin-plugin} involved.
+ *
+ * @since 1.0-SNAPSHOT
+ */
+@Mojo(name = "touch", defaultPhase = "compile")
+public class TouchMojo implements org.apache.maven.api.plugin.Mojo {
+
+ /**
+ * Output file name.
+ *
+ * @since 1.0-SNAPSHOT
+ */
+ @Parameter(property = "gh13644.outputFile", defaultValue = "touch.txt")
+ private String outputFile;
+
+ @Inject
+ private Log log;
+
+ @Inject
+ private Project project;
+
+ @Override
+ public void execute() throws Exception {
+ log.info("[GH-13644] touch goal executed via
annotation-processor-generated descriptor");
+ Path targetDir = project.getBasedir().resolve("target");
+ Files.createDirectories(targetDir);
+ Path out = targetDir.resolve(outputFile);
+ if (!Files.exists(out)) {
+ Files.createFile(out);
+ }
+ }
+}
diff --git a/src/graph/ReactorGraph.java b/src/graph/ReactorGraph.java
index ebd35afed1..5929c0c883 100755
--- a/src/graph/ReactorGraph.java
+++ b/src/graph/ReactorGraph.java
@@ -42,7 +42,7 @@ public class ReactorGraph {
CLUSTER_PATTERNS.put("JLine", Pattern.compile("^org\\.jline:.*"));
CLUSTER_PATTERNS.put("Maven 4 API",
Pattern.compile("^org\\.apache\\.maven:maven-api-(?!impl).*"));
CLUSTER_PATTERNS.put("Maven Resolver 2",
Pattern.compile("^org\\.apache\\.maven\\.resolver:.*"));
- CLUSTER_PATTERNS.put("Maven 4 Implementation",
Pattern.compile("^org\\.apache\\.maven:maven-(support|impl|di|core|cli|xml|jline|logging|executor|testing|utils|classworlds):.*"));
+ CLUSTER_PATTERNS.put("Maven 4 Implementation",
Pattern.compile("^org\\.apache\\.maven:maven-(support|impl|di|core|cli|xml|jline|logging|executor|testing|utils|classworlds|plugin-mixin):.*"));
CLUSTER_PATTERNS.put("Maven 3 Compatibility",
Pattern.compile("^org\\.apache\\.maven:maven-(artifact|builder-support|compat|embedder|model|model-builder|plugin-api|repository-metadata|resolver-provider|settings|settings-builder|toolchain-builder|toolchain-model):.*"));
CLUSTER_PATTERNS.put("Sisu",
Pattern.compile("(^org\\.eclipse\\.sisu:.*)|(.*:guice:.*)|(.*:javax.inject:.*)|(.*:jakarta.annotation-api:.*)|(.*:aopalliance:.*)"));
CLUSTER_PATTERNS.put("Plexus",
Pattern.compile("^org\\.codehaus\\.plexus:.*"));