Search code examples
javam2emaven-mojo

Mojo add eclipse source folder


I have written a maven plugin that generates source code. This works basically fine.

The problem is, that Eclipse does not recognize the directory where I generate the code as an additional source folder. Therefore I get tons of errors saying XXX cannot be resolved to a type. The maven compile and install from the command line works fine, though.

First I had resolved this by using org.codehaus.mojo.build-helper-maven-plugin. This works fine. However, I don't like that the user of my plugin needs to add a second plugin as well. Therefore I had a look into the source code of the add-source goal in the build-helper-maven-plugin and decided to add the relevant code to do this directly into my plugin. Therefore my plugin looks like this:

@Mojo(name = "generate-sources", defaultPhase = LifecyclePhase.GENERATE_SOURCES)
public class MyMojo extends AbstractMojo {
    @Parameter(defaultValue = "${project}", readonly = true, required = true)
    private MavenProject project;

    @Parameter(required = true)
    private File targetDirectory;

    // some more members

    @Override
    public void execute() throws MojoExecutionException {
        // generation of the sources into targetDirectory

        project.addCompileSourceRoot(targetDirectory.getAbsolutePath());
    }
}

There are no errors during execution, both from command line and from eclipse (with Alt+F5 or right click -> Maven -> Update project). The additional source directory is not recognized, though.

Do I do anything wrong? Or do I need a special m2e connector? currently I'm working around this m2e connector with the lifecycle-mapping plugin using

<action>
    <execute>
        <runOnConfiguration>true</runOnConfiguration>
        <runOnIncremental>true</runOnIncremental>
    </execute>
</action>

Solution

  • Although your plugin adds extra source directory to project, Eclipse cannot recognize that. You can configure that Eclipse should execute your goal, but you can't tell Eclipse to add extra source directory.

    Some plugins, for example build-helper, can add extra source directory, but they need corresponding m2e extension. There is no general m2e which works for all plugins.

    You have the following options:

    1. Use build-helper-maven-plugin. I agree that it is stupid
    2. Write own m2e extension. Much worse than option 1.
    3. Use separated maven module for source generated by your plugin. In such module you can define <sourceDirectory>${project.build.directory}/generate-sources</..>. The separation has sense: generated code has usually different nature than regular code.
    4. Do nothing and require that developers add extra source folder manually. That looks very primitive, but has one advantage - manually added source folder is not removed on [right click -> Maven -> Update project]