Is参数不为null

  • 本文关键字:null 参数 Is ant
  • 更新时间 :
  • 英文 :


我正在尝试检查ant构建脚本的参数是否已设置。我尝试了很多方法来做到这一点,但都没有成功。我用-Dmaindir="../propertyfolderpath"定义了这个论点。

这是我尝试过的代码示例;

<ac:if>
    <equals arg1="@{maindir}" arg2="" />
    <ac:then>
        <echo message="maindir argument is empty. Current properties will be used." />
        <property file="build.properties" />
    </ac:then>
    <ac:else>
        <echo message="maindir = ${maindir}" />
        <ac:if>
            <ac:available file="${maindir}/build.properties" type="file" />
            <ac:then>
                <property file="${maindir}/build.properties" />
            </ac:then>
            <ac:else>
                <fail message="${maindir} is not a valid path." />
            </ac:else>
        </ac:if>
    </ac:else>  
</ac:if>
  • 有三种情况;
    1. 可能未定义参数。蚂蚁应该先进去
    2. 参数定义良好
    3. 参数定义的路径错误

对于第二种情况,脚本正在运行。对于第三种情况,脚本正在工作。但对于第一种情况,我的意思是,当我不定义主要论点时,蚂蚁的行为就像第三种情况。这是我的问题。

蚂蚁为什么那样做?

也许您可以尝试为参数设置默认值?

<condition property="maindir" value="[default]">
    <not>  
        <isset property="maindir"/>
    </not>
</condition>
<echo message="${maindir}" />

我试过了,当没有传递参数时,${maindir}的值就是[default]

看起来有两个问题:

  1. 在第一个if的等于条件中,您有@{maindir}。除非它是宏的参数,否则它应该是${maindir},与示例的其余部分相同
  2. 如果尚未设置属性,则不会对其进行任何求值。因此,如果未定义maindir,则${maindir}将计算为${maindir},而不是空字符串

解决此问题的最简单方法是将@符号更改为$符号,并在开头添加一条语句以将属性默认为值:

<property name="maindir" value="." />

这将默认属性为当前目录,因此您可以完全消除外部if,因为不再需要它。ant中的属性是只读的,因此如果用户明确指定了一个值(例如,从命令行),则会使用该值,而上面的行不会有任何效果——只有当用户没有为maindir指定值时,它才会有效果。

事实上,我认为你可以通过做以下事情来完全摆脱蚂蚁悔过:

<property name="maindir" value="." />
<fail message="${maindir}/build.properties is not a valid path.">
    <condition>
        <not>
            <available file="${maindir}/build.properties" />
        </not>
    </condition>
</fail>
<property file="${maindir}/build.properties" />

这应该与你希望通过你的例子实现的效果完全相同。

最新更新