【发布时间】:2009-02-06 14:49:43
【问题描述】:
是否存在仅当给定文件存在时才会执行块的 ANT 任务?我的问题是我有一个通用的 ant 脚本,它应该进行一些特殊处理,但前提是存在特定的配置文件。
【问题讨论】:
标签: file ant build-automation
是否存在仅当给定文件存在时才会执行块的 ANT 任务?我的问题是我有一个通用的 ant 脚本,它应该进行一些特殊处理,但前提是存在特定的配置文件。
【问题讨论】:
标签: file ant build-automation
【讨论】:
if 和 unless 属性仅启用或禁用它们所附加的目标,即始终执行目标的依赖项。否则,依赖于设置您正在检查的属性的目标是行不通的。
<Available> 已被弃用。我用过这个:<target name="do-if-abc" if="${file::exists('abc.txt')}"> ... </target> 检查:nant.sourceforge.net/release/0.85/help/functions/…
<available> 已弃用? 2: ${file::existst...} 似乎无法与 Ant (Apache ANT 1.9.7) 一起使用
从编码的角度来看,这可能更有意义(可通过 ant-contrib 获得:http://ant-contrib.sourceforge.net/):
<target name="someTarget">
<if>
<available file="abc.txt"/>
<then>
...
</then>
<else>
...
</else>
</if>
</target>
【讨论】:
自 Ant 1.8.0 以来,显然也存在资源
从 http://ant.apache.org/manual/Tasks/conditions.html
测试资源是否存在。自从 蚂蚁 1.8.0
要测试的实际资源是 指定为嵌套元素。
一个例子:
<resourceexists> <file file="${file}"/> </resourceexists>
我打算从上面对这个问题的好答案中重新编写示例,然后我发现了这个
从 Ant 1.8.0 开始,您可以改为使用 财产扩张;真值 (或 on 或 yes)将启用该项目, 而假(或关闭或否)将 禁用它。其他值还在 假定为属性名称等 仅当命名的项目才启用 属性已定义。
与旧款相比,这款 为您提供额外的灵活性, 因为你可以覆盖条件 从命令行或父级 脚本:
<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"/>
来自http://ant.apache.org/manual/properties.html#if+unless的蚂蚁手册
希望这个例子对某些人有用。他们没有使用resourceexists,但大概你可以?.....
【讨论】:
if="${file.exists}" 应替换为 if="file.exists",如 if 和 unless 仅按名称检查属性的存在,而不是其值。
我认为值得参考这个类似的答案: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>
【讨论】:
DB_*/**/*.sql
如果存在与通配符过滤器相对应的一个或多个文件,这是一种执行操作的变体。也就是说,您不知道文件的确切名称。
在这里,我们递归地在名为“DB_*”的任何子目录中查找“*.sql”文件。您可以根据需要调整过滤器。
注意: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>
【讨论】:
您可以通过命令对名称与您需要的名称相同的文件列表执行操作来完成此操作。这比创建一个特殊的目标要容易和直接得多。而且你不需要任何额外的工具,只需要纯 Ant。
<delete>
<fileset includes="name or names of file or files you need to delete"/>
</delete>
请参阅:FileSet。
【讨论】: