CodeNarc and Gradle

Posted by & filed under , .

OLYMPUS DIGITAL CAMERAI have started using recently Gradle, which I have to confess I actually find to be a bliss compared to Maven. Maybe because I prefer a Groovy-based syntax for build configuration, rather than Maven’s XML-based configuration file. Or maybe because I feel somehow the Gradle peeps have made the tool a bit easier to use than Maven. Or maybe because the integration with IDE’s seems to be cleaner. And I could probably go on, but you get the idea: after the initial playing with this, I’m digging it 🙂

And while using Gradle, here at Netflix, one of the things I started looking at is how to add a bit more automated defect detection to our code base in Ads Engineering, in order to improve our code quality. Of course, for those of you who are familiar with code coverage tools and the likes, Checkstyle, FindBugs and so on springs to mind. And all of these tools have (rather nice!) Gradle plugins — which makes this task a bit of a breeze!

One of the projects I’m dealing with though is a Groovy-based one, and I realized pretty quickly that some of the Java rules don’t get ported very easily to Groovy. As such I looked around for a Groovy specific code analysis tool and found it in CodeNarc. Brilliant!

CodeNarc has plugins for various build tools and frameworks, and a quick look at their integration page shows that plugging it into Gradle is as simple as:

apply plugin: 'codenarc'

in your build.gradle file. There is however a little “gotcha” it seems with this Gradle plugin. At a closer look at the Gradle plugin page I spotted this:

The CodeNarc plugin expects the following project layout: config/codenarc/codenarc.xml – CodeNarc configuration file.

This doesn’t seem like a problem at first sight, right? Convention over configuration, so what’s the problem?

Well the problem is not the fact that the CodeNarc plugin expects a certain file path, but instead that the file that it expects by default is in XML format!

CodeNarc supports (at least) 2 ways to specify the configuration:

  • (old style) XML configuration file
  • (new and better) Groovy based config

I prefer Groovy based config whenever available — it seems nicer to write :

ruleset {
    BitwiseOperatorInConditional
    ...
}

than to start throwing in all sorts of open/close XML tags and attributes.

So I was a bit annoyed by the fact that the default configuration switches me to XML. A bit of searching around, reveals that it’s very easy to change that, simply add a section like this in your build.gradle file:

codenarc {
    configFile = rootProject.file("path/to/file/with/codenarc/rules/codenarc.groovy")
}

Now I’m up and running with my (nice) Groovy-based CodeNarc config 🙂

As a closing comment if you’re that way inclined, you can actually get a deeper customization of the config file via codenarcMain and codenarcTest. Not my cup of tea so to speak, but it’s there for who needs this.