When doing nightly builds we have been needing an auto-incrementing build number.
I have put together a simple task that increments a property from a Java property file. i.e. reads in the properties, increments the number, sets the new property and writes out the property file.
Attached is the class. Is this a usefull task that you would like to add to the Ant distribution? Either main or optional? If yes then please take and add required licence to top of file.
Thanks. Stuart.
package org.apache.tools.ant.taskdefs;
import org.apache.tools.ant.*; import java.io.*; import java.util.*; /** * Allows a particular property in a Java property file to be incremented by * one. Useful for build numbers that increase by one with each build. * * @author Stuart Barlow <a href="mailto:[EMAIL PROTECTED]">[EMAIL PROTECTED]</a> * @author <a href="mailto:[EMAIL PROTECTED]">Stuart Barlow</a> */ public class IncrementProperty extends Task { private File src = null; private String property = null; /** * Do the execution. */ public void execute() throws BuildException { if (property == null) { throw new BuildException("replace token must not be null", location); } log("Incrementing " + property + " in file: " + src); if (src != null) { processFile(src); } } /** * Perform the increment of a property value on the given file. * * The replacement is performed on a temporary file which then replaces the original file. * * @param src the source file */ private void processFile(File src) throws BuildException { if (!src.exists()) { throw new BuildException("Increment: source file " + src.getPath() + " doesn't exist", location); } File temp = new File(src.getPath() + ".temp"); if (temp.exists()) { throw new BuildException("Replace: temporary file " + temp.getPath() + " already exists", location); } Properties propFile = new Properties(); try { // load in the property file FileInputStream in = new FileInputStream(src); propFile.load(in); in.close(); } catch (IOException ioe) { ioe.printStackTrace(); throw new BuildException(ioe, location); } try { // get the old value and set the new one. String strValue = propFile.getProperty(property); long longValue = Long.parseLong(strValue); longValue++; Long newIncrementedValue = new Long(longValue); propFile.setProperty(property, newIncrementedValue.toString()); // write out the property file FileOutputStream out = new FileOutputStream(src); propFile.store(out, "Ant - written out by the task: IncrementProperty"); out.close(); } catch (Exception ex) { ex.printStackTrace(); throw new BuildException(ex, location); } } /** * Set the source file. */ public void setFile(File file) { this.src = file; } /** * Set the string token to replace. */ public void setProperty(String property) { this.property = property; } }
