Unable to run maven tasks through MavenCli (maven-embedder)

2.5k views Asked by At

I am using Maven embedder 3.3.3 in my program to run maven goals programmatically and I get the following error every time I run the MavenCli.doMain method:

-Dmaven.multiModuleProjectDirectory system property is not set. Check $M2_HOME environment variable and mvn script match.

2

There are 2 answers

1
Tunaki On BEST ANSWER

Since Maven 3.3.1, there is a new system property called maven.multiModuleProjectDirectory. It is set by default to the root of the project (project base directory) by the mvn (or mvn.bat) script (so that is why you never experienced such an error before).

Therefore, when running Maven through maven-embedder, you also need to set this system property (see source code where the check is made). It needs to be set to the project root.

To set this system property, you can adjust your call to doMain and add

"-Dmaven.multiModuleProjectDirectory=" + projectRoot

to the given arguments. An example would be

int result = cli.doMain(new String[] { "-Dmaven.multiModuleProjectDirectory=" + projectRoot, "install" }, "/path/to/project", System.out, System.err);

Alternatively, you can call:

System.setProperty("maven.multiModuleProjectDirectory", projectRoot);

before invoking MavenCli.doMain method, where projectRoot points to root of the project you are building.

0
Holly Cummins On

Setting the system property in code, before invoking the CLI, worked for me on Maven 3.9. (As Mirvnillith observed, just adding it to the doMain arguments was not enough.) For example:

        MavenCli cli = new MavenCli();
        System.setProperty("maven.multiModuleProjectDirectory", new File(projectDir).getAbsolutePath());
        int status = cli.doMain(
                new String[]{"clean", "verify"},
                projectDir,
                new PrintStream(testOut),
                new PrintStream(testErr));

I also had to add maven-compat as a dependency, or I got past the first error and hit failures related to RepositorySystem.