Gradle Migration Part 1: Importing build.xml

Posted on 04. Jan, 2013 by in Gradle

Importing Ant Builds

As I mentioned in the introduction, the approach I’m taking is not a whole sale rewrite of the 2500+ line build process but an incremental rewrite of tasks as needed. One of the great features of Gradle is the ability to import existing ant builds and treat the ant targets just like gradle tasks.

This makes migration much more palatable.

Assuming your ant build file is called build.xml you simply need to add the following line to your build.gradle file

ant.importBuild 'build.xml'

Now we can call any ant tasks that are in build.xml but using gradle.

So instead of

ant build

We can call

gradle build

With that simple start we can now run all ant tasks through gradle.

Plugins and ant task conflicts

The next step I wanted to add to the gradle process was to apply the groovy plugin. Using the groovy plugin automatically configures the gradle project with a number of tasks that are useful for building mixed Groovy and Java projects. The link goes into great detail but things like compiling, running tests, building jars etc come for free with the groovy plugin. In the future I will be taking advantage of some of these tasks as I move the build logic from ant into the gradle build.

I did run into one small gotcha when I applied this plugin.

e:\proj\e1>gradle clean-build
[ant:taskdef] Could not load definitions from resource taskdef.properties. It could not be found.
 
FAILURE: Build failed with an exception.
 
* Where:
Build file 'E:\proj\e1\build.gradle' line: 4
 
* What went wrong:
A problem occurred evaluating root project 'e1'.
> Cannot add task ':clean' as a task with that name already exists.
 
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
 
BUILD FAILED
 
Total time: 2.511 secs

As I mentioned above, the groovy plugin injects some useful tasks. In my case, I have a number of targets in my ant build file that have the same name and therefore conflict with the tasks injected by the groovy plugin.

Fixing this is fairly straight forward. I swept my build.xml file and added ant. prefixes to any target that conflicted with the groovy plugin tasks.

In my case, these targets

init
clean
build
test

became

ant.init
ant.clean
ant.build
ant.test

With these modifications in place I’m now able to run all my ant tasks directly through gradle. Which is fantastic!

Leave a Reply