Question

It sounds a little far fetched to me, but is there an ANT task for watching a directory for changes and then running a particular ANT class when the directory changes?

Was it helpful?

Solution

If files can only be added to or changed in the watched directory, then you can use this simple OutOfDate task from antcontrib.

<property name="watched-dir.flagfile"
  location="MUST be not in watched dir"/>
<outofdate>
  <sourcefiles>
    <fileset dir="watched-dir"/>
  </sourcefiles>
  <targetfiles>
    <pathelement location="${watched-dir.flagfile}"/>        
  </targetfiles>
  <sequential>

    <!--Tasks when something changes go here-->

    <touch file="${watched-dir.flagfile}"/>
  </sequential>
</outofdate>

If files can disappear from the watched-dir, then you have more complicated problem, that you can solve by creating shadow directory structure of the watched dir and checking if its consistent with the watched-dir. This task is more complex, but I'll give you a script to create a shadow directory, as it is not straight forward:

<property name="TALK" value="true"/>
<property name="shadow-dir"
  location="MUST be not in watched dir"/>

<touch
  mkdirs="true"
  verbose="${TALK}"
>
  <fileset dir="watched-dir">
    <patterns/>
    <type type="file"/>
  </fileset>

  <!-- That's the tricky globmapper to make touch task work -->
  <globmapper from="*" to="${shadow-dir}/*"/>
</touch>

<!--
  Due to how touch task with mapped fileset is implemented, it 
  truncates file access times down to a milliseconds, so if you 
  would have used outofdate task on shadow dir it would always 
  show that something is out of date.

  Because of that, touching all files in ${shadow-dir} again fixes
  that chicken and egg problem.
-->
<touch verbose="${TALK}">
  <fileset dir="${shadow-dir}"/>
</touch>

With shadow directory created, I'll leave the task of checking directory consistency as an exercise for the reader.

OTHER TIPS

Yes there is an Ant Task that will do this:

https://github.com/chubbard/WatchTask

It requires 1.7+. It can watch any number of filesets, and invoke any target depending on which fileset it came from.

You might be able to use the Waitfor task to achieve what you want. It blocks until one or more conditions (such as the presence of a particular file) become true.

You can combine the apply task with a fileset selector

<apply executable="somecommand" parallel="false">
  <srcfile/>
  <fileset dir="${watch.dir}">
    <modified/>
  </fileset>
</apply>

The fileset will check the files against a stored MD5 checksum for changes. You'll need to put ANT into a loop in order to repeatedly run this check. this is easy to do in Unix:

while true
> do
> ant
> sleep 300
> done
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top