2013-07-31

How to use Gradle to generate Eclipse files with relative paths to libraries

First, apply the Gradle Eclipse plug-in to your build.gradle file:

apply plugin: 'java'
apply plugin: 'eclipse'

You can now execute the following command to generate the Eclipse configuration files .project and .classpath:

$ gradle eclipse

You can now import and existing project into Eclipse, and enjoy all the correct configurations!

However, in the current Gradle version (1.6), the generated library paths are absolute, for example:

C:/Users/Miguel/.gradle/caches/artifacts-24/filestore/
junit/junit/4.11/source/
28e0ad201304e4a4abf999ca0570b7cffc352c3c/junit-4.11-sources.jar

This leads to problems because if you commit these files in source code control, your specific user settings will be imposed on other developers.

One way to avoid this is to use an Eclipse Classpath Variable and customize the Eclipse plug-in output.

eclipse {
    // find gradle cache location
    def gradleCache = null
    for (o in configurations.compile) {
        if (o.toString().indexOf(".gradle") != -1) {
            final def token = "filestore"
            def s = o.toString()
            def idx = s.indexOf(token)
            if (idx != -1) {
                gradleCache = new File(s.substring(0, idx + token.length()))
                break
            }
        }
    }
    assert gradleCache && gradleCache.exists()
    println "GRADLE_CACHE: " + gradleCache

    // replace absolute paths with classpath variable GRADLE_CACHE
    pathVariables 'GRADLE_CACHE': gradleCache

    // make sure GRADLE_CACHE is defined in 
    // Eclipse, Preferences, Java, Build Path, Classpath Variables

}

Note: an alternative solution could use Eclipse workspace Path variables (referred using the ${...} notation) but without DSL support like the pathVariables statement above.

No comments: