2009-01-17 16 views
36

我想通過os類型以不同的方式在ant任務中設置屬性。使用ant來檢測os並設置屬性

該屬性是一個目錄,在Windows中,我希望它是「c:\ flag」在unix/linux「/ opt/flag」中。

我當前的腳本只適用於當我用默認目標運行它,但爲什麼?

<target name="checksw_path" depends="if_windows, if_unix"/> 

<target name="checkos"> 
    <condition property="isWindows"> 
     <os family="windows" /> 
    </condition> 

    <condition property="isLinux"> 
     <os family="unix" /> 
    </condition> 
</target> 

<target name="if_windows" depends="checkos" if="isWindows"> 
    <property name="sw.root" value="c:\flag" /> 
    <echo message="${sw.root}"/> 
</target> 

<target name="if_unix" depends="checkos" if="isLinux"> 
    <property name="sw.root" value="/opt/flag" /> 
    <echo message="${sw.root}"/> 
</target> 

在我已經添加了我所有的Ant目標 「取決於= checksw_path」。

如果我在Windows中運行默認目標,我已經正確地「c:\ flag」但如果我運行一個非默認目標,我已經調試進入if_windows,但指令「」沒有設置該屬性仍然是/ opt/flag。我正在使用ant 1.7.1。

回答

-3

我解決與用於使用-Dsw.root = C sw.root值執行ant任務:\標誌(對於Windows)或-Dsw.root = /選擇/ superwaba(對於Linux)。

反正感謝

20

將您的條件移出<target />,因爲您的目標可能未被調用。

<condition property="isWindows"> 
        <os family="windows" /> 
</condition> 

<condition property="isLinux"> 
        <os family="unix" /> 
</condition> 
1

試着在你的java任務設置<sysproperty key="foobar" value="fowl"/>。 然後,在你的應用程序中,使用System.getProperty(「foobar」);

12

您需要將值設置爲「true」以使if條件起作用。請參見下面的代碼:

<target name="checkos"> 
    <condition property="isWindows" value="true"> 
      <os family="windows" /> 
    </condition> 

    <condition property="isLinux" value="true"> 
      <os family="unix" /> 
    </condition> 
</target> 

HTH, 哈日

2

我用這樣的劇本,工作很適合我:

<project name="dir" basedir="."> 

    <condition property="isWindows"> 
    <os family="windows" /> 
    </condition> 

    <condition property="isUnix"> 
    <os family="unix" /> 
    </condition> 

    <target name="setWindowsRoot" if="isWindows"> 
    <property name="root.dir" value="c:\tmp\" /> 
    </target> 

    <target name="setUnixRoot" if="isUnix"> 
    <property name="root.dir" value="/i0/" /> 
    </target> 

    <target name="test" depends="setWindowsRoot, setUnixRoot"> 
    <mkdir dir="${root.dir}" /> 
    </target> 

</project> 
2

如果想設置基於OS是單一的財產,你可以設置它直接和,而不需要創建任務:

<condition property="sw.root" value="c:\flag"> 
    <os family="windows" /> 
</condition> 

<condition property="sw.root" value="/opt/flag"> 
     <os family="unix" /> 
</condition> 

<property name="sw.root" value="/os/unknown/"/> 
0

通過使用Ant Contrib你可以通過減少的Elemen量簡化您的構建文件您需要聲明以添加這些條件。

<!--Tell Ant to define the Ant Contrib tasks from the jar--> 
<taskdef resource="net/sf/antcontrib/antcontrib.properties"> 
    <classpath> 
     <pathelement location="path/to/ant-contrib-0.6.jar"/> 
    </classpath> 
</taskdef> 

<!--Do your OS specific stuff--> 
<target name="checkos"> 
    <if> 
     <os family="unix"/> 
     <then> 
      <!--Do your Unix stuff--> 
     </then> 
     <elseif> 
      <os family="windows"/> 
      <then> 
       <!--Do your Windows stuff--> 
      </then> 
     </elseif> 
    </if> 
</target>