仅当文件存在时才运行Ant目标的Ant任务?

Mar*_*gón 150 ant build-automation file

是否存在仅在给定文件存在时才执行块的ANT任务?我有一个问题,我有一个通用的ant脚本,应该做一些特殊的处理,但只有在存在特定的配置文件.

too*_*kit 199

可用条件

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

<target name="do-if-abc" depends="check-abc" if="abc.present">
    ...
</target> 
Run Code Online (Sandbox Code Playgroud)

  • 对于它的作用,可用是一个非常明显的名称.谷歌向人们展示自己的标签,这让我更加困惑 (8认同)
  • 如果有人想知道,`if`和`unless`属性只启用或禁用它们所附加的目标,即始终执行目标的依赖项.否则,依赖于设置您正在检查的属性的目标将无法工作. (4认同)

小智 121

从编码角度来看,这可能会更有意义(ant-contrib可用:http://ant-contrib.sourceforge.net/):

<target name="someTarget">
    <if>
        <available file="abc.txt"/>
        <then>
            ...
        </then>
        <else>
            ...
        </else>
    </if>
</target>
Run Code Online (Sandbox Code Playgroud)

  • 这只在我认为的ant-contrib中可用. (35认同)

Jon*_*ord 26

从Ant 1.8.0开始,显然也有资源存在

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

测试存在的资源.自从Ant 1.8.0开始

要测试的实际资源被指定为嵌套元素.

一个例子:

<resourceexists>
  <file file="${file}"/>
</resourceexists>
Run Code Online (Sandbox Code Playgroud)

我是关于这个问题的上述好回答的例子,然后我找到了这个

从Ant 1.8.0开始,您可以使用属性扩展; 值为true(或on或yes)将启用该项,而false(或off或no)将禁用该项.其他值仍假定为属性名称,因此仅在定义了命名属性时才启用该项.

与旧样式相比,这为您提供了额外的灵活性,因为您可以从命令行或父脚本覆盖条件:

<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"/>
Run Code Online (Sandbox Code Playgroud)

来自http://ant.apache.org/manual/properties.html#if+unless的ant手册

希望这个例子对某些人有用.他们没有使用资源存在,但大概你可以吗?.....

  • 请注意,`if ="$ {file.exists}"`应替换为`if ="file.exists"`as`if`和`unless`仅按名称检查属性的存在,而不是它的值. (2认同)

cmc*_*nty 12

我认为值得参考这个类似的答案: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>
Run Code Online (Sandbox Code Playgroud)