dokaspar
dokaspar

Reputation: 8624

How to check if Ant is executed under certain path?

How can I use Ant to verify that the current working directory is located (arbitrarily deeply nested) under a certain path? For example, I want to execute a target only if the current directory is part of /some/dir/, for example if Ant is executed in directory /some/dir/to/my/project/.

The best I could come up with is a String contains condition:

<if>
    <contains string="${basedir}" substring="/some/dir/"/>
    <then>
        <echo>Execute!</echo>
    </then>
    <else>
        <echo>Skip.</echo>
    </else>
</if>

This works for my current purpose but I'm afraid it might break some time in the future... for example when a build is executed in path /not/some/dir/ which is also contains the specified directory string.

Are there any more robust solutions like a startsWith comparison or even better a file system based check...?

Upvotes: 0

Views: 103

Answers (1)

CAustin
CAustin

Reputation: 4614

There is no specific startswith condition in native Ant, but there is a matches condition that takes regular expressions.

As a side note, ant-contrib is rarely necessary for most build scripts, and will often lead to unreliable code. I would strongly recommend avoiding it.

Here's a sample script to illustrate how you can use the matches condition with native Ant. The test target is, of course, just for demonstration.

<property name="pattern" value="^/some/dir" />

<target name="init">
    <condition property="basedir.starts.with">
        <matches pattern="${pattern}" string="${basedir}" />
    </condition>
</target>

<target name="execute" depends="init" if="basedir.starts.with">
    <echo message="Executing" />
</target>

<target name="test">
    <condition property="dir1.starts.with">
        <matches pattern="${pattern}" string="/some/dir/" />
    </condition>

    <condition property="dir2.starts.with">
        <matches pattern="${pattern}" string="/some/dir/to/my/project/" />
    </condition>

    <condition property="dir3.starts.with">
        <matches pattern="${pattern}" string="/not/some/dir/" />
    </condition>

    <echo message="${dir1.starts.with}" />
    <echo message="${dir2.starts.with}" />
    <echo message="${dir3.starts.with}" />
</target>

Upvotes: 1

Related Questions