0

When calling a task using <ant antfile="...">, how do you get a property from within the <ant ...> call? I ask because a Maven plugin -- the maven-antrun-plugin -- uses this notation and states that using external files with this notation is recommended.

To see the code in a Maven project, click here: Retrieve value from external ant file for use in Maven project, or in an upstream bug report here.

Here's the ant code:

<project default="run-test">

    <target name="run-test">
        <!-- Call using antfile notation -->
        <ant antfile="build.xml" target="antfile-task"/>
        <echo level="info">Outside antfile: my.val: ${my.val}</echo>
    </target>

    <target name="antfile-task">
        <property name="my.val" value="just some test value"/>
        <echo level="info">Inside antfile:  my.val: ${my.val}</echo>
    </target>

</project>

Output:

Buildfile: build.xml

run-test:

antfile-task:
     [echo] Inside antfile:  my.val: just some test value
     [echo] Outside antfile: my.val: ${my.val}

tresf
  • 7,103
  • 6
  • 40
  • 101

1 Answers1

0

A workaround to this limitation is to write-and-read a properties file with the properties requiring export using:

<propertyfile file="my.properties">
   <entry key="my.val" value="${my.val}"/>
</propertyfile>

... and then read it back in using:

<property file="my.properties"/>

This has the disadvantage of an extra step, but does provide a bit of property encapsulation so that only the properties needed are exposed to the parent target.

Working example:

<project default="run-test">

    <target name="run-test">
        <!-- Call using antfile notation -->
        <ant antfile="build.xml" target="antfile-task"/>
        <!-- This will always be empty -->
        <echo level="info">Outside antfile:  my.val: ${my.val}</echo>

        <!-- Read the props file -->
        <property file="my.properties" description="read props from ant"/>
        <!-- Now we have the correct value -->
        <echo level="info">Props workaround: my.val: ${my.val}</echo>
    </target>

    <target name="antfile-task">
        <property name="my.val" value="just some test value"/>
        <echo level="info">Inside antfile:   my.val: ${my.val}</echo>

        <!-- Properties for export to maven -->
        <propertyfile file="my.properties">
            <entry key="my.val" value="${my.val}"/>
        </propertyfile>
    </target>

</project>
tresf
  • 7,103
  • 6
  • 40
  • 101