onsdag 23. november 2011

Show gradle dependencies as graphwiz png

A few weeks ago I needed to show my team an overview of all the dependencies between our sub projects. I found a solution where I generated a graphwiz dot file. The caveat here was that I had to install graphwiz and run another command to generate a png.

Today I was reading through "Making Java Groovy", MEAP authored by Ken Kousen. I saw an example using the googles charting api. A quick check revealed they had experimental support for creating a png from a dot graph !

So my gradle task ended up looking as follows:

reportsDir = new File("build/reports")
compileDepsPng = file("$reportsDir/compileDeps.png")

task dependenciesPng() {
  inputs.files subprojects.configurations.compile
  outputs.files compileDepsPng
  doFirst {
    if(compileDepsPng.exists()) compileDepsPng.delete()
    if(!reportsDir.exists()) reportsDir.mkdirs()
  
  }
  doLast {
    dotGraph = "digraph Compile{"
    subprojects.each {subproject ->
      subproject.configurations.compile.dependencies.each {dependency ->
      if(dependency instanceof ProjectDependency) {
 dotGraph += "\"$subproject.name\" -> \"$dependency.name\"" 
      }   }
    }
    dotGraph += "}"
  
    def chartParams = [cht: 'gv', chof: 'png', chl: dotGraph]
    def url = "http://chart.googleapis.com/chart?" 
    url += chartParams.collect {k,v -> "$k=${URLEncoder.encode(v)}"}.join('&')
  
    compileDepsPng.withOutputStream{out ->
      out << new URL(url).openStream()
    }   
  }
}