terça-feira, 5 de maio de 2020

Using AntRun to run a Maven plugin on multiple files (if the plugin only allows 1 file at a time)


So, i was dealing with a plugin the other day that did not allow multiple declaration of files. Then i figured that Maven has a Maven run, that allows us to code a script to do it.
<properties>
...
    <joynr.generator.fidl.file>placeholder</joynr.generator.fidl.file>
...
</properties>
<plugins>
 ...
  <plugin>
    <groupId>io.joynr.tools.generator</groupId>
    <artifactId>joynr-generator-maven-plugin</artifactId>
    <version>${joynr.version}</version>

    <configuration>
      <model>${joynr.generator.fidl.file}</model>
      <generationLanguage>java</generationLanguage>
      <outputPath>${basedir}/src/main/generated-java</outputPath>
      <addVersionTo>package</addVersionTo>
    </configuration>
    
    <dependencies>
      <dependency>
        <groupId>io.joynr.tools.generator</groupId>
        <artifactId>java-generator</artifactId>
        <version>${joynr.version}</version>
      </dependency>
    </dependencies>
  </plugin>

  <plugin>
    <artifactId>maven-antrun-plugin</artifactId>
    <version>3.0.0</version>

    <executions>
      <execution>
        <phase>generate-sources</phase>
        <configuration>
          <target name="Generate Joynr Java artifacts from FIDL files">
            <apply executable="mvn" parallel="false">
              <arg value="io.joynr.tools.generator:joynr-generator-maven-plugin:generate" />
              <srcfile prefix="-Djoynr.generator.fidl.file=" />
              <fileset dir="src/main/resources">
                <patternset>
                  <include name="**/*.fidl" />
                </patternset>
              </fileset>
            </apply>
          </target>
        </configuration>
        <goals>
          <goal>run</goal>
        </goals>
      </execution>
    </executions>
  </plugin>
 ...
</plugins>

Let me explain a bit of what is happening in the above code: I'm declaring a variable that can be set from the command line environment using -Dvariable=value. Then i proceed to configure all the fixed parameters to the target plugin (in this case joynr-generator-maven-plugin), and then, i configure the Ant Run Plugin to run Maven for each FIDL file that it finds on a particular folder with more advanced filters (include/exclude).

Happy coding!