在Ant中,如何动态构建引用属性文件的属性



我正在使用Input任务来收集特定的属性值,并希望将这些值连接到引用我的属性文件的一个属性值中。

我可以生成属性的格式,但在运行时,它被视为字符串,而不是属性引用。

属性文件示例:

# build.properties
# Some Server Credentials
west.1.server = TaPwxOsa
west.2.server = DQmCIizF
east.1.server = ZCTgqq9A

示例构建文件:

<property file="build.properties"/>
<target name="login">
 <input message="Enter Location:" addproperty="loc" />      
 <input message="Enter Sandbox:" addproperty="box" />
 <property name="token" value="${${loc}.${box}.server}" />
 <echo message="${token}"/>
</target>

当我调用login并为输入值提供"west"one_answers"1"时,echo将打印${west.1.server},但它不会从属性文件中检索属性值。

如果我硬编码消息中的属性值:

<echo message="${west.1.server}"/>

那么Ant将尽职尽责地从属性文件中检索字符串。

如何让Ant接受动态生成的属性值,并将其视为要从属性文件中检索的属性?

props-antlib对此提供了支持,但据我所知,目前还没有可用的二进制版本,因此您必须从源代码构建它。

另一种方法是使用macrodef:

<macrodef name="setToken">
  <attribute name="loc"/>
  <attribute name="box"/>
  <sequential>
    <property name="token" value="${@{loc}.@{box}.server}" />
  </sequential>
</macrodef>
<setToken loc="${loc}" box="${box}"/>

使用Props antlib的其他示例
需要Ant>=1.8.0(适用于最新的Ant版本1.9.4)和Props-antlib二进制文件。

官方Props antlib GIT存储库(或此处)中的当前build.xml无法开箱即用:

BUILD FAILED
Target "compile" does not exist in the project "props".

获取props-antlib的来源,并在文件系统中解压缩
获取ant库的公共源,并将内容解压缩到/蚂蚁蚂蚁道具大师/普通道具
运行ant antlib构建jar:

[jar] Building jar: c:area51ant-antlibs-props-masterbuildlibant-props-1.0Alpha.jar

否则,从MVNRepository或此处获取二进制文件

..中的示例/antunit非常有用。有关嵌套属性,请查看nested-test.xml
将ant-props.jar放在ant类路径上

<project xmlns:props="antlib:org.apache.ant.props">
 <!-- Activate Props antlib -->
 <propertyhelper>
   <props:nested/>
 </propertyhelper>
 <property file="build.properties"/>
 <input message="Enter Location:" addproperty="loc" />      
 <input message="Enter Sandbox:" addproperty="box" />
 <property name="token" value="${${loc}.${box}.server}"/>
 <echo message="${token}"/>
</project>

输出:

Buildfile: c:area51anttryme.xml
    [input] Enter Location:
west
    [input] Enter Sandbox:
1
     [echo] TaPwxOsa
BUILD SUCCESSFUL
Total time: 4 seconds

解决方案是:考虑一下问题是这个,你们想在哪里实现这个:

<property name="prop" value="${${anotherprop}}"/> (double expanding the property)?

您可以使用javascript:

<script language="javascript">
    propname = project.getProperty("anotherprop");
    project.setNewProperty("prop", propname);
</script>

我试了一下,这对我很有效。

最新更新