Press "Enter" to skip to content

Renaming files on build-time with Maven

There are quite a lot of situations when you’d need to rename a file during build time, I had this problem a few weeks ago when I had to generate a unique name for a JavaScript file in order to avoid browser caching.

Copy Rename Maven Plugin example
Copy Rename Maven Plugin example

In order to do this I’ve been using the copy-rename-maven-plugin. Setting it up is just like taking candy from a baby, you simply add the plugin to your pom.xml:


<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>net.gazsi.laszlo</groupId>
    <artifactId>sandbox</artifactId>
    <version>1.0-SNAPSHOT</version>

    <build>
        <plugins>
            <plugin>
                <groupId>com.coderplus.maven.plugins</groupId>
                <artifactId>copy-rename-maven-plugin</artifactId>
                <version>1.0</version>
                <executions>
                    <execution>
                        <id>copy-file</id>
                        <phase>prepare-package</phase>
                        <goals>
                            <goal>rename</goal>
                        </goals>
                        <configuration>
                            <sourceFile>target/classes/randomresource.xml</sourceFile>
                            <destinationFile>target/classes/randomresource.${build}.xml</destinationFile>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

Here I simply generate the new name of the file based on a parameter ${build}, which can be any string passed from the command line, in my case it was the Jenkins build number. So using this maven plugin I could generate a unique filename per Jenkins build for the JavaScript resource. In this example I’ve renamed an XML file in the prepare-package phase. You may modify the phase to fit your needs. I’d also advise you to check out the homepage of the plugin for further features (copy/rename, even multiple files at the same time) and further examples.

In order to pass the ${build} parameter, my example mvn call looks like this:
clean install -Dbuild=88

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *