检查多个属性是否设置而不是空白(蚂蚁)

Cra*_*aig 5 ant ant-contrib

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

ant -DBUILD_ENVIRONMENT=test -Dusername_ext= -Dconf.dir_ext= -Dcgi-dir_ext=
Run Code Online (Sandbox Code Playgroud)

如果参数在命令行中没有给定值,则它们将通过加载.properties文件.我有以下代码,将检查属性是否设置并且不是空白.

<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" />
Run Code Online (Sandbox Code Playgroud)

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

<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>
Run Code Online (Sandbox Code Playgroud)

但AFAIK的反击不会设置全球财产.那么如何编写一个目标来接受它需要检查的参数的名称并且不是空白,然后将其复制到其他目标可以使用的参数中?

Chr*_*ert 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>
Run Code Online (Sandbox Code Playgroud)

产量

$ 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
Run Code Online (Sandbox Code Playgroud)


替代财产价值

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

<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>
Run Code Online (Sandbox Code Playgroud)

产量

$ 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
Run Code Online (Sandbox Code Playgroud)