Search code examples
javaeclipsemavenmaven-embedder

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


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.


Solution

  • 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.