Antとは主にJavaなプロジェクトで使われているビルドツールです。使いこなせたらかなり便利なツールだということにやっと気づいたので、少しずつ勉強しはじめました。Antで何かを書く際の基本となる制御文を主にまとめました。
基本の形
projectタグの中にtargetタグを書いて、その中に実行したいタスクを書きます。projectタグのdefault属性には実行したいtargetの名前を記述します。targetはタスクをまとめた単位のようなものです。echoタグはタスクの一つで、System.out出力をします。
<?xml version="1.0" encoding="UTF-8"?> <project default="main"> <target name="main"> <echo> Hello World! </echo> </target> </project>
eclipse上の適当なプロジェクトの場所に配置し、右クリック→「run as」→「Ant build」で実行すると下記結果になりました。
Buildfile: /Users/xxx/workspace/HelloWorld/build.xml main: [echo] Hello World! [echo] BUILD SUCCESSFUL Total time: 830 milliseconds
実行順序を制御
targetタグのdepends属性に適切な依存関係を記述することで、タスクの実行順序を制御することができます。下記を実行するとfirst→second→thirdの順にコンソール出力されます。
<?xml version="1.0" encoding="UTF-8"?> <project default="target1"> <target name="target1" depends="target3, target2"> <echo> third </echo> </target> <target name="target2"> <echo> second </echo> </target> <target name="target3"> <echo> first </echo> </target> </project>
定数値を扱う
定数を扱いたいときはproperty要素が利用できます。property要素で設定したプロパティは${プロパティ名}で参照できます。下記を実行すると「Hello World!」がコンソール出力されます。
<?xml version="1.0" encoding="UTF-8"?> <project default="main"> <property name="text" value="Hello World!" /> <target name="main"> <echo> ${text} </echo> </target> </project>
条件文を扱う
if文みたいな条件文はcondition要素で実現できます。conditionタグにネストされた要素(and、not等)の評価結果がtrueであれば、checkプロパティにOKが設定されます。下記のコードは、「text1がhogeである、かつ、text2がhogeでない」場合に評価結果がtrueとなる式を表しています。
<?xml version="1.0" encoding="UTF-8"?> <project default="main"> <property name="text1" value="hoge" /> <property name="text2" value="piyo" /> <target name="main"> <condition property="check" value="OK"> <and> <equals arg1="hoge" arg2="${text1}" /> <not> <equals arg1="hoge" arg2="${text2}" /> </not> </and> </condition> <echo> ${check} </echo> </target> </project>
条件付きアクション
条件付きでアクションを実行させたいときは、if属性とunless属性が利用できます。ifはプロパティが設定されているとき、unlessはプロパティが設定されていないときにアクションを実行します。下記を実行すると、"hoge"と"text2 is not exist"が実行されました。
<?xml version="1.0" encoding="UTF-8"?> <project default="target2"> <property name="text1" value="hoge" /> <target name="target1" if="text1"> <echo> ${text1} </echo> </target> <target name="target2" unless="text2" depends="target1"> <echo> text2 is not exist </echo> </target> </project>
ビルドの停止
ビルドを途中で止めたいときはfail要素を記述します。ifやunless等の属性にビルド停止の条件を記述します。下記のAntファイルを実行すると、BUILD FAILEDとなりました。
<?xml version="1.0" encoding="UTF-8"?> <project default="main"> <property name="text" value="hoge" /> <target name="main"> <echo> first </echo> <condition property="check"> <equals arg1="piyo" arg2="${text}" /> </condition> <fail message="second" unless="check" /> <echo> third </echo> </target> </project>
実行結果
Buildfile: /Users/xxx/workspace/HelloWorld/build.xml main: [echo] first [echo] BUILD FAILED /Users/xxx/workspace/HelloWorld/build.xml:11: second Total time: 782 milliseconds