5

我的情况涉及运行带有可选参数的 ant 构建,这些可选参数总是指定但并不总是定义,就像这样

ant -DBUILD_ENVIRONMENT=test -Dusername_ext= -Dconf.dir_ext= -Dcgi-dir_ext=

如果参数没有在命令行上给定值,它们将通过加载 .properties 文件。我有以下代码将检查属性 isset 是否为空。

<if>
    <bool>
        <and>
            <isset property="username_ext"/>
            <not>
                <equals arg1="${username_ext}" arg2="" />
            </not>
        </and>
    </bool>
    <then>
        <property name="username" value="${username_ext}" />
    </then>
</if>
<property file="${BUILD_ENVIRONMENT}.properties" />

由于有多个属性,我似乎应该编写一个目标,该目标将对每个属性执行相同的操作,而不是每次都重复该代码。

<antcall target="checkexists">
    <property name="propname" value="username"/>
    <property name="paramname" value="username_ext"/>
</antcall>
<antcall target="checkexists">
    <property name="propname" value="conf.dir"/>
    <property name="paramname" value="conf.dir_ext"/>
</antcall>

但是 AFAIK an antcall 不会设置全局属性。那么我如何编写一个目标来接受它需要检查的参数名称已设置且不为空,然后将其复制到其他目标可以使用的参数中?

4

1 回答 1

9

除了使用目标之外,您还可以使用宏根据另一个属性是否设置为非空值来有条件地设置属性。

<macrodef name="set-property">
  <attribute name="name" />
  <attribute name="if-property-isset" />
  <attribute name="value" default="${@{if-property-isset}}" />

  <sequential>
    <condition property="@{name}" value="@{value}">
      <and>
        <isset property="@{if-property-isset}" />
        <not>
          <equals arg1="${@{if-property-isset}}" arg2="" />
        </not>
      </and>
    </condition>
  </sequential>
</macrodef>


<target name="test-macro">
  <set-property name="username" if-property-isset="username_ext" />

  <set-property name="conf.dir" if-property-isset="conf.dir_ext" />

  <property name="conf.dir" value="default conf directory" />

  <echo message="username = ${username}" />
  <echo message="conf.dir = ${conf.dir}" />
</target>

输出

$ ant test-macro -Dusername_ext=jsmith -Dconf.dir_ext=
Buildfile: /your/project/build.xml

test-macro:
     [echo] username = jsmith
     [echo] conf.dir = default conf directory

BUILD SUCCESSFUL
Total time: 1 second


备用属性值

此宏还允许您将属性设置为与命令行上提供的值不同的值。

<target name="test-macro">
  <set-property name="username" if-property-isset="username_ext"
      value="It worked!" />

  <set-property name="conf.dir" if-property-isset="conf.dir_ext" />

  <property name="conf.dir" value="default conf directory" />

  <echo message="username = ${username}" />
  <echo message="conf.dir = ${conf.dir}" />
</target>

输出

$ ant test-macro -Dusername_ext=jsmith -Dconf.dir_ext=
Buildfile: /your/project/build.xml

test-macro:
     [echo] username = It worked!
     [echo] conf.dir = default conf directory

BUILD SUCCESSFUL
Total time: 1 second
于 2012-08-20T20:21:34.563 回答