【发布时间】:2010-10-31 00:43:35
【问题描述】:
有没有办法从 Ant 属性中提取子字符串并将该子字符串放入它自己的属性中?
【问题讨论】:
-
您能更具体地说明您要做什么吗?为什么定义一个属性来保存您所依赖的值并在多个地方使用它不是更有意义?如果您的 Ant 属性变化频繁,以至于您需要以编程方式对它们做出反应,那么您可能做错了什么。
标签: ant
有没有办法从 Ant 属性中提取子字符串并将该子字符串放入它自己的属性中?
【问题讨论】:
标签: ant
我使用 scriptdef 创建一个 javascript 标记来子字符串,例如:
<project>
<scriptdef name="substring" language="javascript">
<attribute name="text" />
<attribute name="start" />
<attribute name="end" />
<attribute name="property" />
<![CDATA[
var text = attributes.get("text");
var start = attributes.get("start");
var end = attributes.get("end") || text.length();
project.setProperty(attributes.get("property"), text.substring(start, end));
]]>
</scriptdef>
........
<target ...>
<substring text="asdfasdfasdf" start="2" end="10" property="subtext" />
<echo message="subtext = ${subtext}" />
</target>
</project>
【讨论】:
您可以尝试使用PropertyRegex from Ant-Contrib。
<propertyregex property="destinationProperty"
input="${sourceProperty}"
regexp="regexToMatchSubstring"
select="\1"
casesensitive="false" />
【讨论】:
override="true" 覆盖任何先前的值。
因为我更喜欢使用 vanilla Ant,所以我使用了一个临时文件。在任何地方都可以使用,您可以利用 replaceregex 摆脱您不想要的字符串部分。处理 Git 消息的示例:
<exec executable="git" output="${git.describe.file}" errorproperty="git.error" failonerror="true">
<arg value="describe"/>
<arg value="--tags" />
<arg value="--abbrev=0" />
</exec>
<loadfile srcfile="${git.describe.file}" property="git.workspace.specification.version">
<filterchain>
<headfilter lines="1" skip="0"/>
<tokenfilter>
<replaceregex pattern="\.[0-9]+$" replace="" flags="gi"/>
</tokenfilter>
<striplinebreaks/>
</filterchain>
</loadfile>
【讨论】:
<echo file="version.txt" message="${version}"/> 而不是 exec 并且工作得很好
我想一个简单的普通方法是:
<loadresource property="destinationProperty">
<concat>${sourceProperty}</concat>
<filterchain>
<replaceregex pattern="regexToMatchSubstring" replace="\1" />
</filterchain>
</loadresource>
【讨论】:
我会使用蛮力并编写自定义 Ant 任务:
public class SubstringTask extends Task {
public void execute() throws BuildException {
String input = getProject().getProperty("oldproperty");
String output = process(input);
getProject().setProperty("newproperty", output);
}
}
还剩下什么来实现String process(String) 并添加几个设置器(例如,用于oldproperty 和newproperty 值)
【讨论】:
我会为此目的使用脚本任务,我更喜欢 ruby,例如 切断前 3 个字符 =
<project>
<property name="mystring" value="foobarfoobaz"/>
<target name="main">
<script language="ruby">
$project.setProperty 'mystring', $mystring[3..-1]
</script>
<echo>$${mystring} == ${mystring}</echo>
</target>
</project>
输出 =
main:
[echo] ${mystring} == barfoobaz
在现有的项目上使用带有方法 project.setProperty() 的 ant api 属性将覆盖它,这样你就可以解决标准蚂蚁 行为,意味着属性一旦设置是不可变的
【讨论】: