ANT How to delete ONLY empty directories recursively

最后都变了- 提交于 2019-12-05 02:49:00

Here's the best answer I've been able to come up with:

<delete includeemptydirs="true">
  <fileset dir="${dirToStartFrom}"  >
    <and>
      <size value="0"/>
      <type type="dir"/>
     </and>
  </fileset>
</delete>

I then wrapped it in a macro so I can pass the dir name in from any target:

<!-- Find and delete empty folders under dir -->
<macrodef name="deleteEmptyFolders">
    <attribute name="dir"/>
    <sequential>
        <delete includeemptydirs="true">
            <fileset dir="@{dir}"  >
                <and>
                    <size value="0"/>
                    <type type="dir"/>
                </and>
            </fileset>
        </delete>
    </sequential>
</macrodef>

Like so:

<target name="clean">
  <deleteEmptyFolders dir="build"/>
  <deleteEmptyFolders dir="common"/>
  <deleteEmptyFolders dir="lib"/>
</target>

Here's what I cooked up:

<!-- next three targets are connected
     To remove empty folders from XXX folder.  Process is recursed 3 times.  This 
     is necessary because parent directories are not removed until all their children
     are (if they are empty), and parents are processed before children 
      My example will process structures 3 deep, if you need to go deeper
      then add members to the list  like list="1,2,3,x,x,x,x,x,x"  -->

<target name="rmmtdirs">
        <foreach list="1,2,3" target="rmmtdirs_recurse" param="num"/>
</target>

<target name="rmmtdirs_recurse">
        <foreach target="rmmtdir" param="rmdir">
            <path>
                <dirset dir="${XXX}"/>
            </path>
        </foreach>
</target>

<target name="rmmtdir">
        <echo message=" Removing: ${rmdir} "/>
        <delete includeemptydirs="true">
                <fileset dir="${rmdir}" excludes="**/*"/>
        </delete>
</target>

If it is not sufficient to completely clear the target location (use defaultExcludes="false" to ensure the .svn folders are deleted), you could try writing a custom ant task to traverse the file system below the target, deleting empty directories as you move back up from each leaf.

This is probably easier to do with a batch file that gets called from ant.

You can use Raymond Chen's script, but it doesn't work if there are spaces in the names.

I was able to delete all the empty directories starting with the current working directory with the following:

<delete includeemptydirs="true">
    <fileset dir="." includes="**" excludes="**/*.*" />
</delete>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!