使用 Maven 调用程序时如何获取构建状态?

How to get build status when using the maven invoker?

我正在开发一个插件来验证 Maven 项目是否编译,我正在使用 Maven 调用程序来实现每个项目的 运行 install 目标,但我没有找到如何要从中获取构建结果,这是我尝试使用的代码示例:

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);
    }
}

Usage page开始,你只需要检查execute语句的结果:

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.

将此添加到您的示例中将是:

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);
    }
}