2009-06-01 140 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"