MoleculeMojo.java

package de.schegge.rosinante.maven;

import de.schegge.rosinante.core.PathProtoDestinations;
import de.schegge.rosinante.core.PathProtoSources;
import de.schegge.rosinante.generator.ProtoGenerator;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.codehaus.plexus.util.DirectoryScanner;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

@Mojo(name = "generate-code", threadSafe = true, defaultPhase = LifecyclePhase.GENERATE_SOURCES)
public class MoleculeMojo extends AbstractMojo {

    /**
     * The output directory.
     */
    @Parameter(defaultValue = "${project.build.directory}/generated-sources/rocinante")
    private File outputDirectory;

    /**
     * The input directory.
     */
    @Parameter(defaultValue = "${project.basedir}/src/main/rocinante")
    private File inputDirectory;

    /**
     * The input file.
     */
    private String[] inputs = new String[]{"**/*.proto"};

    @Parameter(name = "inputs")
    public void setInputs(String[] inputs) {
        this.inputs = inputs;
    }

    /**
     * The input directory.
     */
    @Parameter(defaultValue = "${project.basedir}/src/main/rocinante")
    private File importDirectory;

    /**
     * Skip the generation of the sources.
     */
    @Parameter
    private boolean skip;

    public void execute() throws MojoExecutionException {
        if (skip) {
            getLog().info("Skip create sources");
            return;
        }

        DirectoryScanner directoryScanner = new DirectoryScanner();
        directoryScanner.setBasedir(inputDirectory);
        directoryScanner.setIncludes(inputs);
        directoryScanner.scan();

        ProtoGenerator protoGenerator = new ProtoGenerator();
        for (String input : directoryScanner.getIncludedFiles()) {
            getLog().info("generate-code: " + input);
            createSources(protoGenerator, inputDirectory.toPath().resolve(input));
        }
    }

    private void createSources(ProtoGenerator protoGenerator, Path inputPath) throws MojoExecutionException {
        try {
            getLog().info("create sources: " + inputPath);
            Files.createDirectories(outputDirectory.toPath());
            PathProtoDestinations destinations = new PathProtoDestinations(outputDirectory.toPath());
            protoGenerator.generate(inputPath.toString(), new PathProtoSources(inputPath, importDirectory.toPath()), destinations);
            getLog().info("finished sources");
        } catch (IOException | RuntimeException e) {
            getLog().error(e.getMessage(), e);
            throw new MojoExecutionException(e);
        }
    }
}