The Maven Cookbook

2.3. Executing Groovy Scripts in a Maven Build

2.3. Executing Groovy Scripts in a Maven Build

2.3.1. Task

You need to execute one or more groovy scripts in a Maven build.

2.3.2. Action

Configure the execute goal of the GMaven plugin, reference the Groovy script in the source configuration for the execution. The example POM shown in Example 2.2, “Executing External Groovy Scripts in a Maven Build” configures two executions of the execute goal referencing two scripts stored in ${basedir}/src/main/groovy.

Example 2.2. Executing External Groovy Scripts in a Maven Build

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0                        
                             http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.sonatype.mcookbook</groupId>
  <artifactId>groovy-script-ex</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>groovy-script-ex</name>
  <dependencies>
    <dependency>
      <groupId>org.apache.maven</groupId>
      <artifactId>maven-model</artifactId>
      <version>2.2.0</version>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>org.codehaus.groovy.maven</groupId>
        <artifactId>gmaven-plugin</artifactId>
        <executions>
          <execution>
            <id>create-deps-file</id>
            <phase>process-classes</phase>
            <goals>
              <goal>execute</goal>
            </goals>
            <configuration>
              <source>${basedir}/src/main/groovy/CreateDeps.groovy</source>
            </configuration>
          </execution>
          <execution>
            <id>copy-the-source</id>
            <phase>prepare-package</phase>
            <goals>
              <goal>execute</goal>
            </goals>
            <configuration>
              <source>${basedir}/src/main/groovy/CopySource.groovy</source>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>

The CreateDeps.groovy script creates a file named deps.txt in ${basedir}/target/classes which contains a list of direct project dependencies, and the CopySource.groovy script copies the source from ${basedir}/src/main/java to ${basedir}/target/classes.

Example 2.3. The CreateDeps.groovy Script

def depFile = new File(project.build.outputDirectory,
              'deps.txt')

project.dependencies.each() {
  depFile.write("${it.groupId}:${it.artifactId}:${it.version}")
}

Example 2.4. The CopySource.groovy Script

ant.copy(todir: project.build.outputDirectory ) {
  fileset(dir: project.build.sourceDirectory)
}