2011-05-09 49 views
7

我真的很喜欢Ant'sync'任务,但我需要做的是将文件从源文件夹复制到目标文件夹根据是否目标文件的内容与源文件的内容匹配,而不是检查文件修改日期(这是'同步'当前的操作)。有什么办法可以做到这一点?我注意到有一个用于文件内容的Ant比较器,以及一个可能派上用场的'校验和'任务。如何使用Ant的'同步'任务,但基于文件内容

谢谢!

+0

曾经考虑调用rsync的执行同步操作? – ewh 2011-05-20 05:02:13

+1

感谢您的想法。如果可能,我正在寻找一种基于蚂蚁的解决方案。 – 2011-05-20 20:02:12

回答

5

为别人击中这一点,需要的代码,这里是另一种基于内容而不是时间戳同步一个位置上的任务,它采用了修改选择,而不是不同选择在其他答案给了文件的差异是如何计算的更多的控制权:

<project name="Demo" default="newSync"> 
    <description> 
    Sync from ${foo} to ${bar} 
    </description> 

    <macrodef name="syncContents"> 
    <attribute name="from"/> 
    <attribute name="to"/> 
    <sequential> 
     <fileset id="selectCopyFiles" dir="@{from}"> 
     <modified algorithm="hashvalue"/> 
     </fileset> 
     <fileset id="selectDeleteFiles" dir="@{to}"> 
     <not> 
      <present targetdir="@{from}"/> 
     </not> 
     </fileset> 

     <copy overwrite="true" todir="@{to}"> 
     <fileset refid="selectCopyFiles"/> 
     </copy> 
     <delete includeEmptyDirs="true"> 
     <fileset refid="selectDeleteFiles"/>    
     </delete> 
    </sequential> 
    </macrodef> 

    <target name="newSync"> 
    <syncContents from="${foo}" to="${bar}"/> 
    </target> 
</project> 

注意,这使得柱状镜富(同步A-> B),如果你想有一个双向同步,你可以更换一个副本从B-删除> A,并提供一个concat任务来处理对两个位置中相同文件的更改。

1

谢谢你的任务!

但是,selectCopyFiles文件集不正确。我还为selectDeleteFiles文件集提供了另一种解决方案。

这里是macrodef的新代码:

<macrodef name="syncContents"> 
    <attribute name="from"/> 
    <attribute name="to"/> 
    <sequential> 
     <echo>syncContents  : @{from} -> @{to}</echo> 
     <fileset id="selectCopyFiles" dir="@{from}"> 
      <different targetdir="@{to}" 
      ignoreFileTimes="true"/> 
     </fileset> 
     <fileset id="selectDeleteFiles" dir="@{to}"> 
      <present present="srconly" targetdir="@{from}"/> 
     </fileset> 

     <copy overwrite="true" todir="@{to}" preservelastmodified="true" verbose="true"> 
      <fileset refid="selectCopyFiles"/> 
     </copy> 
     <delete includeEmptyDirs="true" verbose="true"> 
      <fileset refid="selectDeleteFiles"/> 
     </delete> 
     <echo>End syncContents : @{from} -> @{to}</echo> 
    </sequential> 
</macrodef>