Ant Purge Task

The purge tasks works with Ant to remove all but the most recent few files from a fileset. For example: let's say you're using an automated build tool, such as Cruise Control, which generates files (logs?) each time it's run. You can use the purge task to keep just the most recent few files --- rather than allowing the directory to fill with old files.

This task has been built against JDK 1.4 with Ant 1.4.1 and tested with Ant 1.4.1 and 1.5.1.

To use Purge...

  1. read the Apache 2.0 license for this software;
  2. download purge.jar (this includes source, javadoc and classes);
  3. put purge.jar in your Ant's "lib" folder;
  4. add the task def to your build script;
  5. and then
  6. add a <purge> tag to build.xml
  7. if you want to contribute, the source is hosted at google code.

For example:

	<taskdef name="purge" classname="com.dallaway.ant.Purge"/>
	...
	<purge test="true" keep="5">
		<fileset dir="logs"/>
	</purge>

This would delete all but the most recent five files from the "logs" folder. However, as the test attribute is true it will actually just reports on the files it would have deleted. Remove the test attribute (or set it false) to really delete the files.

Note that folders are not deleted by this task.

If you have more than one fileset, each fileset is purged individually. This is described in the next example.

A longer example

Construct this build.xml file:

	<?xml version="1.0"?>
	
	<project name="project" default="main" basedir=".">

	<taskdef name="purge" classname="com.dallaway.ant.Purge"/>
	
	<target name="main">
		<purge test="true" keep="5">
			<fileset dir="logs"/>
			<fileset dir="output"/>
		</purge>
	</target>
	</project>

Then run these commands (non-Unix users: a command like "touch 9" simply creates a file called "9" with a last modified time of "right now").

mkdir logs
cd logs
touch 9
touch 8
touch 7
touch 6
touch 5
touch 4
touch 3
touch 2
touch 1
cd ..
mkdir output
cd output
touch 1 
touch 2
touch 3
touch 4
touch 5
touch 6
cd ..
ant

The output from ant is:

Buildfile: build.xml

main:
    [purge] Purging /home/richard/logs
    [purge] Would keep /home/richard/logs/1
    [purge] Would keep /home/richard/logs/2
    [purge] Would keep /home/richard/logs/3
    [purge] Would keep /home/richard/logs/4
    [purge] Would keep /home/richard/logs/5
    [purge] Would delete /home/richard/logs/6
    [purge] Would delete /home/richard/logs/7
    [purge] Would delete /home/richard/logs/8
    [purge] Would delete /home/richard/logs/9
    [purge] Purging /home/richard/output
    [purge] Would keep /home/richard/output/6
    [purge] Would keep /home/richard/output/5
    [purge] Would keep /home/richard/output/4
    [purge] Would keep /home/richard/output/3
    [purge] Would keep /home/richard/output/2
    [purge] Would delete /home/richard/output/1

BUILD SUCCESSFUL
Total time: 3 seconds

 

 

last modified Saturday, 06-Apr-2013 17:26:33 BST | Contact