Search code examples
maven

Pad Number With Zeros in Maven


Is there a way to have maven pad a numeric value (ex: build number) within a POM? I've been googling the topic and haven't come up with anything yet.

My use case is as follows. The maven build process is provided a build number via Jenkins which needs to be included as part of the name of the WAR that is generated. So if I provide it 12 as the build number, then I want the WAR file name to be myWar##000012.war. The ##000012 part of the name is the version identifier used by Tomcat.


Solution

  • The simplest solution may be to embed a scripting language in your build. For example, with Groovy, if you have a buildNumber property:

       <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>groovy-maven-plugin</artifactId>
        <version>1.5</version>
        <executions>
         <execution>
         <phase>validate</phase>
         <goals><goal>execute</goal></goals>
         <configuration>
          <source>
           project.properties['nameSuffix'] = "##" + String.format("%06d", project.properties['buildNumber'].toLong());
          </source>
         </configuration>
         </execution>
        </executions>
       </plugin>
    

    Afterwards the nameSuffix property is available to define the final name.

    Alternatively, as suggested in In Maven, how can I dynamically build a property value at runtime?, use build-helper:regex-property to transform the string.