CodeNarc

CodeNarc is the static analyser of Groovy: it reads the source and reports a rule violation for every habit the ruleset names. This course is checked with it, so the code of the lessons is the code the tool accepts.

The ruleset

A ruleset is a Groovy file that lists the rules of a project. The one of this site is /opt/codenarc/aredel.groovy:

cat /opt/codenarc/aredel.groovy

ruleset {
    description 'aredel Groovy course'
    ruleset('rulesets/basic.xml')
    ruleset('rulesets/braces.xml')
    ruleset('rulesets/imports.xml')
    ruleset('rulesets/unused.xml')
    ruleset('rulesets/unnecessary.xml')
    ruleset('rulesets/exceptions.xml')
    ruleset('rulesets/formatting.xml') {
        LineLength { length = 100 }
        ClassStartsWithBlankLine { enabled = false }
        ClassEndsWithBlankLine { enabled = false }
        SpaceAroundMapEntryColon { characterBeforeColonRegex = /\S/; characterAfterColonRegex = /\s/ }
    }
    ruleset('rulesets/naming.xml') {
        ClassNameSameAsFilename { enabled = false }
    }
}

It enables the basic, braces, imports, unused, unnecessary, exceptions, formatting and naming rulesets, sets the line length to 100 and relaxes two formatting rules that a hand-written course file does not need. The file is the whole configuration.

A file with violations

Bad.groovy

class Bad { String name = "Ada" String greet() { return "Hello, ${name}"; } }

Three habits, three rules. A double-quoted string with nothing to interpolate is an UnnecessaryGString; a return at the end of a method is an UnnecessaryReturnKeyword; a semicolon at the end of a line is an UnnecessarySemicolon.

codenarc Bad.groovy

File: Bad.groovy
    Violation: Rule=UnnecessaryGString P=3 Line=2 Msg=[The String 'Ada' can be wrapped in single quotes instead of double quotes] Src=[String name = "Ada"]
    Violation: Rule=UnnecessaryReturnKeyword P=3 Line=5 Msg=[The return keyword is not needed and can be removed] Src=[return "Hello, ${name}";]
    Violation: Rule=UnnecessarySemicolon P=3 Line=5 Msg=[Semicolons as line endings can be removed safely] Src=[ return "Hello, ${name}"; ]
CodeNarc completed: (p1=0; p2=0; p3=3) <ms>
exit status: 1

Every line names the file, the rule, its priority, the line and the source. Priority 3 is a convention or a simplification, priority 1 a probable defect, and the summary counts both. The command exits with status 0 even with violations; a build makes it fail by passing -maxPriority1Violations 0 or by reading the report.

The fixed file

Good.groovy

class Good { String name = 'Ada' String greet() { "Hello, ${name}" } }

codenarc Good.groovy

CodeNarc completed: (p1=0; p2=0; p3=0) <ms>

The fixed file reports nothing. The three changes are the ones the messages asked for, and none of them changes what the program does: a linter is a review of the form, not of the algorithm.

Related

Article author: Arthur Isaev