2009-02-06 71 views
145

是否有ANT任务只在给定文件存在时才会执行块?我有问题,我有一个通用的蚂蚁脚本,应该做一些特殊的处理,但只有当一个特定的配置文件存在。仅当文件存在时Ant任务才能运行Ant目标?

+0

参见[如何在Ant的可用命令中使用通配符](http://stackoverflow.com/questions/1073077/how-to-use-wildcard-in-ants-available-command/) – Vadzim 2013-10-07 08:03:02

回答

192

AvailableCondition

<target name="check-abc"> 
    <available file="abc.txt" property="abc.present"/> 
</target> 

<target name="do-if-abc" depends="check-abc" if="abc.present"> 
    ... 
</target> 
+8

可用是一个非常明显的名字,它的作用。谷歌显示人们编写自己的标签 – 2009-02-06 19:42:29

+2

看起来不适用于Ant 1.6.2,这让我更加困惑。 – djangofan 2011-04-16 00:56:07

+0

它对我很好(Ant 1.8.2)。谢谢。 – 2011-11-01 15:46:36

115

这可能使从编程角度来说,多了几分感(可用蚂蚁的contrib:http://ant-contrib.sourceforge.net/):

<target name="someTarget"> 
    <if> 
     <available file="abc.txt"/> 
     <then> 
      ... 
     </then> 
     <else> 
      ... 
     </else> 
    </if> 
</target> 
25

由于蚂蚁1.8.0有显然也资源存在

http://ant.apache.org/manual/Tasks/conditions.html

测试存在的资源。自 Ant 1.8.0

要测试的实际资源是指定为嵌套元素的 。

一个例子:

<resourceexists> 
    <file file="${file}"/> 
</resourceexists> 

我正要从上面很好地回答了这个问题返工的例子,然后我发现这个

蚂蚁1.8.0,你可改用 进行物业扩张;值为真 (或开或是)将启用项目, ,而虚假(或关或不)将 禁用它。其他值仍然是 假定为属性名称,因此 只有在定义了名为 的属性时才启用该项目。

相比老款的风格,这种 为您提供了额外的灵活性, 因为你可以通过命令行或家长忽略该情况 脚本:在http://ant.apache.org/manual/properties.html#if+unless

<target name="-check-use-file" unless="file.exists"> 
    <available property="file.exists" file="some-file"/> 
</target> 
<target name="use-file" depends="-check-use-file" if="${file.exists}"> 
    <!-- do something requiring that file... --> 
</target> 
<target name="lots-of-stuff" depends="use-file,other-unconditional-stuff"/> 

从蚂蚁手册

希望这个例子对某些人有用。他们不使用resourceexists,但想必你会.....

10

我认为它的价值引用此类似的答案:https://stackoverflow.com/a/5288804/64313

这里是一个又一个快速的解决方案。有可能在此其他变化使用<available>标签:

# exit with failure if no files are found 
<property name="file" value="${some.path}/some.txt" /> 
<fail message="FILE NOT FOUND: ${file}"> 
    <condition><not> 
     <available file="${file}" /> 
    </not></condition> 
</fail> 
0

您可以通过订购与文件等于你需要的姓名(或名称)名称的列表做手术做到这一点。比创建一个特殊的目标要容易和直接得多。而且你不需要任何额外的工具,只需要纯粹的Ant。

<delete> 
     <fileset includes="name or names of file or files you need to delete"/> 
    </delete> 

http://ant.apache.org/manual/Types/fileset.html

2

检查使用文件名过滤器,如 “DB _ */**/*。SQL”

这里是如果一个或多个文件是否存在对应于通配符执行动作的变化过滤。也就是说,你不知道文件的确切名称。

在这里,我们正在寻找任何子目录 “* .SQL” 文件名为 “DB_ *”,递归。您可以根据需要调整过滤器。

注意:Apache Ant 1.7及更高版本!

下面是设置属性的目标是否存在匹配的文件:

<target name="check_for_sql_files"> 
    <condition property="sql_to_deploy"> 
     <resourcecount when="greater" count="0"> 
      <fileset dir="." includes="DB_*/**/*.sql"/> 
     </resourcecount> 
    </condition> 
</target> 

这里是“有条件”的目标,只有运行是否存在文件:

<target name="do_stuff" depends="check_for_sql_files" if="sql_to_deploy"> 
    <!-- Do stuff here --> 
</target>