2009-06-01 148 views
50

我希望我的构建脚本能够在发布和开发环境中正常运行。使用默认值定义来自环境的ant属性

为此,我想在蚂蚁来定义属性,称之为(例如)fileTargetName

fileTargetName会得到它从环境变量RELEASE_VER价值,如果它是可用的,如果它不存在,它会得到默认开发

帮助蚂蚁<condition><value></condition> & <property>的价值得到它的工作表示赞赏。

回答

71

从如何获得一个环境变量到属性的Ant documentation一个例子:

<property environment="env"/> 
<echo message="Number of Processors = ${env.NUMBER_OF_PROCESSORS}"/> 
<echo message="ANT_HOME is set to = ${env.ANT_HOME}"/> 

在你的情况,你可以使用${env.RELEASE_VER}

然后在条件部分,该文档here说,有三种可能的属性:

 
Attribute Description            Required 
property The name of the property to set.      Yes 
value  The value to set the property to. Defaults to "true". No 
else  The value to set the property to if the condition  No 
      evaluates to false. By default the property will 
      remain unset. Since Ant 1.6.3 

将其组合在一起:

<property environment="env"/> 
<condition property="fileTargetName" value="${env.RELEASE_VER}" else="dev"> 
    <isset property="env.RELEASE_VER" /> 
</condition> 
+2

昨天我不能回答这个问题,但是SO迫使我去研究。万岁的StackOverflow! – 2009-06-01 21:37:28

+1

谢谢! ant的一个奇怪行为:如果未设置环境参数,则在$ {env.ANT_HOME}上执行回显将显示“$ {env.ANT_HOME}”。默认的蚂蚁调用没有设置它(至少在这台机器上:RH WS 5,bash) – 2009-06-02 06:42:01

0

我敢肯定有比这更简单的方法,但如何:

<project name="example" default="show-props"> 

    <property environment="env" /> 

    <condition property="fileTargetName" value="${env.RELEASE_VER}"> 
     <isset property="env.RELEASE_VER" /> 
    </condition> 

    <condition property="fileTargetName" value="dev"> 
     <not> 
      <isset property="env.RELEASE_VER" /> 
     </not> 
    </condition> 

    <target name="show-props"> 
     <echo>property is ${fileTargetName}</echo> 
    </target> 

</project> 
+0

不知道有关条件的else属性 - @mmyers FTW – toolkit 2009-06-01 21:38:38

38

您不需要使用<condition>为此。在Ant属性是immutable,所以你可以使用这个:

<property environment="env"/> 
<property name="env.RELEASE_VER" value="dev"/> 

如果RELEASE_VER环境变量设置,则该属性会从环境中获取其值和第二<property>声明不会有任何效果。否则,该属性将在第一条语句后取消设置,第二条语句将其值设置为"dev"