ktlint and KotlinProjectExtension

2.4k Views Asked by At

I tried to implement Kotlin check style in project using ktlint. I added

plugins {
    id("org.jlleitschuh.gradle.ktlint") version "10.1.0" apply false
}

in root build.gradle.kts and

plugins {
id("org.jlleitschuh.gradle.ktlint")
}

in build.gradle.kts in subprojects

When I called

gradlew ktlintCheck

I got

FAILURE: Build failed with an exception.
 
* What went wrong:
org/jetbrains/kotlin/gradle/dsl/KotlinProjectExtension

How can I fix it?

1

There are 1 best solutions below

0
On

This is how I went about it for Klint with Kotlin DSL on gradle.kts files for Android Gradle. Have also added Spotless with Kotlin DSL ( code formatter ) at the same time.

It is also worth noting mine is NOT a Multi Module project.

Step 1 - gradle.kts (app) - Add Klint and Spotless plugins and import Reporters

import org.jlleitschuh.gradle.ktlint.reporter.ReporterType

plugins {
            id("com.android.application") ... 
            //Klint
            id("org.jlleitschuh.gradle.ktlint") version "11.0.0"

            //Spotless
            id("com.diffplug.spotless")
        }

Step 2 - gradle.kts (app) - Configure Klint only

// ktlintFormat task will need to run before preBuild
tasks.getByPath("preBuild")
    .dependsOn("ktlintFormat")

configure<org.jlleitschuh.gradle.ktlint.KtlintExtension> {

    android.set(true)
    ignoreFailures.set(false)
    disabledRules.set(setOf("final-newline", "no-wildcard-imports"))
    reporters {
        reporter(ReporterType.PLAIN)
        reporter(ReporterType.CHECKSTYLE)
        reporter(ReporterType.SARIF)
    }
}

Step 3 - gradle.kts(app) - Configure Spotless only

configure<com.diffplug.gradle.spotless.SpotlessExtension> {
    kotlin {
        // version, setUseExperimental, userData and editorConfigOverride are all optional
        ktlint("0.45.2")
            .setUseExperimental(true)
            .userData(mapOf("android" to "true"))
            .editorConfigOverride(mapOf("indent_size" to 2))
    }
    kotlinGradle {
        target("*.gradle.kts") // default target for kotlinGradle
        ktlint() // or ktfmt() or prettier()
    }
}

Step 4 - gradle.kts(project) - Add Spotless in the Classpath

buildscript {

    repositories{
        google()
        mavenCentral()
    }
    dependencies {
        
        ... 
        //class path for Spotless
        classpath("com.diffplug.spotless:spotless-plugin-gradle:6.9.1")
    }

}

The 2 plugins works fine with this set-up.