jGuru
Register Email     Password Forgot your
password?
HOME FAQS FORUMS DOWNLOADS ARTICLES PEERSCOPE LEARN

  Search   jGuru Search Help

Question Can Ant increment a build number?
Derived from A question posed by Joseph Biron
Topics Tools:Build:Ant
Author Joseph Biron
Created Aug 22, 2001


Answer
Check out Ant's optional <propertyfile> task. It has numeric incrementing capability (as well as string append and date calculation capabilities). By auto-incrementing a number from a properties file, and then reading the properties file using the <property file="..."> task you can easily implement auto-incrementing build numbers.

Is this item helpful?  yes  no     Previous votes   Yes: 2  No: 0



Comments and alternative answers

Comment on this FAQ entry

increment build number
akshat garg, Nov 14, 2001  [replies:4]
please help me in finding Ant's optional <propertyfile> task

Is this item helpful?  yes  no     Previous votes   Yes: 0  No: 0



Reply to this answer/comment  Help  
Re: increment build number
K rapp, Dec 4, 2001  [replies:3]

I tried the property file task. But everytime I run the script, it rewrites the properties file and therefore always starts from 0 instead of going onto the next higher number, in this case "1".

Are there any examples on how to increment existing numbers rather than taking current time and date as it is explained in the documentation? Ant would have to be able to read off the properties file first to be able to increment it. Does Ant support this?

Thanks for all your help

Kerstin



Is this item helpful?  yes  no     Previous votes   Yes: 0  No: 0



Reply to this answer/comment  Help  
Re[2]: increment build number
Erik Hatcher PREMIUM, Dec 4, 2001  [replies:2]
Are you using the default attribute on the <entry> tags?

Please provide an example the code that is causing the problems. Also, what version of Ant are you using?

Is this item helpful?  yes  no     Previous votes   Yes: 0  No: 0



Reply to this answer/comment  Help  

Re[3]: increment build number
K rapp, Dec 5, 2001  [replies:1]
I figured it out how to keep it incrementing, rather than overwriting, but for some reason it doesn't resolve the key="build.number" so I can call it later to label the sources in VSS"

I will add the code and error message. 

Thanks, Kerstin

Code:

<target name="usage">

<propertyfile file="./build.properties">
	<entry key="minor.number" type="int" operation="+" value="1" pattern="00"/>
    </propertyfile>
   
   <echo message= "Build ${minor.number}"/>
    
</target>

error:


[propertyfile] Updating property file: (rather long path to)  .....\build.properties
    Property ${minor.number} has not been set
     [echo] Build ${minor.number}
     [echo] 

BUILD SUCCESSFUL



Is this item helpful?  yes  no     Previous votes   Yes: 0  No: 0



Reply to this answer/comment  Help  
Re[4]: increment build number
Erik Hatcher PREMIUM, Dec 5, 2001
<propertyfile> does not load the the file into Ant properties. That is why ${minor.number} is not resolving in the above example. You should load the file with <property file="./build.properties"/>

Is this item helpful?  yes  no     Previous votes   Yes: 0  No: 0



Reply to this answer/comment  Help  
Can Ant Increment a build number yes it can....
Gary Leeson, Feb 6, 2002  [replies:4]

I needed Ant to do this on a recent project...but I wanted it to be built into the resulting product itself. What I did was to use a custom ant task to generate a JAVA source file containing the version, build number etc. Values were taken from a property file (maj version, minor version, build number) which kept track of the build number.

Works very well. It might not be quite what you want but it does exactly what we want it to do

/********************************************************************
* Simple class that generates a java file containing a 
* build version sequence number.
*
* Version 1.0: By gremlin@indigo.ie June 12 2001
*
* Build sequence numbers are of the form:
*
* <version>.<subversion>:<buildnumber>
*
* The class generated exposes the 
*
*  getBuildVersion();         // the whole lot
*  getBuildNumber();         // the build number
*  getVersion();          // the build/product version
*  getRevision();          // the build/product update/revision
*  toString();              // the build/product update/revision
*
* The ant task works by keeping track of the buildnumber in a file
* stored within the /var/ant directory and incrementing it after
* creating the simple java class file.
*
*********************************************************************/

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;

import java.util.*;
import java.io.*;

public class BuildVersion extends Task 
{
  private String version="0";
  private String revision="0";
  private long  buildNumber = -1;
  private String baseDir=null;  // The root of the source tree
  private String projectName="UKNOWN";
  private String packageName=null;
  
/*********************************************************************
* Creates the file
**********************************************************************/
  public void execute() throws BuildException 
  {
    buildNumber = getNextBuildNumber();
 PrintStream out = null;
 System.out.println("    [build] creating : "+getFilename());
 try
  {
    out = new PrintStream( new FileOutputStream(getFilename()));
    
      out.println("/***************************************************/");
       out.println("// AUTO GENERATED BY ANT ");
    out.println("// "+projectName+" Build = "+version+"."+revision+"."+buildNumber);
    out.println("// File : "+getFilename());
    out.println();
    if(packageName != null )
     {
   out.println("package "+packageName+";");
     out.println();
     }
   out.println("import java.util.Date;");
   out.println();
   out.println("public class BuildVersion");
   out.println("{");
   out.println("  public String toString() {return getBuildVersion();}");
   out.println("  public String getBuildVersion() { return \""+version+"."+revision+"."+buildNumber+"\"; }");
   out.println("  public String getBuildNumber() {return \""+buildNumber+"\";}");
   out.println("  public String getVersion() {return \""+version+"\";}");
   out.println("  public String getRevision() {return \""+revision+"\";}");
   out.println("  public String getBuildDate() {return \""+(new Date()).toString()+"\";}");
   out.println("}");
   out.println("/******************** END OF FILE ***************/");
   out.println();
  }
  catch(Exception ex)
  {
    throw new BuildException(ex.getMessage());
  }
  finally
  {
    if( out != null ) 
     {
    try{ out.close(); out=null;} catch(Exception ex1){;}
  }
  }
  }
  
/*********************************************************************
* generates the output file name
**********************************************************************/
File getFilename()
{
  File ret = null;
  String par = null;
  
  if( packageName == null ) return new File("BuildVersion.java");
  par = packageName.replace('.','/');
  par += "/BuildVersion.java";
  if(baseDir!= null) par = ""+baseDir+"/"+par;
  
  return new File(par);
}

/*********************************************************************
* Sets the product version
**********************************************************************/
  public void setVersion(String msg) 
  {
    version = msg;
  }
  
  
/*********************************************************************
* Sets the product revision
**********************************************************************/
  public void setReVision(String msg) 
  {
    revision = msg;
  }
  
  
 /*********************************************************************
* Sets the basedir of the source tree.
**********************************************************************/
public void setBaseDir(String dir)
{
  baseDir = dir;
}
   
 /*********************************************************************
* Sets the package name
**********************************************************************/
public void setPackageName(String packageName)
{
  this.packageName = packageName;
}
 
 /*********************************************************************
* Sets the project name of the source tree.
**********************************************************************/
public void setProductName(String name)
{
  projectName = name;
}

/*********************************************************************
* This function gets the next build sequence generating
* storage in "/var/ant" as appropriate and overwriting it
* afterwards.
*
* Returns -1 if cannot access file etc
**********************************************************************/
long getNextBuildNumber()
{
  File theFile = new File("/var/ant/"+projectName+"_"+version+"_"+revision+".txt");
  Properties prop = new Properties();
  long ver = -1;
  InputStream input = null;
  OutputStream output = null;
  
  try
  {
             // 1 - Read file
 //     System.out.println("\t\tReading Configuration in '"+theFile+"'");
      if( theFile.exists())
   {
        input = new FileInputStream(theFile);
        prop.load(input);
        input.close();
  input = null;
   } 
     if( prop.containsKey("buildnumber"))
    ver = (new Integer((String)prop.get("buildnumber"))).longValue();
  else 
    ver = 0;
             // 2 - update and re-write
 prop.put("buildnumber",""+(++ver));
    output = new FileOutputStream(theFile);
 prop.store(output,"Build Number System for "+projectName);
 output.close();
 output = null;
// System.out.println("Build number = "+ver);
  }
  catch(Exception ex)
  {
    ver =  -1;
  }
    finally
    {
      try
      {
        if( input != null ) input.close();
        if( output != null ) output.close();
      }
      catch(Exception n){;}
    }
  return ver;
} 
  
}


/*************** END OF FILE *************************************/


Is this item helpful?  yes  no     Previous votes   Yes: 0  No: 0



Reply to this answer/comment  Help  
Re: Can Ant Increment a build number yes it can....
Erik Hatcher PREMIUM, Feb 6, 2002  [replies:3]
That was a lot of effort to do something that you could have done much easier.... you could have written the Java class with @VERSION@ tags and used the <replace> or <copy> task to create a build-time source module that gets compiled instead of the templated one.

Is this item helpful?  yes  no     Previous votes   Yes: 0  No: 0



Reply to this answer/comment  Help  
Re[2]: Can Ant Increment a build number yes it can....
Gary Leeson, Feb 6, 2002  [replies:2]
True. But I prefer something independent of a versioning system - some of the companies I have worked for don't use them :-(

Is this item helpful?  yes  no     Previous votes   Yes: 0  No: 0



Reply to this answer/comment  Help  
Re[3]: Can Ant Increment a build number yes it can....
Erik Hatcher PREMIUM, Feb 7, 2002  [replies:1]
Huh? <replace> and filtered <copy> are independent of a versioning system. Do you mean source code control when refering to a "versioning system"?

Is this item helpful?  yes  no     Previous votes   Yes: 0  No: 0



Reply to this answer/comment  Help  
Re[4]: Can Ant Increment a build number yes it can....
Gary Leeson, Feb 7, 2002
Yes. Sorry not with it this morning. I received some tragic family news so you will I hope understand.

Is this item helpful?  yes  no     Previous votes   Yes: 0  No: 0



Reply to this answer/comment  Help  
Here is a solution I came up with to autogenerate an html file with build # and build date.
Brendan Patterson, Mar 18, 2003  [replies:3]
1) add this target to your build.xml
-----------
    <!-- this target will automatically create an html file with
    an incremented build number and version number-->
    <target name="versionInfo" depends="props" >
        <propertyfile
            file="version.properties" comment="Build version info">
            <entry key="buildDate" type="date" value="now"/>
            <entry key="buildNum" default="0" type="int" operation="+" value="1"/>
        </propertyfile>
        <copy file="${web-source-dir}/version.html" tofile="${build-dir}/version.html" overwrite="true" />
        <replace
            file="${build-dir}/version.html"
            value="value not found in version.properties"
            propertyFile="version.properties">
            <replacefilter
                token="@buildDate@"
                property="buildDate"/>
            <replacefilter
                token="@buildNum@"
                property="buildNum"/>
        </replace>
    </target>

----------
2) put a an html file like this in the right place
to have its values populated  by the above target
-----------

- Project - Version - Build # - Build Date
My Proj - 1.0 - @buildNum@ - @buildDate@
-----------



The end result of this is having ANT automatically populate an html file with build version info that can then be referenced by a user of the webapp. Its pretty slick.

Is this item helpful?  yes  no     Previous votes   Yes: 2  No: 0



Reply to this answer/comment  Help  
Re: Here is a solution I came up with to autogenerate an html file with build # and build date.
Mani Achanta, Sep 1, 2004
Is there anyway that I can add a version automatically to the HTML file (just like @buildNum@ and @buildDate@). The format of the version number should be "2.87.buildnumber". where, 2 - Major version 87 - Minor version. By default the "entry key" field in "PropertyFile" task supports only int, date or string. How can i auto-increment the minor/major version only and print it out to the HTML file? Thanks in Advance! Mani

Is this item helpful?  yes  no     Previous votes   Yes: 0  No: 0



Reply to this answer/comment  Help  
Re: Here is a solution I came up with to autogenerate an html file with build # and build date.
Norman Wright, May 13, 2005  [replies:1]
THANKS This was exactly what I was looking for.

Is this item helpful?  yes  no     Previous votes   Yes: 0  No: 0



Reply to this answer/comment  Help  
Re[2]: Here is a solution I came up with to autogenerate an html file with build # and build date.
Pavel Vlasov, Jul 17, 2006
You might want to take a look at more sophisticated build numbering solution: Build Number Ant Task

Is this item helpful?  yes  no     Previous votes   Yes: 0  No: 0



Reply to this answer/comment  Help  


Ask A Question



 
Related Links

Ant FAQ

Ant Forum

Ant Homepage

Sun: Best Practices

Hatcher Ant Book

Hatcher Ant Book

Automate your build process using Java and Ant

Wish List
Features
About jGuru
Contact Us

 


Internet.com
The Network for Technology Professionals

Search:

About Internet.com

Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | E-mail Offers