This is an automated email from the ASF dual-hosted git repository.

slachiewicz pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/maven-plugin-tools.git


The following commit(s) were added to refs/heads/master by this push:
     new 3f2b71d1 Mirror the mojo's injected constructor in the generated v4 
factory
3f2b71d1 is described below

commit 3f2b71d12f22edd39e02461b5d9515ebebcbeee6
Author: Animesh Kumar <[email protected]>
AuthorDate: Tue Oct 6 06:32:20 2026 +0530

    Mirror the mojo's injected constructor in the generated v4 factory
    
    The factory generated for a Maven 4 API mojo always called the mojo's
    no-arg constructor, so a mojo using constructor injection built fine
    and then failed at run time with NoSuchMethodError.
    
    The factory constructor now mirrors the constructor DI would pick on
    the mojo (the @Inject one, else the no-arg one, else the only one),
    with the same generic signature and annotations, and passes its
    arguments to super. A mojo with no usable constructor fails the
    descriptor goal instead.
    
    Fixes #1229
---
 .../plugin/plugin/DescriptorGeneratorMojo.java     | 146 +++++++++++-
 .../plugin/plugin/GeneratedMojoFactoryTest.java    | 250 +++++++++++++++++++++
 2 files changed, 391 insertions(+), 5 deletions(-)

diff --git 
a/maven-plugin-plugin/src/main/java/org/apache/maven/plugin/plugin/DescriptorGeneratorMojo.java
 
b/maven-plugin-plugin/src/main/java/org/apache/maven/plugin/plugin/DescriptorGeneratorMojo.java
index 781994b9..6fa04abd 100644
--- 
a/maven-plugin-plugin/src/main/java/org/apache/maven/plugin/plugin/DescriptorGeneratorMojo.java
+++ 
b/maven-plugin-plugin/src/main/java/org/apache/maven/plugin/plugin/DescriptorGeneratorMojo.java
@@ -86,6 +86,8 @@ import static org.objectweb.asm.Opcodes.ACC_PUBLIC;
 public class DescriptorGeneratorMojo extends AbstractGeneratorMojo {
     private static final String VALUE_AUTO = "auto";
 
+    private static final String INJECT_DESCRIPTOR = 
"Lorg/apache/maven/api/di/Inject;";
+
     /**
      * The directory where the generated <code>plugin.xml</code> file will be 
put.
      */
@@ -510,7 +512,7 @@ public class DescriptorGeneratorMojo extends 
AbstractGeneratorMojo {
         }
     }
 
-    private void generateFactory(MojoDescriptor md) throws IOException {
+    private void generateFactory(MojoDescriptor md) throws IOException, 
GeneratorException {
         String mojoClassName = md.getImplementation();
         String packageName = mojoClassName.substring(0, 
mojoClassName.lastIndexOf('.'));
         String generatorClassName = 
mojoClassName.substring(mojoClassName.lastIndexOf('.') + 1) + "Factory";
@@ -518,7 +520,11 @@ public class DescriptorGeneratorMojo extends 
AbstractGeneratorMojo {
 
         getLog().debug("Generating v4 factory for " + mojoClassName);
 
-        byte[] bin = computeGeneratorClassBytes(packageName, 
generatorClassName, mojoName, mojoClassName);
+        Path mojoClassFile = 
classesOutputDirectory.toPath().resolve(mojoClassName.replace('.', '/') + 
".class");
+        byte[] mojoClassBytes = Files.isRegularFile(mojoClassFile) ? 
Files.readAllBytes(mojoClassFile) : null;
+
+        byte[] bin =
+                computeGeneratorClassBytes(packageName, generatorClassName, 
mojoName, mojoClassName, mojoClassBytes);
 
         try (OutputStream os = new CachingOutputStream(classesOutputDirectory
                 .toPath()
@@ -527,8 +533,19 @@ public class DescriptorGeneratorMojo extends 
AbstractGeneratorMojo {
         }
     }
 
+    /**
+     * Generates the factory for a v4 mojo. The factory constructor mirrors 
the mojo constructor DI would use
+     * (descriptor, generic signature and annotations, including those of its 
parameters) and passes its
+     * parameters on, so that constructor injection keeps working.
+     *
+     * @param mojoClassBytes the compiled mojo class, or {@code null} if it is 
not available, in which case the
+     *            mojo's no-arg constructor is called
+     */
     static byte[] computeGeneratorClassBytes(
-            String packageName, String generatorClassName, String mojoName, 
String mojoClassName) {
+            String packageName, String generatorClassName, String mojoName, 
String mojoClassName, byte[] mojoClassBytes)
+            throws GeneratorException {
+        MojoConstructor constructor =
+                mojoClassBytes != null ? findMojoConstructor(mojoClassName, 
mojoClassBytes) : MojoConstructor.NO_ARG;
         String mojo = mojoClassName.replace('.', '/');
         ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES | 
ClassWriter.COMPUTE_MAXS);
         cw.visitSource(generatorClassName + ".java", null);
@@ -543,10 +560,23 @@ public class DescriptorGeneratorMojo extends 
AbstractGeneratorMojo {
                 null,
                 mojo,
                 null);
-        MethodVisitor mv = cw.visitMethod(ACC_PUBLIC + ACC_SYNTHETIC, 
"<init>", "()V", null, null);
+        MethodVisitor mv = cw.visitMethod(
+                ACC_PUBLIC + ACC_SYNTHETIC,
+                "<init>",
+                constructor.descriptor,
+                constructor.signature,
+                constructor.exceptions);
+        if (constructor != MojoConstructor.NO_ARG) {
+            copyConstructorAnnotations(mojoClassBytes, constructor.descriptor, 
mv);
+        }
         mv.visitCode();
         mv.visitVarInsn(Opcodes.ALOAD, 0);
-        mv.visitMethodInsn(Opcodes.INVOKESPECIAL, mojo, "<init>", "()V", 
false);
+        int slot = 1;
+        for (Type argumentType : 
Type.getArgumentTypes(constructor.descriptor)) {
+            mv.visitVarInsn(argumentType.getOpcode(Opcodes.ILOAD), slot);
+            slot += argumentType.getSize();
+        }
+        mv.visitMethodInsn(Opcodes.INVOKESPECIAL, mojo, "<init>", 
constructor.descriptor, false);
         mv.visitInsn(Opcodes.RETURN);
         mv.visitMaxs(-1, -1);
         mv.visitEnd();
@@ -554,6 +584,98 @@ public class DescriptorGeneratorMojo extends 
AbstractGeneratorMojo {
         return cw.toByteArray();
     }
 
+    /**
+     * Selects the mojo constructor the way Maven 4 DI does: the constructor 
annotated with {@code @Inject},
+     * otherwise the no-arg constructor (kept for compatibility), otherwise 
the only constructor.
+     */
+    private static MojoConstructor findMojoConstructor(String mojoClassName, 
byte[] mojoClassBytes)
+            throws GeneratorException {
+        List<MojoConstructor> constructors = new ArrayList<>();
+        List<MojoConstructor> injectConstructors = new ArrayList<>();
+        new ClassReader(mojoClassBytes)
+                .accept(
+                        new ClassVisitor(Opcodes.ASM9) {
+                            @Override
+                            public MethodVisitor visitMethod(
+                                    int access, String name, String 
descriptor, String signature, String[] exceptions) {
+                                if (!"<init>".equals(name) || (access & 
ACC_PRIVATE) != 0) {
+                                    return null;
+                                }
+                                MojoConstructor constructor = new 
MojoConstructor(descriptor, signature, exceptions);
+                                constructors.add(constructor);
+                                return new MethodVisitor(Opcodes.ASM9) {
+                                    @Override
+                                    public AnnotationVisitor 
visitAnnotation(String annotation, boolean visible) {
+                                        if 
(INJECT_DESCRIPTOR.equals(annotation)) {
+                                            
injectConstructors.add(constructor);
+                                        }
+                                        return null;
+                                    }
+                                };
+                            }
+                        },
+                        ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG | 
ClassReader.SKIP_FRAMES);
+
+        MojoConstructor selected;
+        if (injectConstructors.size() > 1) {
+            throw new GeneratorException("Mojo " + mojoClassName + " has more 
than one @Inject constructor", null);
+        } else if (injectConstructors.size() == 1) {
+            selected = injectConstructors.get(0);
+        } else if (constructors.stream().anyMatch(c -> 
c.descriptor.equals(MojoConstructor.NO_ARG.descriptor))) {
+            selected = MojoConstructor.NO_ARG;
+        } else if (constructors.size() == 1) {
+            selected = constructors.get(0);
+        } else {
+            throw new GeneratorException(
+                    "Mojo " + mojoClassName + " needs a no-arg constructor or 
a non-private constructor annotated"
+                            + " with @Inject",
+                    null);
+        }
+        return selected.descriptor.equals(MojoConstructor.NO_ARG.descriptor) ? 
MojoConstructor.NO_ARG : selected;
+    }
+
+    private static void copyConstructorAnnotations(
+            byte[] mojoClassBytes, String constructorDescriptor, MethodVisitor 
to) {
+        new ClassReader(mojoClassBytes)
+                .accept(
+                        new ClassVisitor(Opcodes.ASM9) {
+                            @Override
+                            public MethodVisitor visitMethod(
+                                    int access, String name, String 
descriptor, String signature, String[] exceptions) {
+                                if (!"<init>".equals(name) || 
!constructorDescriptor.equals(descriptor)) {
+                                    return null;
+                                }
+                                return new MethodVisitor(Opcodes.ASM9) {
+                                    @Override
+                                    public void visitParameter(String 
parameterName, int access) {
+                                        to.visitParameter(parameterName, 
access);
+                                    }
+
+                                    @Override
+                                    public AnnotationVisitor 
visitAnnotation(String annotation, boolean visible) {
+                                        return visible ? 
to.visitAnnotation(annotation, true) : null;
+                                    }
+
+                                    @Override
+                                    public void 
visitAnnotableParameterCount(int parameterCount, boolean visible) {
+                                        if (visible) {
+                                            
to.visitAnnotableParameterCount(parameterCount, true);
+                                        }
+                                    }
+
+                                    @Override
+                                    public AnnotationVisitor 
visitParameterAnnotation(
+                                            int parameter, String annotation, 
boolean visible) {
+                                        return visible
+                                                ? 
to.visitParameterAnnotation(parameter, annotation, true)
+                                                : null;
+                                    }
+                                };
+                            }
+                        },
+                        ClassReader.SKIP_CODE | ClassReader.SKIP_FRAMES);
+    }
+
     private PluginDescriptor extendPluginDescriptor(PluginToolsRequest 
request) {
         PluginDescriptor pluginDescriptor = request.getPluginDescriptor();
         
pluginDescriptor.setRequiredMavenVersion(getRequiredMavenVersion(request));
@@ -638,4 +760,18 @@ public class DescriptorGeneratorMojo extends 
AbstractGeneratorMojo {
 
         return filteredArtifacts;
     }
+
+    private static final class MojoConstructor {
+        static final MojoConstructor NO_ARG = new MojoConstructor("()V", null, 
null);
+
+        final String descriptor;
+        final String signature;
+        final String[] exceptions;
+
+        MojoConstructor(String descriptor, String signature, String[] 
exceptions) {
+            this.descriptor = descriptor;
+            this.signature = signature;
+            this.exceptions = exceptions;
+        }
+    }
 }
diff --git 
a/maven-plugin-plugin/src/test/java/org/apache/maven/plugin/plugin/GeneratedMojoFactoryTest.java
 
b/maven-plugin-plugin/src/test/java/org/apache/maven/plugin/plugin/GeneratedMojoFactoryTest.java
new file mode 100644
index 00000000..821c5ff6
--- /dev/null
+++ 
b/maven-plugin-plugin/src/test/java/org/apache/maven/plugin/plugin/GeneratedMojoFactoryTest.java
@@ -0,0 +1,250 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.maven.plugin.plugin;
+
+import java.lang.reflect.Constructor;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import org.apache.maven.tools.plugin.generator.GeneratorException;
+import org.junit.jupiter.api.Test;
+import org.objectweb.asm.AnnotationVisitor;
+import org.objectweb.asm.ClassReader;
+import org.objectweb.asm.ClassVisitor;
+import org.objectweb.asm.ClassWriter;
+import org.objectweb.asm.MethodVisitor;
+import org.objectweb.asm.Opcodes;
+import org.objectweb.asm.Type;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Tests the factory generated for Maven 4 API mojos, using mojo classes built 
with ASM so that the Maven 4 API
+ * does not need to be on the test classpath.
+ */
+class GeneratedMojoFactoryTest {
+    private static final String INJECT = "Lorg/apache/maven/api/di/Inject;";
+    private static final String NAMED = "Lorg/apache/maven/api/di/Named;";
+    private static final String MOJO = "org.example.TestMojo";
+
+    @Test
+    void factoryPassesInjectConstructorArgumentsToMojo() throws Exception {
+        Class<?> factory = loadFactory(mojoClass(constructor(
+                "(Ljava/lang/String;JLjava/util/List;)V",
+                "(Ljava/lang/String;JLjava/util/List<Ljava/lang/String;>;)V",
+                true)));
+
+        Constructor<?> constructor = factory.getConstructor(String.class, 
long.class, List.class);
+        assertEquals("java.util.List<java.lang.String>", 
constructor.getGenericParameterTypes()[2].getTypeName());
+
+        Object mojo = constructor.newInstance("name", 42L, 
Collections.singletonList("item"));
+        assertEquals("name", field(mojo, "p0"));
+        assertEquals(42L, field(mojo, "p1"));
+        assertEquals(Collections.singletonList("item"), field(mojo, "p2"));
+    }
+
+    @Test
+    void factoryConstructorKeepsInjectAndParameterAnnotations() throws 
Exception {
+        byte[] factory = generateFactory(
+                
mojoClass(constructor("(Ljava/lang/String;Ljava/lang/String;)V", null, true, 
null, "second")));
+
+        assertEquals(Arrays.asList("@" + INJECT, "1:@" + NAMED + 
"(value=second)"), constructorAnnotations(factory));
+    }
+
+    @Test
+    void factoryUsesInjectConstructorOverNoArgConstructor() throws Exception {
+        Class<?> factory = loadFactory(
+                mojoClass(constructor("()V", null, false), 
constructor("(Ljava/lang/String;)V", null, true)));
+
+        assertEquals(1, factory.getDeclaredConstructors().length);
+        assertEquals("value", 
field(factory.getConstructor(String.class).newInstance("value"), "p0"));
+    }
+
+    @Test
+    void factoryUsesSoleConstructorWithoutInject() throws Exception {
+        Class<?> factory = 
loadFactory(mojoClass(constructor("(Ljava/lang/String;)V", null, false)));
+
+        assertEquals("value", 
field(factory.getConstructor(String.class).newInstance("value"), "p0"));
+    }
+
+    @Test
+    void factoryForMojoWithNoArgConstructorIsUnchanged() throws Exception {
+        byte[] mojo = mojoClass(constructor("()V", null, false), 
constructor("(Ljava/lang/String;)V", null, false));
+
+        assertArrayEquals(generateFactory(null), generateFactory(mojo));
+    }
+
+    @Test
+    void mojoWithoutUsableConstructorIsRejected() {
+        byte[] mojo = mojoClass(constructor("(Ljava/lang/String;)V", null, 
false), constructor("(J)V", null, false));
+
+        GeneratorException e = assertThrows(GeneratorException.class, () -> 
generateFactory(mojo));
+        assertTrue(e.getMessage().contains(MOJO), e.getMessage());
+    }
+
+    @Test
+    void mojoWithTwoInjectConstructorsIsRejected() {
+        byte[] mojo = mojoClass(constructor("(Ljava/lang/String;)V", null, 
true), constructor("(J)V", null, true));
+
+        GeneratorException e = assertThrows(GeneratorException.class, () -> 
generateFactory(mojo));
+        assertTrue(e.getMessage().contains(MOJO), e.getMessage());
+    }
+
+    private static byte[] generateFactory(byte[] mojoClassBytes) throws 
GeneratorException {
+        return DescriptorGeneratorMojo.computeGeneratorClassBytes(
+                "org.example", "TestMojoFactory", "org.example:test:1.0:run", 
MOJO, mojoClassBytes);
+    }
+
+    private static Class<?> loadFactory(byte[] mojoClassBytes) throws 
GeneratorException {
+        byte[] factoryClassBytes = generateFactory(mojoClassBytes);
+        TestClassLoader loader = new TestClassLoader();
+        loader.define(MOJO, mojoClassBytes);
+        return loader.define(MOJO + "Factory", factoryClassBytes);
+    }
+
+    private static Object field(Object instance, String name) throws 
ReflectiveOperationException {
+        return 
instance.getClass().getSuperclass().getField(name).get(instance);
+    }
+
+    private static List<String> constructorAnnotations(byte[] classBytes) {
+        List<String> annotations = new ArrayList<>();
+        new ClassReader(classBytes)
+                .accept(
+                        new ClassVisitor(Opcodes.ASM9) {
+                            @Override
+                            public MethodVisitor visitMethod(
+                                    int access, String name, String 
descriptor, String signature, String[] exceptions) {
+                                return new MethodVisitor(Opcodes.ASM9) {
+                                    @Override
+                                    public AnnotationVisitor 
visitAnnotation(String annotation, boolean visible) {
+                                        return recorder("@" + annotation);
+                                    }
+
+                                    @Override
+                                    public AnnotationVisitor 
visitParameterAnnotation(
+                                            int parameter, String annotation, 
boolean visible) {
+                                        return recorder(parameter + ":@" + 
annotation);
+                                    }
+                                };
+                            }
+
+                            private AnnotationVisitor recorder(String prefix) {
+                                StringBuilder values = new StringBuilder();
+                                return new AnnotationVisitor(Opcodes.ASM9) {
+                                    @Override
+                                    public void visit(String name, Object 
value) {
+                                        values.append('(')
+                                                .append(name)
+                                                .append('=')
+                                                .append(value)
+                                                .append(')');
+                                    }
+
+                                    @Override
+                                    public void visitEnd() {
+                                        annotations.add(prefix + values);
+                                    }
+                                };
+                            }
+                        },
+                        0);
+        return annotations;
+    }
+
+    private static MojoConstructor constructor(
+            String descriptor, String signature, boolean inject, String... 
namedParameters) {
+        return new MojoConstructor(descriptor, signature, inject, 
namedParameters);
+    }
+
+    /**
+     * Builds a mojo class whose constructors store each argument {@code i} in 
a public field {@code p<i>}.
+     */
+    private static byte[] mojoClass(MojoConstructor... constructors) {
+        String mojo = MOJO.replace('.', '/');
+        ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES | 
ClassWriter.COMPUTE_MAXS);
+        cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC | Opcodes.ACC_SUPER, mojo, 
null, "java/lang/Object", null);
+        Set<String> fields = new HashSet<>();
+        for (MojoConstructor constructor : constructors) {
+            MethodVisitor mv =
+                    cw.visitMethod(Opcodes.ACC_PUBLIC, "<init>", 
constructor.descriptor, constructor.signature, null);
+            if (constructor.inject) {
+                mv.visitAnnotation(INJECT, true).visitEnd();
+            }
+            for (int i = 0; i < constructor.namedParameters.length; i++) {
+                if (constructor.namedParameters[i] != null) {
+                    AnnotationVisitor av = mv.visitParameterAnnotation(i, 
NAMED, true);
+                    av.visit("value", constructor.namedParameters[i]);
+                    av.visitEnd();
+                }
+            }
+            mv.visitCode();
+            mv.visitVarInsn(Opcodes.ALOAD, 0);
+            mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", 
"<init>", "()V", false);
+            Type[] argumentTypes = 
Type.getArgumentTypes(constructor.descriptor);
+            int slot = 1;
+            for (int i = 0; i < argumentTypes.length; i++) {
+                String fieldDescriptor = argumentTypes[i].getDescriptor();
+                if (fields.add("p" + i + fieldDescriptor)) {
+                    cw.visitField(Opcodes.ACC_PUBLIC, "p" + i, 
fieldDescriptor, null, null)
+                            .visitEnd();
+                }
+                mv.visitVarInsn(Opcodes.ALOAD, 0);
+                mv.visitVarInsn(argumentTypes[i].getOpcode(Opcodes.ILOAD), 
slot);
+                mv.visitFieldInsn(Opcodes.PUTFIELD, mojo, "p" + i, 
fieldDescriptor);
+                slot += argumentTypes[i].getSize();
+            }
+            mv.visitInsn(Opcodes.RETURN);
+            mv.visitMaxs(-1, -1);
+            mv.visitEnd();
+        }
+        cw.visitEnd();
+        return cw.toByteArray();
+    }
+
+    private static final class MojoConstructor {
+        final String descriptor;
+        final String signature;
+        final boolean inject;
+        final String[] namedParameters;
+
+        MojoConstructor(String descriptor, String signature, boolean inject, 
String[] namedParameters) {
+            this.descriptor = descriptor;
+            this.signature = signature;
+            this.inject = inject;
+            this.namedParameters = namedParameters;
+        }
+    }
+
+    private static final class TestClassLoader extends ClassLoader {
+        TestClassLoader() {
+            super(GeneratedMojoFactoryTest.class.getClassLoader());
+        }
+
+        Class<?> define(String name, byte[] classBytes) {
+            return defineClass(name, classBytes, 0, classBytes.length);
+        }
+    }
+}

Reply via email to