ktlint-gradle

repository·main·Indexed 23 days ago

https://github.com/jlleitschuh/ktlint-gradle

A Gradle wrapper plugin for the ktlint project that provides tasks for running linting checks and automatic code formatting. It supports Kotlin plugins including kotlin, kotlin-android, kotlin-multiplatform, and org.jetbrains.kotlin.js. Requires Gradle 7.4+, Kotlin 1.4+, ktlint 0.47.1+, and Android Gradle plugin 4.1.0+.

Tokens
2.8K
Snippets
8
Records
14
Agent score
33%

What's inside ktlint-gradle

  1. Overview of Ktlint Gradle

    main

    Ktlint Gradle is a Gradle wrapper plugin for the ktlint project. It provides convenient Gradle tasks to run ktlint checks or perform automatic code formatting.

    Note: The plugin can be applied to any project, but it only activates if a Kotlin plugin is also applied. This ensures that you only lint code that is being compiled.

  2. Use KtLint baseline support

    main

    The plugin supports KtLint baselines to ignore existing lint errors.

    Limitations:

    • format tasks ignore the baseline.
    • One baseline file is generated per Gradle project (module).

    To generate a new baseline, run the ktlintGenerateBaseline task.

  3. How to handle task failures in Ktlint Gradle

    main

    If you want to prevent the entire Gradle build from stopping when a subproject's Ktlint task fails, use the --continue flag. This allows Gradle to attempt running other tasks even if some linting checks fail.

    $ ./gradlew --continue ktlintCheck
  4. Apply the Ktlint plugin to all subprojects

    main

    To apply the plugin to all modules in a multi-project build, use the subprojects block. Note that the plugin version should be inherited from the parent project.

    subprojects {
        apply(plugin = "org.jlleitschuh.gradle.ktlint") // Version should be inherited from parent
    
        repositories {
            mavenCentral()
        }
    
        // Optionally configure plugin
        configure<org.jlleitschuh.gradle.ktlint.KtlintExtension> {
            debug.set(true)
        }
    }
  5. Install the Ktlint Gradle plugin

    main

    You can install the plugin using the modern plugins block, a Gradle Version Catalog, or the legacy apply method.

    ### Simple setup (Kotlin DSL)
    ```kotlin
    plugins {
      id("org.jlleitschuh.gradle.ktlint") version "<current_version>"
    }
    
    repositories {
      mavenCentral()
    }

    Using Version Catalog

    Add to libs.versions.toml:

    [versions]
    ktlint = "<current_version>"
    
    [plugins]
    ktlint = { id = "org.jlleitschuh.gradle.ktlint", version.ref = "ktlint" }

    Apply in build script:

    plugins {
      alias(libs.plugins.ktlint)
    }
    
    repositories {
      mavenCentral()
    }

    Using legacy apply method

    buildscript {
      repositories {
        maven("https://plugins.gradle.org/m2/")
      }
      dependencies {
        classpath("org.jlleitschuh.gradle:ktlint-gradle:<current_version>")
      }
    }
    
    repositories {
      mavenCentral()
    }
    
    apply(plugin = "org.jlleitschuh.gradle.ktlint")
  6. How to filter files located outside the project directory

    main

    Gradle-based filtering (like exclude) only works for files located inside the project (subproject) folder. To filter files located outside the project directory, use a custom exclusion block in your configuration:

    exclude { element -> element.file.path.contains("generated/") }
  7. Configure the KtlintExtension

    main

    The ktlint extension allows you to customize linting behavior. All properties are optional and defaults are provided by the KtlintExtension object.

    Note on compatibility:

    • additionalEditorconfigFile is not supported with ktlint 0.47+
    • additionalEditorconfig is not supported until ktlint 0.49
    • disabledRules is not supported with ktlint 0.48+
    import org.jlleitschuh.gradle.ktlint.reporter.ReporterType
    
    configure<org.jlleitschuh.gradle.ktlint.KtlintExtension> {
        version.set("0.22.0")
        debug.set(true)
        verbose.set(true)
        android.set(false)
        outputToConsole.set(true)
        outputColorName.set("RED")
        ignoreFailures.set(true)
        enableExperimentalRules.set(true)
        additionalEditorconfigFile.set(file("/some/additional/.editorconfig"))
        additionalEditorconfig.set(
            mapOf(
                "max_line_length" to "20"
            )
        )
        disabledRules.set(setOf("final-newline"))
        baseline.set(file("my-project-ktlint-baseline.xml"))
        reporters {
            reporter(ReporterType.PLAIN)
            reporter(ReporterType.CHECKSTYLE)
    
            customReporters {
                register("csv") {
                    fileExtension = "csv"
                    dependency = "com.example:ktlint-yaml-reporter:1.0.0"
                }
            }
        }
        kotlinScriptAdditionalPaths {
            include(fileTree("scripts/"))
        }
        filter {
            exclude("**/generated/**")
            include("**/kotlin/**")
        }
    }
    
    dependencies {
        ktlintRuleset("com.github.username:rulseset:main-SNAPSHOT")
        ktlintRuleset(files("/path/to/custom/rulseset.jar"))
        ktlintRuleset(project(":chore:project-ruleset"))
    }
  8. Increase KtLint worker memory usage

    main

    By default, KtLint Gradle workers use a maximum heap size of 256mb. If your project requires more memory, you can increase it by configuring the workerMaxHeapSize property on BaseKtLintCheckTask instances.

    tasks.withType<org.jlleitschuh.gradle.ktlint.tasks.BaseKtLintCheckTask> {
        workerMaxHeapSize.set("512m")
    }
  9. Configure the ktlint version

    main

    The plugin uses a default ktlint version which may change between plugin patch versions. To ensure stability, you can lock the version in two ways:

    1. Via the ktlint extension in your build script.
    2. Via a ktlint-version.properties file, which allows coordination between this plugin and the IntelliJ Kotlin plugin.
  10. Set the reports output directory

    main

    By default, reports are generated in build/reports/ktlint. You can change this by configuring the reportsOutputDirectory property on GenerateReportsTask instances.

    tasks.withType<org.jlleitschuh.gradle.ktlint.tasks.GenerateReportsTask> {
        reportsOutputDirectory.set(
            project.layout.buildDirectory.dir("other/location/$name")
        )
    }
  11. Prevent Kotlin version pinning in ktlint configurations

    main

    KtLint relies on the Kotlin compiler to parse source files, and each version of KtLint is built with a specific Kotlin version. If you are forcing a specific Kotlin version globally in your project, it might conflict with the ktlint* configurations added by the plugin, causing exceptions.

    To avoid this, ensure you are not pinning the Kotlin version for any configuration that starts with ktlint. You can use a resolutionStrategy to exclude these configurations from your global version forcing:

    configurations.all {
        if (!name.startsWith("ktlint")) {
            resolutionStrategy {
                eachDependency {
                    // Force Kotlin to our version
                    if (requested.group == "org.jetbrains.kotlin") {
                        useVersion("1.3.72")
                    }
                }
            }
        }
    }