Skip to content

Instantly share code, notes, and snippets.

@winash
Last active December 14, 2015 11:39
Show Gist options
  • Save winash/5080671 to your computer and use it in GitHub Desktop.
Save winash/5080671 to your computer and use it in GitHub Desktop.
Gradle task for intellij Idea
//Create a simple java project to generate the iml file first
task idea << {
// change this to the name of your module file
def moduleFileName = "<your project name>.iml"
def root = new XmlParser().parse(moduleFileName)
def newModuleRootManager = root.component.find {it.'@name' == 'NewModuleRootManager'}
// if there is already a module library in place we should remove it
remove(newModuleRootManager)
// add the new module library with our current gradle dependencies
addEntry(newModuleRootManager)
// output the .iml XML
def writer = new StringWriter()
new XmlNodePrinter(new PrintWriter(writer)).print(root)
def result = writer.toString()
print result
// overwrite our old .iml file
def moduleFile = new File(moduleFileName)
moduleFile.text = result
}
private def addEntry(newModuleRootManager) {
def newEntry = newModuleRootManager.appendNode('orderEntry', [type: project.orderEntryType])
def newLibrary = newEntry.appendNode('library', [name: project.gradleLibraryId])
def classesNode = newLibrary.appendNode('CLASSES')
def path = configurations.compile.asPath
def jars = path.split(System.getProperty("path.separator"))
jars = Arrays.asList(jars)
jars.each { jar ->
classesNode.appendNode('root', [url: "jar://$jar!/"])
}
}
private def remove(newModuleRootManager) {
def oldEntry = newModuleRootManager.orderEntry.find {
(it.'@type' == project.orderEntryType) && (it.library[0].'@name' == project.gradleLibraryId)
}
if (oldEntry) {
newModuleRootManager.remove(oldEntry)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment