All Projects → JLLeitschuh → Ktlint Gradle

JLLeitschuh / Ktlint Gradle

Licence: mit
A ktlint gradle plugin

Programming Languages

kotlin
9241 projects

Projects that are alternatives of or similar to Ktlint Gradle

Calces Gradle Plugin
Android构建工具集:包含快速实现组件化构建脚本,快速实现屏幕最小宽度适配脚本
Stars: ✭ 366 (-48.67%)
Mutual labels:  gradle, gradle-plugin
Gogradle
A Gradle Plugin Providing Full Support for Go
Stars: ✭ 712 (-0.14%)
Mutual labels:  gradle, gradle-plugin
Axion Release Plugin
Gradle release & version management plugin.
Stars: ✭ 372 (-47.83%)
Mutual labels:  gradle, gradle-plugin
Javapackager
📦 Gradle/Maven plugin to package Java applications as native Windows, Mac OS X, or GNU/Linux executables and create installers for them.
Stars: ✭ 285 (-60.03%)
Mutual labels:  gradle, gradle-plugin
Gradle Download Task
Adds a download task to Gradle that displays progress information
Stars: ✭ 478 (-32.96%)
Mutual labels:  gradle, gradle-plugin
Swagger Gradle Codegen
💫 A Gradle Plugin to generate your networking code from Swagger
Stars: ✭ 330 (-53.72%)
Mutual labels:  gradle, gradle-plugin
Gradle Static Analysis Plugin
Easy setup of static analysis tools for Android and Java projects.
Stars: ✭ 398 (-44.18%)
Mutual labels:  gradle, gradle-plugin
schema-registry-plugin
Gradle plugin to interact with Confluent Schema-Registry.
Stars: ✭ 60 (-91.58%)
Mutual labels:  gradle, gradle-plugin
Gradle Test Logger Plugin
A Gradle plugin for printing beautiful logs on the console while running tests
Stars: ✭ 460 (-35.48%)
Mutual labels:  gradle, gradle-plugin
Bnd
Bnd/Bndtools. Tooling to build OSGi bundles including Eclipse, Maven, and Gradle plugins.
Stars: ✭ 446 (-37.45%)
Mutual labels:  gradle, gradle-plugin
Gradle Code Quality Tools Plugin
Gradle plugin that generates ErrorProne, Findbugs, Checkstyle, PMD, CPD, Lint, Detekt & Ktlint Tasks for every subproject.
Stars: ✭ 282 (-60.45%)
Mutual labels:  gradle, gradle-plugin
Let
Annotation based simple API flavored with AOP to handle new Android runtime permission model
Stars: ✭ 532 (-25.39%)
Mutual labels:  gradle, gradle-plugin
Gradle Unused Resources Remover Plugin
Gradle Plugin that removes unused resources in Android projects.
Stars: ✭ 282 (-60.45%)
Mutual labels:  gradle, gradle-plugin
Gradle Android Command Plugin
Handy commands for testing Android on CI
Stars: ✭ 349 (-51.05%)
Mutual labels:  gradle, gradle-plugin
Gradle Aws Plugin
Gradle plugin to manage Amazon Web Services
Stars: ✭ 269 (-62.27%)
Mutual labels:  gradle, gradle-plugin
Androidautotrack
Android Asm 插桩 教学
Stars: ✭ 378 (-46.98%)
Mutual labels:  gradle, gradle-plugin
gradle-console-reporter
Gradle plugin to report various kinds of summaries to console.
Stars: ✭ 49 (-93.13%)
Mutual labels:  gradle, gradle-plugin
change-tracker-plugin
A Gradle plugin to help analyse the dependency between modules and run tasks only on modules impacted by specific set of changes.
Stars: ✭ 103 (-85.55%)
Mutual labels:  gradle, gradle-plugin
Javafx Gradle Plugin
Gradle plugin for JavaFX
Stars: ✭ 425 (-40.39%)
Mutual labels:  gradle, gradle-plugin
Laziertracker
本项目通过Android字节码插桩插件实现Android端无埋点(或自动埋点),并且支持根据配置文件实现业务数据的自动采集。
Stars: ✭ 485 (-31.98%)
Mutual labels:  gradle, gradle-plugin

Ktlint Gradle

Provides a convenient wrapper plugin over the ktlint project.

Latest plugin version: 10.0.0

Join the chat at https://kotlinlang.slack.com Build Status ktlint Gradle Plugin Portal

This plugin creates convenient tasks in your Gradle project that run ktlint checks or do code auto format.

The plugin can be applied to any project, but only activates if that project has the kotlin plugin applied. The assumption being that you would not want to lint code you weren't compiling.

Table of content

Supported Kotlin plugins

This plugin supports the following kotlin plugins:

  • "kotlin"
  • "kotlin-android"
  • "kotlin-multiplatform"
  • project kotlin script files
  • "org.jetbrains.kotlin.js"

If you know any new Kotlin plugin that is not in this list - please, open a new issue.

How to use

Minimal supported versions

This plugin was written using the new API available for the Gradle script Kotlin builds. This API is available in new versions of Gradle.

Minimal supported Gradle version: 6.0

Minimal supported ktlint version: 0.34.0 (additionally excluding 0.37.0 on Windows OS and 0.38.0 on all OS types)

Ktlint plugin

Simple setup

Build script snippet for use in all Gradle versions:

Groovy
buildscript {
  repositories {
    maven {
      url "https://plugins.gradle.org/m2/"
    }
  }
  dependencies {
    classpath "org.jlleitschuh.gradle:ktlint-gradle:<current_version>"
  }
}

repositories {
  // Required to download KtLint
  mavenCentral()
}

apply plugin: "org.jlleitschuh.gradle.ktlint"
Kotlin
buildscript {
  repositories {
    maven("https://plugins.gradle.org/m2/")
  }
  dependencies {
    classpath("org.jlleitschuh.gradle:ktlint-gradle:<current_version>")
  }
}

repositories {
  // Required to download KtLint
  mavenCentral()
}

apply(plugin = "org.jlleitschuh.gradle.ktlint")

Using new plugin API

Build script snippet for new, incubating, plugin mechanism introduced in Gradle 2.1:

plugins {
  id "org.jlleitschuh.gradle.ktlint" version "<current_version>"
}

repositories {
  // Required to download KtLint
  mavenCentral()
}

Applying to subprojects

Optionally apply plugin to all project modules:

Groovy
subprojects {
    apply plugin: "org.jlleitschuh.gradle.ktlint" // Version should be inherited from parent

    repositories {
        // Required to download KtLint
        mavenCentral()
    }

    // Optionally configure plugin
    ktlint {
        debug = true
    }
}
Kotlin
subprojects {
    apply(plugin = "org.jlleitschuh.gradle.ktlint") // Version should be inherited from parent

    repositories {
        // Required to download KtLint
        mavenCentral()
    }
    
    // Optionally configure plugin
    configure<org.jlleitschuh.gradle.ktlint.KtlintExtension> {
        debug.set(true)
    }
}

Testing KtLint snapshots

To test KtLint snapshots add following configuration into project build script (latest KtLint snapshot version name you could find here):

Groovy
repositories {
    maven {
      url 'https://oss.sonatype.org/content/repositories/snapshots'
    }
}

ktlint {
  version = "0.41.0-SNAPSHOT"
}
Kotlin
repositories {
    maven {
        setUrl("https://oss.sonatype.org/content/repositories/snapshots")
    }
}

ktlint {
    version.set("0.41.0-SNAPSHOT")
}

IntelliJ Idea Only Plugin

Note: This plugin is automatically applied by the main ktlint plugin.

This plugin just adds special tasks that can generate IntelliJ IDEA codestyle rules using ktlint.

Idea plugin simple setup

For all Gradle versions:

Use the same buildscript logic as above, but with this instead of the above suggested apply line. If you also want the GIT pre-commit gradle tasks, keep both apply variations.

apply plugin: "org.jlleitschuh.gradle.ktlint-idea"

Idea plugin setup using new plugin API

Build script snippet for new, incubating, plugin mechanism introduced in Gradle 2.1:

plugins {
  id("org.jlleitschuh.gradle.ktlint-idea") version "<current_version>"
}

Configuration

The following configuration block is optional.

If you don't configure this the defaults defined in the KtlintExtension object will be used.

The version of ktlint used by default may change between patch versions of this plugin. If you don't want to inherit these changes then make sure you lock your version here.

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

ktlint {
    version = "0.22.0"
    debug = true
    verbose = true
    android = false
    outputToConsole = true
    outputColorName = "RED"
    ignoreFailures = true
    enableExperimentalRules = true
    additionalEditorconfigFile = file("/some/additional/.editorconfig")
    disabledRules = ["final-newline"]
    reporters {
        reporter "plain"
        reporter "checkstyle"
        
        customReporters {
            "csv" {
                fileExtension = "csv"
                dependency = project(":project-reporters:csv-reporter")
            }
            "yaml" {
                fileExtension = "yml"
                dependency = "com.example:ktlint-yaml-reporter:1.0.0"
            }
        }
    }
    kotlinScriptAdditionalPaths {
        include fileTree("scripts/")
    }
    filter {
        exclude("**/generated/**")
        include("**/kotlin/**")
    }
}

dependencies {
    ktlintRuleset "com.github.username:rulseset:master-SNAPSHOT"
    ktlintRuleset files("/path/to/custom/rulseset.jar")
    ktlintRuleset project(":chore:project-ruleset") 
}

or in kotlin script:

Kotlin
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"))
    disabledRules.set(setOf("final-newline"))
    reporters {
        reporter(ReporterType.PLAIN)
        reporter(ReporterType.CHECKSTYLE)
        
        customReporters {
            register("csv") {
                fileExtension = "csv"
                dependency = project(":project-reporters:csv-reporter")
            }
            register("yaml") {
                fileExtension = "yml"
                dependency = "com.example:ktlint-yaml-reporter:1.0.0"
            }
        }
    }
    kotlinScriptAdditionalPaths {
        include(fileTree("scripts/"))
    }
    filter {
        exclude("**/generated/**")
        include("**/kotlin/**")
    }
}

dependencies {
    ktlintRuleset("com.github.username:rulseset:master-SNAPSHOT")
    ktlintRuleset(files("/path/to/custom/rulseset.jar"))
    ktlintRuleset(project(":chore:project-ruleset")) 
}

Setting reports output directory

It is possible also to define different from default output directory for generated reports (by default it is "build/reports/ktlint"):

Groovy
tasks.withType(org.jlleitschuh.gradle.ktlint.tasks.GenerateReportsTask) {
    reportsOutputDirectory = project.layout.buildDirectory.dir("other/location/$name")
}
Kotlin script
tasks.withType<org.jlleitschuh.gradle.ktlint.tasks.GenerateReportsTask>() {
    reportsOutputDirectory.set(
        project.layout.buildDirectory.dir("other/location/$name")
    )
}

Custom reporters

Note: If Ktlint custom reporter creates report output file internally, for example:

class CsvReporter(
    private val out: PrintStream
) : Reporter {
    override fun onLintError(file: String, err: LintError, corrected: Boolean) {
        val line = "$file;${err.line};${err.col};${err.ruleId};${err.detail};$corrected"
        out.println(line)
        File("some_other_file.txt").write(line) // <-- Here!!!
    }
}

"some_other_file.txt" won't be captured as task output. This may lead to the problem, that task will always be not "UP_TO_DATE" and caching will not work.

Samples

This repository provides the following examples of how to set up this plugin:

Tasks Added

Main tasks

This plugin adds following tasks to every project:

  • loadKtlintReporters - preloads KtLint Reporters
  • runKtlintCheckOverKotlinScripts - runs actual lint check over project Kotlin script files
  • ktlintKotlinScriptCheck - generates reports and prints issues into Gradle console based on lint check found errors. This task execution depends on loadKtlintReporters and runKtlintCheckOverKotlinScripts tasks execution outputs
  • runKtlintFormatOverKotlinScripts - tries to format according to the code style project Kotlin script files
  • ktlintKotlinScriptFormat - generate reports and prints issues into Gradle console based on found non-formattable errors. This task execution depends on loadKtlintReporters and runKtlintFormatOverKotlinScripts tasks execution outputs
  • ktlintCheck - checks all SourceSets and project Kotlin script files
  • ktlintFormat - tries to format according to the code style all SourceSets Kotlin files and project Kotlin script files

Then for each SourceSet plugin adds following tasks:

  • runKtlintCheckOver[source set name]SourceSet - runs actual lint check on every Kotlin file in given SourceSet
  • ktlint[source set name]SourceSetCheck - generates reports and prints issues into Gradle console based on lint check found errors. This task execution depends on loadKtlintReporters and runKtlintCheckOver[source set name]SourceSet tasks execution outputs
  • runKtlintFormatOver[source set name]SourceSet - tries to format according to the code style every Kotlin file in given SourceSet
  • ktlint[source set name]SourceSetCheck - generates reports and prints issues into Gradle console based on found non-formattable errors. This task execution depends on loadKtlintReporters and runKtlintFormatOver[source set name]SourceSet tasks execution outputs

Additional helper tasks

Following additional tasks are added:

  • ktlintApplyToIdea - The task generates IntelliJ IDEA (or Android Studio) Kotlin style files in the project .idea/ folder. Note that this task will overwrite the existing style file.
  • ktlintApplyToIdeaGlobally - The task generates IntelliJ IDEA (or Android Studio) Kotlin style files in the user home IDEA (or Android Studio) settings folder. Note that this task will overwrite the existing style file.
  • addKtlintCheckGitPreCommitHook - adds Git pre-commit hook, that runs ktlint check over staged files.
  • addKtlintFormatGitPreCommitHook - adds Git pre-commit hook, that runs ktlint format over staged files and adds fixed files back to commit.

All these additional tasks are always added only to the root project.

FAQ

  • Is it possible to not stop task execution if some of the subprojects tasks failed?

Yes. Just use gradle --continue option:

$ ./gradlew --continue ktlintCheck

No. These approaches are not equivalent to how they work. The problem that the plugin may not find some of the kotlin plugins if both approaches are used in the project configuration. Especially it is related to the Android plugin.

  • Does plugin check change files incrementally?

Yes, check tasks support it. On the first run, the task will check all files in the source set, on subsequent runs it will check only added/modified files.

Format tasks do not check files incrementally.

  • I could not filter dynamically attached sources that are located outside of the project dir.

Gradle based filtering are only working for files located inside project (subproject) folder, see https://github.com/gradle/gradle/issues/3417 To filter files outside project dir, use:

exclude { element -> element.file.path.contains("generated/") }
  • Running KtLint fails with strange exception (for example, check #383)

Ensure you are not pinning Kotlin version for "ktlint*" configurations added by plugin.

KtLint relies on Kotlin compiler to parse source files. Each version of KtLint are build using specific Kotlin version.

To exclude "ktlint*" Gradle configurations from Kotlin version pinning - use following approach:

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

Developers

Importing

Import the settings.gradle.kts file into your IDE.

To enable the Android sample either define the ANDROID_HOME environmental variable or add a local.properties file to the project root folder with the following content:

sdk.dir=<android-sdk-location>

Building

Building the plugin: ./plugin/gradlew build

On how to run the current plugin snapshot check on sample projects: ./gradlew ktlintCheck

Running tests from IDEA IDE

To run tests in IDEA IDE, firstly you need to run following gradle task (or after any dependency change):

$ ./plugin/gradlew pluginUnderTestMetadata

Optionally you can add this step test run configuration.

Links

Ktlint Gradle Plugin on the Gradle Plugin Registry

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].