Over a million developers have joined DZone.

Gradle Goodness: Rename Ant Task Names When Importing Ant Build File

· Java Zone

Navigate the Maze of the End-User Experience and pick up this APM Essential guide, brought to you in partnership with CA Technologies

Migrating from Ant to Gradle is very easy with the importBuild method from AntBuilder. We only have to add this single line and reference our existing Ant build XML file and all Ant tasks can now be executed as Gradle tasks. We can automatically rename the Ant tasks if we want to avoid task name collisions with Gradle task names. We use a closure argument with the importBuild method and return the new task names. The existing Ant task name is the first argument of the closure.

Let's first create a simple Ant build.xml file:

<project>

    <target name="showMessage"
        description="Show simple message">

        <echo message="Running Ant task 'showMessage'"/>

    </target>

    <target name="showAnotherMessage"
        depends="showMessage"
        description="Show another simple message">

        <echo message="Running Ant task 'showAnotherMessage'"/>

    </target>

</project>

The build file contains two targets: showMessage andshowAnotherMessage with a task dependency. We have the next example Gradle build file to use these Ant tasks and prefix the original Ant task names withant-:

// Import Ant build and 
// prefix all task names with
// 'ant-'.
ant.importBuild('build.xml') { antTaskName ->
    "ant-${antTaskName}".toString()
}

// Set group property for all 
// Ant tasks.
tasks.matching { task ->
    task.name.startsWith('ant-')
}*.group = 'Ant'

We can run the tasks task to see if the Ant tasks are imported and renamed:

$ gradle tasks --all
...
Ant tasks
---------
ant-showAnotherMessage - Show another simple message 
ant-showMessage - Show simple message
...
$

We can execute the ant-showAnotherMessage task and we get the following output:

$ gradle ant-showAnotherMessage
:ant-showMessage
[ant:echo] Running Ant task 'showMessage'
:ant-showAnotherMessage
[ant:echo] Running Ant task 'showAnotherMessage'

BUILD SUCCESSFUL

Total time: 3.953 secs
$

Written with Gradle 2.2.1

Thrive in the application economy with an APM model that is strategic. Be E.P.I.C. with CA APM.  Brought to you in partnership with CA Technologies.

Topics:

Published at DZone with permission of Hubert Klein Ikkink, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}