2009-02-06 69 views
145

是否有ANT任務只在給定文件存在時纔會執行塊?我有問題,我有一個通用的螞蟻腳本,應該做一些特殊的處理,但只有當一個特定的配置文件存在。僅當文件存在時Ant任務才能運行Ant目標?

+0

參見[如何在Ant的可用命令中使用通配符](http://stackoverflow.com/questions/1073077/how-to-use-wildcard-in-ants-available-command/) – Vadzim 2013-10-07 08:03:02

回答

192

AvailableCondition

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

<target name="do-if-abc" depends="check-abc" if="abc.present"> 
    ... 
</target> 
+8

可用是一個非常明顯的名字,它的作用。谷歌顯示人們編寫自己的標籤 – 2009-02-06 19:42:29

+2

看起來不適用於Ant 1.6.2,這讓我更加困惑。 – djangofan 2011-04-16 00:56:07

+0

它對我很好(Ant 1.8.2)。謝謝。 – 2011-11-01 15:46:36

115

這可能使從編程角度來說,多了幾分感(可用螞蟻的contrib:http://ant-contrib.sourceforge.net/):

<target name="someTarget"> 
    <if> 
     <available file="abc.txt"/> 
     <then> 
      ... 
     </then> 
     <else> 
      ... 
     </else> 
    </if> 
</target> 
25

由於螞蟻1.8.0有顯然也資源存在

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

測試存在的資源。自 Ant 1.8.0

要測試的實際資源是指定爲嵌套元素的 。

一個例子:

<resourceexists> 
    <file file="${file}"/> 
</resourceexists> 

我正要從上面很好地回答了這個問題返工的例子,然後我發現這個

螞蟻1.8.0,你可改用 進行物業擴張;值爲真 (或開或是)將啓用項目, ,而虛假(或關或不)將 禁用它。其他值仍然是 假定爲屬性名稱,因此 只有在定義了名爲 的屬性時才啓用該項目。

相比老款的風格,這種 爲您提供了額外的靈活性, 因爲你可以通過命令行或家長忽略該情況 腳本:在http://ant.apache.org/manual/properties.html#if+unless

<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"/> 

從螞蟻手冊

希望這個例子對某些人有用。他們不使用resourceexists,但想必你會.....

10

我認爲它的價值引用此類似的答案: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> 
0

您可以通過訂購與文件等於你需要的姓名(或名稱)名稱的列表做手術做到這一點。比創建一個特殊的目標要容易和直接得多。而且你不需要任何額外的工具,只需要純粹的Ant。

<delete> 
     <fileset includes="name or names of file or files you need to delete"/> 
    </delete> 

http://ant.apache.org/manual/Types/fileset.html

2

檢查使用文件名過濾器,如 「DB _ */**/*。SQL」

這裏是如果一個或多個文件是否存在對應於通配符執行動作的變化過濾。也就是說,你不知道文件的確切名稱。

在這裏,我們正在尋找任何子目錄 「* .SQL」 文件名爲 「DB_ *」,遞歸。您可以根據需要調整過濾器。

注意:Apache Ant 1.7及更高版本!

下面是設置屬性的目標是否存在匹配的文件:

<target name="check_for_sql_files"> 
    <condition property="sql_to_deploy"> 
     <resourcecount when="greater" count="0"> 
      <fileset dir="." includes="DB_*/**/*.sql"/> 
     </resourcecount> 
    </condition> 
</target> 

這裏是「有條件」的目標,只有運行是否存在文件:

<target name="do_stuff" depends="check_for_sql_files" if="sql_to_deploy"> 
    <!-- Do stuff here --> 
</target>