Felipe Cypriano

You're about to read

Synchronizing IntelliJ IDEA Dependencies With Gradle [Updated]

Based on the great post Managing IntelliJ dependencies with Gradle from Kallin Nagelberg, I’ve came to a solution about how to manage Intellij IDEA dependencies on projects that uses .idea directory as its structure.

Basically instead of changing your_project.iml file we create a xml file in .idea/libraries with the jars listed on it. For more details, please, read Kallin’s post. This is the task:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// IntelliJ IDEA configuration sync
task intellijSync << {
    final def librariesDir = new File(".idea${File.separator}libraries")
    librariesDir.mkdirs()

    final def gradleLibsPath = configurations.compile.asPath
    final def userHomeGradle = project.gradle.gradleUserHomeDir
    final def libsJar = gradleLibsPath.split(File.pathSeparator).collect {
        it.replaceAll userHomeGradle.path, "\\\$USER_HOME_GRADLE\\\$"
    }
    println libsJar

    final def gradleLibXml = new File(librariesDir, 'Gradle_Libraries.xml')
    gradleLibXml.write """
<component name="libraryTable">
  <library name="Gradle Libraries"/>
</component>
"""
    final def xmlRoot = new XmlParser().parse(gradleLibXml)
    final def classesNode = xmlRoot.library[0].appendNode('CLASSES')

    libsJar.each { jar ->
        classesNode.appendNode('root', [url: "jar://$jar!/"])
    }

    def writer = new StringWriter()
    new XmlNodePrinter(new PrintWriter(writer)).print(xmlRoot)
    println writer.toString()
    gradleLibXml.write writer.toString()
}

The complete build.gradle file is on Gist.

# Update 1

Check the file on Gist, I’ve updated it to sync test libraries as well.