Ant - 字符串包含在字符串数组中

Thi*_*ago 2 ant

我基本上试图在 Ant (v1.9.4) 中执行以下操作:

我有一个固定字符串列表,如 {a,b,c,d} --> 首先我应该如何在 Ant 中声明它?然后我有一个输入参数,例如 ${mystring},我想检查变量值是否在我的列表中。这意味着在此示例中,如果变量值等于 a 或 b 或 c 或 d。如果是,则返回 true,否则返回 false(或 0 和 1 之类的东西)。

有没有一种简单的方法可以做到这一点?

谢谢,

蒂亚戈

Reb*_*bse 5

使用 ant属性任务来声明您的字符串列表。
使用 ant contains 条件检查列表是否包含特定项目。
就像是 :

<project>

 <!-- your stringlist -->
 <property name="csvprop" value="foo,bar,foobar"/>

 <!-- fail if 'foobaz' is missing --> 
 <fail message="foobaz not in List => [${csvprop}]">
  <condition>
   <not>
    <contains string="${csvprop}" substring="foobaz"/>
   </not>
  </condition>
 </fail>

</project>
Run Code Online (Sandbox Code Playgroud)

或者将其包装在宏定义中以供重用:

<project>

 <!-- your stringlist -->
 <property name="csvprop" value="foo,bar,foobar"/>

 <!-- create macrodef -->
 <macrodef name="listcontains">
  <attribute name="list"/>
  <attribute name="item"/>
  <sequential>
  <fail message="@{item} not in List => [@{list}]">
   <condition>
    <not>
     <contains string="${csvprop}" substring="foobaz"/>
    </not>
   </condition>
  </fail>   
  </sequential>
 </macrodef>

 <!-- use macrodef -->       
 <listcontains item="foobaz" list="${csvprop}"/>

</project>
Run Code Online (Sandbox Code Playgroud)

- 编辑 -
来自蚂蚁手册条件

If the condition holds true, the property value is set to true by default; otherwise, the property is not set. You can set the value to something other than the default by specifying the value attribute.
Run Code Online (Sandbox Code Playgroud)

因此,只需使用一个条件来创建一个为 true 或未设置的属性,fe 结合Ant 1.9.1 引入的新 if/unless 功能

<project 
  xmlns:if="ant:if"
  xmlns:unless="ant:unless"
>

 <!-- your stringlist -->
 <property name="csvprop" value="foo,bar,foobar"/>

 <!-- create macrodef -->
 <macrodef name="listcontains">
  <attribute name="list"/>
  <attribute name="item"/>
  <sequential>
   <condition property="itemfound">
     <contains string="${csvprop}" substring="foobaz"/>
   </condition>
   <!-- echo as example only instead of 
        your real stuff -->  
   <echo if:true="${itemfound}">Item @{item} found => OK !!</echo>  
   <echo unless:true="${itemfound}">Warning => Item @{item} not found !!</echo>
  </sequential>
 </macrodef>

 <!-- use macrodef -->       
 <listcontains item="foobaz" list="${csvprop}"/>

</project>
Run Code Online (Sandbox Code Playgroud)

输出 :

[echo] Warning => Item foobaz not found !!
Run Code Online (Sandbox Code Playgroud)

请注意,您需要命名空间声明来激活 if/unless 功能。