2012-04-17 70 views
1

匹配占位符删除文件,我有两个目录:在另一个目录树

source/aaa/bbb/ccc/file01.txt 
source/aaa/bbb/file02.txt 
source/aaa/bbb/file03.txt 
source/aaa/ddd/file03.txt 
source/file01.txt 

template/aaa/bbb/ccc/file01.txt 
template/aaa/bbb/DELETE-file03.txt 
template/aaa/DELETE-ddd 
template/DELETE-file01.txt 

使用Ant,我想要做的三件事情。首先,我想将任何文件从“模板”复制到“源”中,以便所有不以“DELETE-”开头的文件都被替换。例如,“source/aaa/bbb/ccc/file01.txt”将被替换。这是简单的搭配:

<copy todir="source" verbose="true" overwrite="true"> 
    <fileset dir="template"> 
     <exclude name="**/DELETE-*"/> 
    </fileset> 
</copy> 

其次,我想删除其名称匹配的“模板”树的相应目录下的“删除 - ”文件中的“源”树中的所有文件。例如,“source/aaa/bbb/file03.txt”和“source/file01.txt”都将被删除。我已经能够做到这一点:

<delete verbose="true"> 
    <fileset dir="source"> 
     <present present="both" targetdir="template"> 
      <mapper type="regexp" from="(.*[/\\])?([^/\\]+)" to="\1DELETE-\2"/> 
     </present> 
    </fileset> 
</delete> 

第三,我想删除其名称匹配的相同方式的任何目录(空或不)。例如,“template/aaa/DELETE-ddd”及其下的所有文件都将被删除。我不知道如何在目录在“模板”树中具有DELETE- *文件的“源”树中构建与目录(及其下的所有文件)相匹配的文件集。

这是第三个任务甚至可以用Ant(1.7.1)?我最好喜欢在不写任何自定义ant任务/选择器的情况下执行此操作。

回答

1

这似乎是造成这种困难的根本问题是,ant基于文件集目标目录中找到的文件驱动选择器/文件集。然而,通常情况下,人们会想要从DELETE- *标记文件列表中驱动事物。

迄今为止找到的最佳解决方案确实需要一些自定义代码。我选择了<groovy>任务,但也可以使用<script>

要点:创建一个文件集,使用groovy添加一系列用DELETE- *标记跳过文件和目录的排除项,然后执行复制。这完成了我的问题的第二个和第三个任务。

<fileset id="source_files" dir="source"/> 

<!-- add exclude patterns to fileset that will skip any files with a DELETE-* marker --> 
<groovy><![CDATA[ 
    def excludes = [] 
    new File("template").eachFileRecurse(){ File templateFile -> 
     if(templateFile.name =~ /DELETE-*/){ 
      // file path relative to template dir 
      def relativeFile = templateFile.toString().substring("template".length()) 
      // filename with DELETE- prefix removed 
      def withoutPrefix = relativeFile.replaceFirst("DELETE-", "") 
      // add wildcard to match all files under directories 
      def exclude = withoutPrefix + "/**" 
      excludes << exclude 
     } 
    } 
    def fileSet = project.getReference("source_files") 
    fileSet.appendExcludes(excludes as String[]) 
]]></groovy> 

<!-- create a baseline copy, excluding files with DELETE-* markers in the template directories --> 
<copy todir="target"> 
    <fileset refid="source_files"/> 
</copy> 
0

要删除一个目录及其内容使用delete with nested fileset,即:

<delete includeemptydirs="true"> 
    <fileset dir="your/root/directory" defaultexcludes="false"> 
    <include name="**/DELETE-*/**" /> 
    </fileset> 
</delete> 

随着属性includeemptydirs="true"目录也将被删除。

+0

我想你们误解了我的问题。我想从中删除文件/目录(源)的树不是与其中具有DELETE- *文件(模板)的树。 – GreenGiant 2012-04-18 14:21:16