Search code examples
javagradlebuild.gradlecheckstylegradle-kotlin-dsl

Run Checkstyle before gradle build on build.gradle.kts and make build fail if there are issues


I added Checkstyle to my Gradle project's build.gradle.kts succesfully:

plugins {
    ...
    checkstyle
}

checkstyle {
    toolVersion = "10.3.2"
    isIgnoreFailures = false // Added this so that the tasks fail if CheckStyle errors are present.
}

I now have access to CheckStyle's tools with:

  • gradle checkstyleMain
  • gradle checkstyleTest

They both work as expected showing warnings and generating HTML reports.

I now want to make the gradle run task run the checkstyleMain task before itself and to fail if there are CheckStyle issues.

Is there a way to do this? The only references I've found so far are not very clear and are for Groovy and Android instead of Kotlin and Java build.gradle files.


Solution

  • This is what worked for me:

    checkstyle {
        toolVersion = "10.3.2"
        isIgnoreFailures = false
        maxWarnings = 0
        maxErrors = 0
    }
    
    val build = "build"
    tasks[build].dependsOn("checkstyleMain")
    

    Now gradle build fails if there are errors found in checkstyleMain .