SyntaxCheckingMojo.java

package org.thewonderlemming.c4plantuml.mojo;

import java.io.IOException;

import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.thewonderlemming.c4plantuml.syntaxchecker.SyntaxChecker;

/**
 * A MOJO that parses the C4 PlantUML that are contained in the output directory and breaks the build if any syntax
 * error is detected.
 *
 * @author thewonderlemming
 *
 */
@Mojo(name = "check-syntax", defaultPhase = LifecyclePhase.COMPILE)
public class SyntaxCheckingMojo extends AbstractParentMojo {

    private MojoReporter reporter;


    /**
     * Processes the output directory to find syntax errors in the C4 files, and breaks the file if any error was found.
     * <p>
     * {@inheritDoc}
     */
    @Override
    protected void doExecute() throws MojoExecutionException, MojoFailureException {

        setReporter();

        processOutputDirectory();
        reportsAndBreakBuildIfNecessary();
    }

    private void processOutputDirectory() throws MojoFailureException {

        assert (getOutputDirectory() != null) : "Expected outputDirectory to be set!";

        try {

            final SyntaxChecker syntaxChecker = new SyntaxChecker(this.reporter);
            processOutputDirectoryFiles(path -> syntaxChecker.check(path, getCurrentCharset()));

        } catch (final IOException e) {

            final String errMsg = "Cannot process output directory: \"" + getOutputDirectory() + "\" for linting";
            throw new MojoFailureException(errMsg);
        }
    }

    private void reportsAndBreakBuildIfNecessary() throws MojoFailureException {

        assert (this.reporter != null) : "Expected reporter to be set";

        if (this.reporter.containsReports()) {

            this.reporter
                .getReports()
                    .forEach(report -> getLog().error(report));

            throw new MojoFailureException(
                "The build contains syntax errors. Please fix them then restart the build.");
        }
    }

    private void setReporter() {
        this.reporter = new MojoReporter();
    }
}