ITコンサルの日常

ITコンサル会社に勤務する普通のITエンジニアの日常です。

Antでファイルやディレクトリのありなしを判断して処理を分ける

これは標準タスクだけで出来ます。こんな感じ。

<?xml version = "1.0" ?>
<project name = "test" default = "main">
	<target name = "main">
		<available property = "file.exists" file = "C:\hoge.txt"/>
		<echo message = "${file.exists}"/>
	</target>
</project>

もしC:\hoge.txtが存在していれば、file.existsという変数の中にtrueがセットされ、存在していなければ何もセットされません。
このことを踏まえて、targetの属性であるifやunlessを組み合わせると、条件分岐が可能です。例えばこんな感じ。

<?xml version = "1.0" ?>
<project name = "test" default = "main">
	<target name = "main">
		<available property = "file.exists" file = "C:\hoge.txt"/>

		<antcall target = "execWhenFileExists"/>
		<antcall target = "execWhenFileNotExists"/>
	</target>

	<target name = "execWhenFileExists" if="file.exists">
		<echo message = "File exists."/>
	</target>

	<target name = "execWhenFileNotExists" unless="file.exists">
		<echo message = "File Not exists."/>
	</target>
</project>

コンパイルにおいても、終了ステータスとか拾うことが出来れば、条件分岐できるのですが。