如何检查Ant是否在特定路径下执行?

时间:2018-02-20 23:06:57

标签: ant

如何使用Ant验证当前工作目录是否位于特定路径下(任意深度嵌套)?例如,我只想在当前目录是/some/dir/的一部分时执行目标,例如,如果在目录/some/dir/to/my/project/中执行了Ant。

我能想到的最好的是String包含条件:

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

这适用于我目前的目的,但我担心它可能会在将来中断一段时间...例如,在路径/not/some/dir/中执行构建时,它也包含指定的目录字符串。

是否有更强大的解决方案,例如startsWith比较,或者更好的基于文件系统的检查......?

1 个答案:

答案 0 :(得分:1)

本机Ant中没有特定的startswith条件,但有matches条件采用正则表达式。

作为旁注,大多数构建脚本很少需要ant-contrib,并且通常会导致代码不可靠。我强烈建议避免它。

这是一个示例脚本,用于说明如何将matches条件与本机Ant一起使用。当然,test目标仅用于演示。

<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>
相关问题