Search code examples
javamavenmaven-3maven-plugin

How to get build status when using the maven invoker?


I'm developing a plugin that verifies if a maven project compiles or not, I'm using the maven invoker to run install goal on each project but I didn't find how to get the build result from, here's an example of the code I'm trying to use:

private void verify(File file) {
    Invoker invoker = new DefaultInvoker();
    InvocationRequest request = new DefaultInvocationRequest();
    request.setGoals(Collections.singletonList("install"))
    .setMavenOpts("-Dmaven.test.skip=true")
    .setBaseDirectory(file).
    setBatchMode(true);
    try {
        invoker.execute(request);
    } catch (Exception e) {
        failedToCompileList.add(file.getAbsolutePath());
        getLog().error(e);
    }
}

Solution

  • From the Usage page, you just need to check the results of the execute statement:

    InvocationResult result = invoker.execute( request );
     
    if ( result.getExitCode() != 0 )
    {
        throw new IllegalStateException( "Build failed." );
    }
    

    This will retrieve the exit code from the invocation result, and throw an exception if it's not 0 (the traditional all-clear code). Note that we could capture the build output by adding an InvocationOutputHandler instance to either the invoker or the request.

    Adding this to your example would be:

    private void verify(File file) {
        Invoker invoker = new DefaultInvoker();
        InvocationRequest request = new DefaultInvocationRequest();
        request.setGoals(Collections.singletonList("install"))
        .setMavenOpts("-Dmaven.test.skip=true")
        .setBaseDirectory(file).
        setBatchMode(true);
        try {
            InvocationResult result = invoker.execute(request);
            if ( result.getExitCode() != 0 )
            {
                throw new IllegalStateException( "Build failed." );
            }
        } catch (Exception e) {
            failedToCompileList.add(file.getAbsolutePath());
            getLog().error(e);
        }
    }