Configure codeNarc plugin

I have in buildSrc - multiProject build,so I want to apply to all of the subprojects ‘codeNarc’ plugin and to configure it. So in the build.gradle file in the buildSrc, I wrote

subprojects{
    apply plugin: "codenarc"
      tasks.withType(CodeNarc).each { codeNarcTask ->
        println "-------------------------------->"+codeNarcTask.name
        codeNarcTask.ignoreFailures = true
        codeNarcTask.configFile = file("../../config/codenarc/codenarc.xml")
          codeNarcTask.maxPriority1Violations = 2
        codeNarcTask.maxPriority2Violations = 4
        codeNarcTask.maxPriority3Violations
   = 7
      }

But Only codenarc is applyed. The other configurations are not applied, even the println doesn’t work and with 1 violation the build fails? Where is my fault?

Hey.

the problem with your snippet is, that it your configuration block is only applied to the CodeNarc tasks that are already in the tasks container and will not affect CodeNarc tasks added later on (e.g. when the java plugin is applied). The culprit is this line:

tasks.withType(CodeNarc).each { codeNarcTask ->

To fix this behaviour, you should not use the .each method. instead gradle offers you to apply this logic lazily for all tasks in that container and all matching tasks added somewhen in the future by using this syntax instead:

tasks.withType(CodeNarc) { codeNarcTask ->

OO this works. But if I try to put

tasks.withType(CodeNarc).each { codeNarcTask ->

in project.afterEvaluate block this(old version with each) doesn’t work. And I am wondering why? In afterEvaluate I have CodeNarc tasks in tasks container, or I am wrong?

‘each’ is a Groovy method and is executed eagerly. You need to use Gradle’s lazy ‘all’ method instead (which can be omitted in some cases).

Thanks, Peter and Rene. You can mark the topic as аnswered.