Search code examples
ant

ant - how to get a zero resource count if the folder does not exist


I'm trying to base a task on whether a folder has content, not on whether it merely exists. I know there is probably a long winded solution, is there a better solution that I'm missing ?

I've tried two different methods to set a property depending on whether or not a folder has files in it.

My understanding is that 'available' does not permit wildcards like:

  <available property="has.test.data" file="${test.data.dir}/**" type="file"/>

I tried this but it does not work if the folder (test.data.dir) does not exist:

  <fileset id="test.data.files" dir="${test.data.dir}" includes="**/*" />
  <condition property="has.test.data">
    <resourcecount when="greater" count="0"> <fileset refid="test.data.files" /> </resourcecount>
  </condition>

Ideally, I want to base a task on whether the folder actually has content, not just an empty folder.


Solution

  • You can use erroronmissingdir="false", to avoid the error for a non-existing directory. Add else="false" if you need the property to always exist

    <?xml version="1.0" encoding="utf-8"?>
    <project name="Test resourcecount" xmlns:if="ant:if">
    
      <fileset id="test.data.files" dir="${test.data.dir}" includes="**/*" erroronmissingdir="false"/>
      <condition property="has.test.data" else="false">
        <resourcecount when="greater" count="0"> <fileset refid="test.data.files" /> </resourcecount>
      </condition>
    
      <echo if:true="${has.test.data}">${test.data.dir} is exists and is not empty</echo>
    
    
    </project>
    

    related Ant: How can I ignore build error if directory doesn't exist?