是否可以替换Ant build.xml中的属性中的文本?

时间:2009-12-30 07:17:31

标签: java ant

我有一个属性app.version,设置为1.2.0(当然,总是在变化),需要创建名为“something-ver-1_2_0”的zip文件。这可能吗?

5 个答案:

答案 0 :(得分:7)

您可以使用pathconvert任务替换“。”使用“_”并分配给新属性:

<?xml version="1.0" encoding="UTF-8"?>
<project>
    <property name="app.version" value="1.2.0"/>

    <pathconvert property="app.version.underscore" dirsep="" pathsep="" description="Replace '.' with '_' and assign value to new property">
        <path path="${app.version}" description="Original app version with dot notation" />

        <!--Pathconvert will try to add the root directory to the "path", so replace with empty string -->
        <map from="${basedir}" to="" />

        <filtermapper>
            <replacestring from="." to="_"/>     
        </filtermapper>

    </pathconvert>

    <echo>${app.version} converted to ${app.version.underscore}</echo>
</project>

答案 1 :(得分:2)

另一种方法是filter使用正则表达式从文件到属性的版本号,如本示例所示:

<loadfile srcfile="${main.path}/Main.java" property="version">
    <filterchain>
        <linecontainsregexp>
            <regexp pattern='^.*String VERSION = ".*";.*$'/>
        </linecontainsregexp>
        <tokenfilter>
            <replaceregex pattern='^.*String VERSION = "(.*)";.*$' replace='\1'/>
        </tokenfilter>
        <striplinebreaks/>
    </filterchain>
</loadfile>

答案 2 :(得分:0)

可以使用zip任务

<zip zipfile="something-ver-${app.version}.zip">
<fileset basedir="${bin.dir}" prefix="bin">
    <include name="**/*" />
</fileset>
<fileset basedir="${doc.dir}" prefix="doc">
    <include name="**/*" />
</fileset></zip>

有关zip任务的更多信息:http://ant.apache.org/manual/Tasks/zip.html

答案 3 :(得分:0)

由于属性app.version总是在变化,我假设您不想将其硬编码到属性文件中,而是在进行构建时传递它。继answer之后,您可以在命令行上尝试以下操作;

ant -f build.xml -Dapp.version=1.2.0

app.version更改为当时所需的那个。

修改

从反馈中更好地理解你的问题。 Unfortunately ant没有字符串操作任务,您需要为此编写自己的task。这是一个关闭example

答案 4 :(得分:0)

属性无法更改,但antContrib vars(http://ant-contrib.sourceforge.net/tasks/tasks/variable_task.html)可以更改。

这里是一个宏,可以在var上查找/替换所有内容:

    <macrodef name="replaceVarText">
        <attribute name="varName" />
        <attribute name="from" />
        <attribute name="to" />
        <sequential>
            <local name="replacedText"/>
            <local name="textToReplace"/>
            <local name="fromProp"/>
            <local name="toProp"/>
            <property name="textToReplace" value = "${@{varName}}"/>
            <property name="fromProp" value = "@{from}"/>
            <property name="toProp" value = "@{to}"/>

            <script language="javascript">
                project.setProperty("replacedText",project.getProperty("textToReplace").split(project.getProperty("fromProp")).join(project.getProperty("toProp")));
            </script>
            <ac:var name="@{varName}" value = "${replacedText}"/>
        </sequential>
    </macrodef>

然后像这样调用宏:

<ac:var name="newFileName" value="${app.version}"/>
<current:replaceVarText varName="newFileName" from="." to="_" />
<echo>Filename will be ${newFileName}