Giter VIP home page Giter VIP logo

ktlint-gradle's Introduction

Ktlint Gradle

Provides a convenient wrapper plugin over the ktlint project.

Latest plugin version: 12.1.0

Join the chat at https://kotlinlang.slack.com Build and Check ktlint Gradle Plugin Portal OpenSSF Scorecard

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: 7.4

Minimal supported Kotlin version: 1.4

Minimal supported ktlint version: 0.47.1

Minimal supported Android Gradle plugin version: 4.1.0

Ktlint plugin

Simple setup

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

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

repositories {
  // Required to download KtLint
  mavenCentral()
}
Kotlin
plugins {
  id("org.jlleitschuh.gradle.ktlint") version "<current_version>"
}

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

Using legacy apply method

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")

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)
    }
}

Baseline support

Plugin supports KtLint baseline with following limitations:

  • Format tasks ignore baseline. See #1072 KtLint issue for more details.
  • One baseline file is generated per one Gradle project (module).

Run task ktlintGenerateBaseline to generate a new baseline.

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("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

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

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

Idea plugin setup using legacy apply method

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"

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. Consult the ktlint release notes for more information about the differences between ktlint versions.

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")  // not supported with ktlint 0.47+
    additionalEditorconfig = [ // not supported until ktlint 0.49
        "max_line_length": "20"
    ]
    disabledRules = ["final-newline"] // not supported with ktlint 0.48+
    baseline = file("my-project-ktlint-baseline.xml")
    reporters {
        reporter "plain"
        reporter "checkstyle"
        reporter "sarif"

        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:main-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")) // not supported with ktlint 0.47+
    additionalEditorconfig.set( // not supported until ktlint 0.49
        mapOf(
            "max_line_length" to "20"
        )
    )
    disabledRules.set(setOf("final-newline")) // not supported with ktlint 0.48+
    baseline.set(file("my-project-ktlint-baseline.xml"))
    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:main-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.

Changing workers memory usage

By default, KtLint Gradle workers will use at most 256mb of heap size. For some projects it may be not enough, but it is possible to change:

Groovy
tasks.withType(org.jlleitschuh.gradle.ktlint.tasks.BaseKtLintCheckTask).configureEach {
    it.workerMaxHeapSize.set("512m")
}
Kotlin script
tasks.withType<org.jlleitschuh.gradle.ktlint.tasks.BaseKtLintCheckTask> {
    workerMaxHeapSize.set("512m")
}

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 gradle/gradle#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 -p ./plugin pluginUnderTestMetadata

Optionally you can add this step test run configuration.

Links

Ktlint Gradle Plugin on the Gradle Plugin Registry

ktlint-gradle's People

Contributors

adammc331 avatar aleksanderbrzozowski avatar arranlomas avatar davidnelson-hms avatar devisnik avatar eskatos avatar friederbluemle avatar goooler avatar hmiyado avatar jlleitschuh avatar kevinrob avatar kotlinisland avatar lampietti avatar m-burst avatar mverleg avatar nuhkoca avatar olegivo avatar orafaaraujo avatar originx avatar radimvaculik avatar rbleuse avatar rschattauer avatar shiraji avatar tapchicoma avatar tasomaniac avatar tbroyer avatar uzzu avatar wakingrufus avatar wolfs avatar zhenleiji avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ktlint-gradle's Issues

Print report path

Hello,

Is there a way to print out the path for the report file on the console ? Useful for CI/CD environments.
If not, is there a work around to print it out ?

Kind Regards .

Fail build only after all sources are checked.

When plugin runs checks it fails the build on first failed check task(for example, test sources) and doesn't run others checks(for example, main sources).

It becomes more inconvenient in multi-module projects.

Plugin should run all check tasks and fail build after all check tasks run if one or more of them are failed.

Editorconfig file should be treated as input

Currently check task caching doesn't take into consideration any changes in .editorconfig file.

For example, if I add max_line_length=40 to .editorconfig, task result will still be taken from Gradle cache.

Plugin does not support pre 3.0 versions of the Android Gradle Plugin

Repro:

Apply to Android app using Kotlin.

Error:

FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring project ':app'.
> Failed to notify project evaluation listener.
   > com.android.build.gradle.internal.VariantManager.getVariantScopes()Ljava/util/List;

* Try:
Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Exception is:
org.gradle.api.ProjectConfigurationException: A problem occurred configuring project ':app'.
        at org.gradle.configuration.project.LifecycleProjectEvaluator.addConfigurationFailure(LifecycleProjectEvaluator.java:94)
        at org.gradle.configuration.project.LifecycleProjectEvaluator.notifyAfterEvaluate(LifecycleProjectEvaluator.java:89)
        at org.gradle.configuration.project.LifecycleProjectEvaluator.doConfigure(LifecycleProjectEvaluator.java:70)
        at org.gradle.configuration.project.LifecycleProjectEvaluator.access$100(LifecycleProjectEvaluator.java:34)
        at org.gradle.configuration.project.LifecycleProjectEvaluator$ConfigureProject.run(LifecycleProjectEvaluator.java:110)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110)
        at org.gradle.configuration.project.LifecycleProjectEvaluator.evaluate(LifecycleProjectEvaluator.java:50)
        at org.gradle.api.internal.project.DefaultProject.evaluate(DefaultProject.java:667)
        at org.gradle.api.internal.project.DefaultProject.evaluate(DefaultProject.java:136)
        at org.gradle.execution.TaskPathProjectEvaluator.configure(TaskPathProjectEvaluator.java:35)
        at org.gradle.execution.TaskPathProjectEvaluator.configureHierarchy(TaskPathProjectEvaluator.java:62)
        at org.gradle.execution.TaskSelector.getSelection(TaskSelector.java:100)
        at org.gradle.execution.TaskSelector.getSelection(TaskSelector.java:81)
        at org.gradle.execution.commandline.CommandLineTaskParser.parseTasks(CommandLineTaskParser.java:42)
        at org.gradle.execution.TaskNameResolvingBuildConfigurationAction.configure(TaskNameResolvingBuildConfigurationAction.java:44)
        at org.gradle.execution.DefaultBuildConfigurationActionExecuter.configure(DefaultBuildConfigurationActionExecuter.java:48)
        at org.gradle.execution.DefaultBuildConfigurationActionExecuter.access$000(DefaultBuildConfigurationActionExecuter.java:25)
        at org.gradle.execution.DefaultBuildConfigurationActionExecuter$1.proceed(DefaultBuildConfigurationActionExecuter.java:54)
        at org.gradle.execution.DefaultTasksBuildExecutionAction.configure(DefaultTasksBuildExecutionAction.java:44)
        at org.gradle.execution.DefaultBuildConfigurationActionExecuter.configure(DefaultBuildConfigurationActionExecuter.java:48)
        at org.gradle.execution.DefaultBuildConfigurationActionExecuter.access$000(DefaultBuildConfigurationActionExecuter.java:25)
        at org.gradle.execution.DefaultBuildConfigurationActionExecuter$1.proceed(DefaultBuildConfigurationActionExecuter.java:54)
        at org.gradle.execution.ExcludedTaskFilteringBuildConfigurationAction.configure(ExcludedTaskFilteringBuildConfigurationAction.java:47)
        at org.gradle.execution.DefaultBuildConfigurationActionExecuter.configure(DefaultBuildConfigurationActionExecuter.java:48)
        at org.gradle.execution.DefaultBuildConfigurationActionExecuter.select(DefaultBuildConfigurationActionExecuter.java:36)
        at org.gradle.initialization.DefaultGradleLauncher$CalculateTaskGraph.run(DefaultGradleLauncher.java:268)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110)
        at org.gradle.initialization.DefaultGradleLauncher.constructTaskGraph(DefaultGradleLauncher.java:175)
        at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:130)
        at org.gradle.initialization.DefaultGradleLauncher.executeTasks(DefaultGradleLauncher.java:109)
        at org.gradle.internal.invocation.GradleBuildController$1.call(GradleBuildController.java:78)
        at org.gradle.internal.invocation.GradleBuildController$1.call(GradleBuildController.java:75)
        at org.gradle.internal.work.DefaultWorkerLeaseService.withLocks(DefaultWorkerLeaseService.java:152)
        at org.gradle.internal.invocation.GradleBuildController.doBuild(GradleBuildController.java:100)
        at org.gradle.internal.invocation.GradleBuildController.run(GradleBuildController.java:75)
        at org.gradle.tooling.internal.provider.ExecuteBuildActionRunner.run(ExecuteBuildActionRunner.java:28)
        at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
        at org.gradle.tooling.internal.provider.ValidatingBuildActionRunner.run(ValidatingBuildActionRunner.java:32)
        at org.gradle.launcher.exec.RunAsBuildOperationBuildActionRunner$1.run(RunAsBuildOperationBuildActionRunner.java:43)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110)
        at org.gradle.launcher.exec.RunAsBuildOperationBuildActionRunner.run(RunAsBuildOperationBuildActionRunner.java:40)
        at org.gradle.tooling.internal.provider.SubscribableBuildActionRunner.run(SubscribableBuildActionRunner.java:51)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:49)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:32)
        at org.gradle.launcher.exec.BuildTreeScopeBuildActionExecuter.execute(BuildTreeScopeBuildActionExecuter.java:39)
        at org.gradle.launcher.exec.BuildTreeScopeBuildActionExecuter.execute(BuildTreeScopeBuildActionExecuter.java:25)
        at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:80)
        at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:53)
        at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:57)
        at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:32)
        at org.gradle.tooling.internal.provider.GradleThreadBuildActionExecuter.execute(GradleThreadBuildActionExecuter.java:36)
        at org.gradle.tooling.internal.provider.GradleThreadBuildActionExecuter.execute(GradleThreadBuildActionExecuter.java:25)
        at org.gradle.tooling.internal.provider.ParallelismConfigurationBuildActionExecuter.execute(ParallelismConfigurationBuildActionExecuter.java:43)
        at org.gradle.tooling.internal.provider.ParallelismConfigurationBuildActionExecuter.execute(ParallelismConfigurationBuildActionExecuter.java:29)
        at org.gradle.tooling.internal.provider.StartParamsValidatingActionExecuter.execute(StartParamsValidatingActionExecuter.java:64)
        at org.gradle.tooling.internal.provider.StartParamsValidatingActionExecuter.execute(StartParamsValidatingActionExecuter.java:29)
        at org.gradle.tooling.internal.provider.SessionFailureReportingActionExecuter.execute(SessionFailureReportingActionExecuter.java:59)
        at org.gradle.tooling.internal.provider.SessionFailureReportingActionExecuter.execute(SessionFailureReportingActionExecuter.java:44)
        at org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:45)
        at org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:30)
        at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:67)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
        at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:37)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
        at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
        at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:74)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:72)
        at org.gradle.util.Swapper.swap(Swapper.java:38)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:72)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
        at org.gradle.launcher.daemon.server.exec.LogAndCheckHealth.execute(LogAndCheckHealth.java:55)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
        at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:62)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
        at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:82)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
        at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50)
        at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:295)
        at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
        at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
        at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
Caused by: org.gradle.internal.event.ListenerNotificationException: Failed to notify project evaluation listener.
        at org.gradle.internal.event.AbstractBroadcastDispatch.dispatch(AbstractBroadcastDispatch.java:86)
        at org.gradle.internal.event.BroadcastDispatch$CompositeDispatch.dispatch(BroadcastDispatch.java:324)
        at org.gradle.internal.event.BroadcastDispatch$CompositeDispatch.dispatch(BroadcastDispatch.java:234)
        at org.gradle.internal.event.ListenerBroadcast.dispatch(ListenerBroadcast.java:140)
        at org.gradle.internal.event.ListenerBroadcast.dispatch(ListenerBroadcast.java:37)
        at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
        at com.sun.proxy.$Proxy25.afterEvaluate(Unknown Source)
        at org.gradle.configuration.project.LifecycleProjectEvaluator.notifyAfterEvaluate(LifecycleProjectEvaluator.java:76)
        ... 94 more
Caused by: java.lang.NoSuchMethodError: com.android.build.gradle.internal.VariantManager.getVariantScopes()Ljava/util/List;
        at org.jlleitschuh.gradle.ktlint.KtlintPlugin$addKtLintTasksToAndroidKotlinPlugin$1$1.execute(KtlintPlugin.kt:85)
        at org.jlleitschuh.gradle.ktlint.KtlintPlugin$addKtLintTasksToAndroidKotlinPlugin$1$1.execute(KtlintPlugin.kt:31)
        at org.gradle.internal.event.BroadcastDispatch$ActionInvocationHandler.dispatch(BroadcastDispatch.java:91)
        at org.gradle.internal.event.BroadcastDispatch$ActionInvocationHandler.dispatch(BroadcastDispatch.java:80)
        at org.gradle.internal.event.AbstractBroadcastDispatch.dispatch(AbstractBroadcastDispatch.java:42)
        at org.gradle.internal.event.BroadcastDispatch$SingletonDispatch.dispatch(BroadcastDispatch.java:230)
        at org.gradle.internal.event.BroadcastDispatch$SingletonDispatch.dispatch(BroadcastDispatch.java:149)
        at org.gradle.internal.event.AbstractBroadcastDispatch.dispatch(AbstractBroadcastDispatch.java:58)
        ... 101 more


* Get more help at https://help.gradle.org

Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0.
See https://docs.gradle.org/4.5/userguide/command_line_interface.html#sec:command_line_warnings

BUILD FAILED in 1s

Depend on kotlin 1.1.1

This project depends on kotlin-stdlib 1.1.0-rc-91.

Now that kotlin 1.1.1 is released, isn't it better to depend on a stable version?

ktlintFormat and ktlintCheck also run compilation related tasks

At the very least, this issue pertains to Android projects. I recall a previous version of this plugin running much faster as I believe all it did was simply invoke ktlint. The more recent versions seem to do a lot more than just run ktlint. This plugin now seems to build your app before running ktlint. Not sure if this is by design.

Please see logs below. Both tasks were run after running ./gradlew clean. The project I tested this with was a barebones sample Android project.

ktlintFormat

./gradlew ktlintFormat --console=plain
:app:preBuild UP-TO-DATE
:app:preDebugAndroidTestBuild
:app:compileDebugAndroidTestAidl
:app:preDebugBuild
:app:checkDebugManifest
:app:createDebugCompatibleScreenManifests
:app:processDebugManifest
:app:processDebugAndroidTestManifest
:app:compileDebugAndroidTestRenderscript
:app:generateDebugAndroidTestBuildConfig
:app:generateDebugAndroidTestResValues
:app:generateDebugAndroidTestResources
:app:mergeDebugAndroidTestResources
:app:splitsDiscoveryTaskDebugAndroidTest
:app:processDebugAndroidTestResources
:app:ktlintDebugAndroidTestFormat
:app:compileDebugAidl
:app:compileDebugRenderscript
:app:generateDebugBuildConfig
:app:generateDebugResValues
:app:generateDebugResources
:app:mergeDebugResources
:app:splitsDiscoveryTaskDebug
:app:processDebugResources
:app:ktlintDebugFormat
:app:ktlintDebugUnitTestFormat
:app:preReleaseBuild
:app:compileReleaseAidl
:app:compileReleaseRenderscript
:app:checkReleaseManifest
:app:generateReleaseBuildConfig
:app:generateReleaseResValues
:app:generateReleaseResources
:app:mergeReleaseResources
:app:createReleaseCompatibleScreenManifests
:app:processReleaseManifest
:app:splitsDiscoveryTaskRelease
:app:processReleaseResources
:app:ktlintReleaseFormat
:app:ktlintReleaseUnitTestFormat
:ktlintFormat
:app:ktlintFormat

BUILD SUCCESSFUL in 5s
36 actionable tasks: 36 executed

ktlintCheck

./gradlew ktlintCheck --console=plain
:app:preBuild UP-TO-DATE
:app:preDebugAndroidTestBuild
:app:compileDebugAndroidTestAidl
:app:preDebugBuild
:app:checkDebugManifest
:app:createDebugCompatibleScreenManifests
:app:processDebugManifest
:app:processDebugAndroidTestManifest
:app:compileDebugAndroidTestRenderscript
:app:generateDebugAndroidTestBuildConfig
:app:generateDebugAndroidTestResValues
:app:generateDebugAndroidTestResources
:app:mergeDebugAndroidTestResources
:app:splitsDiscoveryTaskDebugAndroidTest
:app:processDebugAndroidTestResources
:app:ktlintDebugAndroidTestCheck
:app:compileDebugAidl
:app:compileDebugRenderscript
:app:generateDebugBuildConfig
:app:generateDebugResValues
:app:generateDebugResources
:app:mergeDebugResources
:app:splitsDiscoveryTaskDebug
:app:processDebugResources
:app:ktlintDebugCheck
:app:ktlintDebugUnitTestCheck
:app:preReleaseBuild
:app:compileReleaseAidl
:app:compileReleaseRenderscript
:app:checkReleaseManifest
:app:generateReleaseBuildConfig
:app:generateReleaseResValues
:app:generateReleaseResources
:app:mergeReleaseResources
:app:createReleaseCompatibleScreenManifests
:app:processReleaseManifest
:app:splitsDiscoveryTaskRelease
:app:processReleaseResources
:app:ktlintReleaseCheck
:app:ktlintReleaseUnitTestCheck
:ktlintCheck
:app:ktlintCheck

BUILD SUCCESSFUL in 6s
36 actionable tasks: 36 executed

Provide output to console

Ktlint since 0.10.0 allows to provide multiple outputs.

Plugin should enable plain output by default for console, this will allow to see style failures in console builds.

Plugin fails on gradle 4.10 snapshots

Trying our build that applies the ktlin plugin version 4.1.0 in our buildSrc project against a Gradle 4.10 snapshot gives the following error:

> Task :buildSrc:ktlintMainCheck FAILED
Exception in thread "main" java.lang.NoClassDefFoundError: org/jetbrains/kotlin/preprocessor/PreprocessorKt
        at com.github.shyiko.ktlint.Main$loadReporter$2.invoke(Main.kt:396)
        at com.github.shyiko.ktlint.Main.loadReporter(Main.kt:410)
        at com.github.shyiko.ktlint.Main.main(Main.kt:262)
Caused by: java.lang.ClassNotFoundException: org.jetbrains.kotlin.preprocessor.PreprocessorKt
        at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
        ... 3 more

Inspecting the buildSrc dependencies, it looks like the snapshot is using a Kotlin 1.2.60-eap build:

org.jetbrains.kotlin:kotlin-reflect:1.2.60-eap-44
org.jetbrains.kotlin:kotlin-stdlib:1.2.60-eap-44
org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.2.60-eap-44

I presume that the error is due to changes in the Kotlin libs.

Not necessarily advocating for an immediate fix, but more a head-up that as it currently stands, this plugin will break with Gradle 4.10 if it ships with kotlin libs based on 1.2.60 or later.

@eskatos @bamboo I presume that we're unlikely to roll this back to 1.2.41 at this point, right?

Plugin fails on missing kotlin-gradle-plugin dependency

with build.gradle:

plugins {
    id 'org.jetbrains.kotlin.jvm' version '1.1.1'
    id 'org.jlleitschuh.gradle.ktlint' version '1.0.2'
}

gradle tasks fails with:

> Could not resolve all dependencies for configuration ':classpath'.
   > Could not find org.jetbrains.kotlin:kotlin-gradle-plugin:1.1.0-rc-91.
     Searched in the following locations:
         https://plugins.gradle.org/m2/org/jetbrains/kotlin/kotlin-gradle-plugin/1.1.0-rc-91/kotlin-gradle-plugin-1.1.0-rc-91.pom
         https://plugins.gradle.org/m2/org/jetbrains/kotlin/kotlin-gradle-plugin/1.1.0-rc-91/kotlin-gradle-plugin-1.1.0-rc-91.jar
     Required by:
         project : > gradle.plugin.org.jlleitschuh.gradle:ktlint-gradle:1.0.2

The problem goes away if you add this to the top of build.gradle:

buildscript {
    repositories {
        maven { url 'http://dl.bintray.com/kotlin/kotlin-eap-1.1' }
    }
}

I'm a bit puzzled as to the cause since your 1.0.2 plugin appears to depend on kotlin 1.1.1 ๐Ÿค”.

Add a task to check project kotlin dsl files

Currently, while KtlintCheck task supports checking kts files, plugin itself doesn't add any task for this files.

Plugin should add task that checks project kotlin gradle dsl files.

Not in `check` task

My project has

apply plugin: 'kotlin'
apply plugin: "org.jlleitschuh.gradle.ktlint"

and ./gradlew ktlintCheck works fine.

But ./gradlew check does not run ktlint. I tried adding check.dependsOn ktlintCheck but this results in:

> Could not get unknown property 'ktlintCheck' for root project 'xyz' of type org.gradle.api.Project.

Is there any way to get this attached to the check task?

Release new version

Hi, can you release new version of this library? Readme already contains changes like outputToConsole = true and reporters = ["PLAIN", "CHECKSTYLE"] but latest version doesn't implement them which is confusing. Thank you

ktlint check tasks should be cacheable

The ktlint check tasks created by this plugin don't have any output registered, so they are never up to date and cannot be cached by the Gradle build cache.

The report files generated by those tasks should be registered as outputs and the task marked as cacheable.

Other tasks contributed by this plugin might be good candidates for build cache too, I just didn't look at them closely.

Same output file for every task

Currently the output of the all the ktlint*Check task is the same XML file:
image
This means that is not possible to have multiple tasks checking different variants in the same gradle execution (this is really common in CI).

My suggestion is to align the output to the one that Lint is using and generate one file per task:
image

This way is possible to generate multiple reports with a single gradle execution.

I have already fixed this issue locally, if you want I can open a Pull Request.

Turn on android code style

Ktlint since 0.12.0 version added android code style support. This enabled by providing --android option.

Plugin should add flag to extension that will enable this rules.

Add a way to run check for non-JVM projects

Feature request: Could some way be added to check code for other platforms than JVM?

I have a multiplatform module but the kotlin-common and kotlin-javascript code is skipped. Most of the code is kotlin-common, which should be a subset of kotlin-JVM I think.

I'm not sure how hard this is but I'll just suggest it (I'm not really sure how the platform relates to style checks).

Allow to use custom rule sets

Ktlint provides an ability to use custom rulesets. There are two ways to load them:

$ ktlint -R /path/to/custom/rulseset.jar "src/test/**/*.kt"
$ ktlint -R com.github.username:rulseset:master-SNAPSHOT

Plugin should allow to define custom rulesets and apply it when running check/fortmatting tasks.

Publish releases after every PR is merged

This is just a practice that I need to start doing myself.

I need to remember to do this so I don't end up having people wait on me to get things released.

Maybe I can automate this but for now this is just a practice I need to get into the habit of doing.

Allow user to selectively not apply task to check task

Use case is my own.

I'd like to apply this plugin to get the ktlintApplyToIdea and ktlintApplyToIdeaGlobally task without the ktlintCheck task also getting added.

Something like:

ktlint {
    automaticallyAddToCheckTask = false
}

Add task to install git pre-commit-hook

Ktlint supports installing git pre-commit hook, that will check style violations on git commit. Would be nice to add this as a Gradle task to simplify setup for the project.

Name should be: ktlintAddGitPreCommitHook

Plugin fails on missing kotlin-gradle-plugin dependency

Error:Could not find org.jetbrains.kotlin:kotlin-gradle-plugin:1.2-M2.
Searched in the following locations:
    file:/D:/courses/android-studio-ide-171.4220116-windows/android-studio/gradle/m2repository/org/jetbrains/kotlin/kotlin-gradle-plugin/1.2-M2/kotlin-gradle-plugin-1.2-M2.pom
    file:/D:/courses/android-studio-ide-171.4220116-windows/android-studio/gradle/m2repository/org/jetbrains/kotlin/kotlin-gradle-plugin/1.2-M2/kotlin-gradle-plugin-1.2-M2.jar
    https://dl.google.com/dl/android/maven2/org/jetbrains/kotlin/kotlin-gradle-plugin/1.2-M2/kotlin-gradle-plugin-1.2-M2.pom
    https://dl.google.com/dl/android/maven2/org/jetbrains/kotlin/kotlin-gradle-plugin/1.2-M2/kotlin-gradle-plugin-1.2-M2.jar
    https://jcenter.bintray.com/org/jetbrains/kotlin/kotlin-gradle-plugin/1.2-M2/kotlin-gradle-plugin-1.2-M2.pom
    https://jcenter.bintray.com/org/jetbrains/kotlin/kotlin-gradle-plugin/1.2-M2/kotlin-gradle-plugin-1.2-M2.jar
Required by:
    project :

Multidimensional flavors are currently not working properly

Our project has several flavor dimensions (flavorDimensions 'pay', 'country', 'api') but the only ktlint task that works is the one that contains only the single dimension where the .kt files are (in our case app/src/italy/java/.../SomeFile.kt):

> Task :app:ktlintItalyCheck
[DEBUG] Discovered ruleset "standard"
[DEBUG] Discovered reporter "plain"
[DEBUG] Discovered reporter "json"
[DEBUG] Discovered reporter "checkstyle"
[DEBUG] Initializing "checkstyle" reporter with {verbose=true}
[DEBUG] {} loaded from .editorconfig
[DEBUG] Checking /home/rleinardi/Workspace/git/dsa_android/app/src/italy/java/ui/digitalcard/DigitalCardActivity.kt
[DEBUG] Checking /home/rleinardi/Workspace/git/dsa_android/app/src/italy/java/ui/digitalcard/DigitalCardViewModel.kt
[DEBUG] Checking /home/rleinardi/Workspace/git/dsa_android/app/src/italy/java/ui/digitalcard/DigitalCardRepository.kt
[DEBUG] 612ms / 3file(s) / 4error(s)

> Task :app:ktlintNonpayCheck
[DEBUG] Discovered ruleset "standard"
[DEBUG] Discovered reporter "plain"
[DEBUG] Discovered reporter "json"
[DEBUG] Discovered reporter "checkstyle"
[DEBUG] Initializing "checkstyle" reporter with {verbose=true}
[DEBUG] {} loaded from .editorconfig
[DEBUG] 161ms / 0file(s) / 0error(s)

> Task :app:ktlintNonpayItalyCompatCheck
[DEBUG] Discovered ruleset "standard"
[DEBUG] Discovered reporter "plain"
[DEBUG] Discovered reporter "json"
[DEBUG] Discovered reporter "checkstyle"
[DEBUG] Initializing "checkstyle" reporter with {verbose=true}
[DEBUG] {} loaded from .editorconfig
[DEBUG] 143ms / 0file(s) / 0error(s)

> Task :app:ktlintNonpayItalyCompatDebugCheck
[DEBUG] Discovered ruleset "standard"
[DEBUG] Discovered reporter "plain"
[DEBUG] Discovered reporter "json"
[DEBUG] Discovered reporter "checkstyle"
[DEBUG] Initializing "checkstyle" reporter with {verbose=true}
[DEBUG] {} loaded from .editorconfig
[DEBUG] 133ms / 0file(s) / 0error(s)

> Task :app:ktlintNonpayItalyCompatReleaseCheck
[DEBUG] Discovered ruleset "standard"
[DEBUG] Discovered reporter "plain"
[DEBUG] Discovered reporter "json"
[DEBUG] Discovered reporter "checkstyle"
[DEBUG] Initializing "checkstyle" reporter with {verbose=true}
[DEBUG] {} loaded from .editorconfig
[DEBUG] 145ms / 0file(s) / 0error(s)

> Task :app:ktlintNonpayItalyDevCheck
[DEBUG] Discovered ruleset "standard"
[DEBUG] Discovered reporter "plain"
[DEBUG] Discovered reporter "json"
[DEBUG] Discovered reporter "checkstyle"
[DEBUG] Initializing "checkstyle" reporter with {verbose=true}
[DEBUG] {} loaded from .editorconfig
[DEBUG] 137ms / 0file(s) / 0error(s)

> Task :app:ktlintNonpayItalyDevDebugCheck
[DEBUG] Discovered ruleset "standard"
[DEBUG] Discovered reporter "plain"
[DEBUG] Discovered reporter "json"
[DEBUG] Discovered reporter "checkstyle"
[DEBUG] Initializing "checkstyle" reporter with {verbose=true}
[DEBUG] {} loaded from .editorconfig
[DEBUG] 129ms / 0file(s) / 0error(s)

> Task :app:ktlintNonpayItalyDevReleaseCheck
[DEBUG] Discovered ruleset "standard"
[DEBUG] Discovered reporter "plain"
[DEBUG] Discovered reporter "json"
[DEBUG] Discovered reporter "checkstyle"
[DEBUG] Initializing "checkstyle" reporter with {verbose=true}
[DEBUG] {} loaded from .editorconfig
[DEBUG] 125ms / 0file(s) / 0error(s)

The expected result is that all the task that include "Italy" as country flavor dimension will run the check/format verification.

Unable to specify any reporter if ktlint version is bigger than "0.9.x"

There seems to be a bug that prevents you from using a custom reporter when ktlint version is bigger than "0.9.x", eg. "0.10.1".

This is due to comparing strings instead of integers:

private fun isReportAvailable(version: String, availableSinceVersion: String): Boolean {
    val versionsNumbers = version.split('.')
    val reporterVersionNumbers = availableSinceVersion.split('.')
    return versionsNumbers[0] >= reporterVersionNumbers[0] &&
            versionsNumbers[1] >= reporterVersionNumbers[1] &&
            versionsNumbers[2] >= reporterVersionNumbers[2]
}

To reproduce the issue you can use this configuration:

ktlint {
    version = "0.10.1"
    debug = true
    verbose = false
    reporter = "json"
    ignoreFailures = true
}

The output is:

> Task :app:ktlintItalyCheck
[DEBUG] Discovered ruleset "standard"
[DEBUG] Discovered reporter "plain"
[DEBUG] Discovered reporter "json"
[DEBUG] Discovered reporter "checkstyle"
[DEBUG] Initializing "plain" reporter with {verbose=false}
[DEBUG] {} loaded from .editorconfig
[...]

java.lang.NoClassDefFoundError: com/android/build/gradle/AppPlugin

Gradle 4.4.1, Android Gradle Plugin 3.0.1

I'm trying to add the plugin to https://github.com/hzsweers/CatchUp via the plugins block in the top-level build.gradle file. The build fails with the following error:

FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring project ':app'.
> Failed to notify project evaluation listener.
   > Could not resolve all dependencies for configuration ':app:kapt'.
      > A problem occurred configuring project ':bypass'.
         > Failed to notify project evaluation listener.
            > com/android/build/gradle/BaseExtension
   > com/android/build/gradle/BaseExtension

Here's a part of the stacktrace that looks relevant:

Caused by: java.lang.NoClassDefFoundError: com/android/build/gradle/BaseExtension
        at org.jlleitschuh.gradle.ktlint.KtlintPlugin$addKtLintTasksToAndroidKotlinPlugin$1$1.execute(KtlintPlugin.kt:72)
        at org.jlleitschuh.gradle.ktlint.KtlintPlugin$addKtLintTasksToAndroidKotlinPlugin$1$1.execute(KtlintPlugin.kt:26)
        at org.gradle.internal.event.BroadcastDispatch$ActionInvocationHandler.dispatch(BroadcastDispatch.java:91)
        at org.gradle.internal.event.BroadcastDispatch$ActionInvocationHandler.dispatch(BroadcastDispatch.java:80)
        at org.gradle.internal.event.AbstractBroadcastDispatch.dispatch(AbstractBroadcastDispatch.java:42)
        at org.gradle.internal.event.BroadcastDispatch$SingletonDispatch.dispatch(BroadcastDispatch.java:230)
        at org.gradle.internal.event.BroadcastDispatch$SingletonDispatch.dispatch(BroadcastDispatch.java:149)
        at org.gradle.internal.event.AbstractBroadcastDispatch.dispatch(AbstractBroadcastDispatch.java:58)
        ... 153 more
Caused by: java.lang.ClassNotFoundException: com.android.build.gradle.BaseExtension
        ... 161 more

Any special considerations when running the plugin on Android?

Add support for colored output

Ktlint version 0.13.0 introduced colored ouput support:

--color CLI option for colored output (where supported, e.g. --print-ast, default (plain) reporter, etc)

Can't build samples without Android SDK installed

If you don't have the Android SDK installed you will get the following exception below.

We should conditionally check in the settings.gradle.kts file and only include the sample in the project if the Android SDK is installed/configured.

FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring project ':samples:android-app'.
> SDK location not found. Define location with sdk.dir in the local.properties file or with an ANDROID_HOME environment variable.

* Try:
Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Exception is:
org.gradle.api.ProjectConfigurationException: A problem occurred configuring project ':samples:android-app'.
        at org.gradle.configuration.project.LifecycleProjectEvaluator.addConfigurationFailure(LifecycleProjectEvaluator.java:94)
        at org.gradle.configuration.project.LifecycleProjectEvaluator.notifyAfterEvaluate(LifecycleProjectEvaluator.java:89)
        at org.gradle.configuration.project.LifecycleProjectEvaluator.doConfigure(LifecycleProjectEvaluator.java:70)
        at org.gradle.configuration.project.LifecycleProjectEvaluator.access$100(LifecycleProjectEvaluator.java:34)
        at org.gradle.configuration.project.LifecycleProjectEvaluator$ConfigureProject.run(LifecycleProjectEvaluator.java:110)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110)
        at org.gradle.configuration.project.LifecycleProjectEvaluator.evaluate(LifecycleProjectEvaluator.java:50)
        at org.gradle.api.internal.project.DefaultProject.evaluate(DefaultProject.java:667)
        at org.gradle.api.internal.project.DefaultProject.evaluate(DefaultProject.java:136)
        at org.gradle.execution.TaskPathProjectEvaluator.configure(TaskPathProjectEvaluator.java:35)
        at org.gradle.execution.TaskPathProjectEvaluator.configureHierarchy(TaskPathProjectEvaluator.java:62)
        at org.gradle.configuration.DefaultBuildConfigurer.configure(DefaultBuildConfigurer.java:38)
        at org.gradle.initialization.DefaultGradleLauncher$ConfigureBuild.run(DefaultGradleLauncher.java:249)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110)
        at org.gradle.initialization.DefaultGradleLauncher.configureBuild(DefaultGradleLauncher.java:167)
        at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:126)
        at org.gradle.initialization.DefaultGradleLauncher.executeTasks(DefaultGradleLauncher.java:109)
        at org.gradle.internal.invocation.GradleBuildController$1.call(GradleBuildController.java:78)
        at org.gradle.internal.invocation.GradleBuildController$1.call(GradleBuildController.java:75)
        at org.gradle.internal.work.DefaultWorkerLeaseService.withLocks(DefaultWorkerLeaseService.java:152)
        at org.gradle.internal.invocation.GradleBuildController.doBuild(GradleBuildController.java:100)
        at org.gradle.internal.invocation.GradleBuildController.run(GradleBuildController.java:75)
        at org.gradle.tooling.internal.provider.ExecuteBuildActionRunner.run(ExecuteBuildActionRunner.java:28)
        at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
        at org.gradle.tooling.internal.provider.ValidatingBuildActionRunner.run(ValidatingBuildActionRunner.java:32)
        at org.gradle.launcher.exec.RunAsBuildOperationBuildActionRunner$1.run(RunAsBuildOperationBuildActionRunner.java:43)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110)
        at org.gradle.launcher.exec.RunAsBuildOperationBuildActionRunner.run(RunAsBuildOperationBuildActionRunner.java:40)
        at org.gradle.tooling.internal.provider.SubscribableBuildActionRunner.run(SubscribableBuildActionRunner.java:51)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:49)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:32)
        at org.gradle.launcher.exec.BuildTreeScopeBuildActionExecuter.execute(BuildTreeScopeBuildActionExecuter.java:39)
        at org.gradle.launcher.exec.BuildTreeScopeBuildActionExecuter.execute(BuildTreeScopeBuildActionExecuter.java:25)
        at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:80)
        at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:53)
        at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:57)
        at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:32)
        at org.gradle.tooling.internal.provider.GradleThreadBuildActionExecuter.execute(GradleThreadBuildActionExecuter.java:36)
        at org.gradle.tooling.internal.provider.GradleThreadBuildActionExecuter.execute(GradleThreadBuildActionExecuter.java:25)
        at org.gradle.tooling.internal.provider.ParallelismConfigurationBuildActionExecuter.execute(ParallelismConfigurationBuildActionExecuter.java:43)
        at org.gradle.tooling.internal.provider.ParallelismConfigurationBuildActionExecuter.execute(ParallelismConfigurationBuildActionExecuter.java:29)
        at org.gradle.tooling.internal.provider.StartParamsValidatingActionExecuter.execute(StartParamsValidatingActionExecuter.java:64)
        at org.gradle.tooling.internal.provider.StartParamsValidatingActionExecuter.execute(StartParamsValidatingActionExecuter.java:29)
        at org.gradle.tooling.internal.provider.SessionFailureReportingActionExecuter.execute(SessionFailureReportingActionExecuter.java:59)
        at org.gradle.tooling.internal.provider.SessionFailureReportingActionExecuter.execute(SessionFailureReportingActionExecuter.java:44)
        at org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:45)
        at org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:30)
        at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:67)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
        at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:37)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
        at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
        at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:74)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:72)
        at org.gradle.util.Swapper.swap(Swapper.java:38)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:72)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
        at org.gradle.launcher.daemon.server.exec.LogAndCheckHealth.execute(LogAndCheckHealth.java:55)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
        at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:62)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
        at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:82)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
        at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50)
        at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:295)
        at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
        at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
        at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
Caused by: java.lang.RuntimeException: SDK location not found. Define location with sdk.dir in the local.properties file or with an ANDROID_HOME environment variable.
        at com.android.build.gradle.internal.SdkHandler.getAndCheckSdkFolder(SdkHandler.java:218)
        at com.android.build.gradle.internal.SdkHandler.getSdkLoader(SdkHandler.java:228)
        at com.android.build.gradle.internal.SdkHandler.initTarget(SdkHandler.java:138)
        at com.android.build.gradle.BasePlugin.ensureTargetSetup(BasePlugin.java:718)
        at com.android.build.gradle.BasePlugin.createAndroidTasks(BasePlugin.java:600)
        at com.android.build.gradle.BasePlugin.lambda$null$3(BasePlugin.java:555)
        at com.android.builder.profile.ThreadRecorder.record(ThreadRecorder.java:81)
        at com.android.build.gradle.BasePlugin.lambda$createTasks$4(BasePlugin.java:551)
        at org.gradle.internal.event.BroadcastDispatch$ActionInvocationHandler.dispatch(BroadcastDispatch.java:91)
        at org.gradle.internal.event.BroadcastDispatch$ActionInvocationHandler.dispatch(BroadcastDispatch.java:80)
        at org.gradle.internal.event.AbstractBroadcastDispatch.dispatch(AbstractBroadcastDispatch.java:42)
        at org.gradle.internal.event.BroadcastDispatch$SingletonDispatch.dispatch(BroadcastDispatch.java:230)
        at org.gradle.internal.event.BroadcastDispatch$SingletonDispatch.dispatch(BroadcastDispatch.java:149)
        at org.gradle.internal.event.AbstractBroadcastDispatch.dispatch(AbstractBroadcastDispatch.java:58)
        at org.gradle.internal.event.BroadcastDispatch$CompositeDispatch.dispatch(BroadcastDispatch.java:324)
        at org.gradle.internal.event.BroadcastDispatch$CompositeDispatch.dispatch(BroadcastDispatch.java:234)
        at org.gradle.internal.event.ListenerBroadcast.dispatch(ListenerBroadcast.java:140)
        at org.gradle.internal.event.ListenerBroadcast.dispatch(ListenerBroadcast.java:37)
        at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
        at com.sun.proxy.$Proxy48.afterEvaluate(Unknown Source)
        at org.gradle.configuration.project.LifecycleProjectEvaluator.notifyAfterEvaluate(LifecycleProjectEvaluator.java:76)
        ... 81 more


* Get more help at https://help.gradle.org

BUILD FAILED in 0s

Does not work with Gradle version 4

org/gradle/script/lang/kotlin/KotlinDependencyHandler has been renamed to DependencyHandlerScope which means that this plugin breaks.

Moving forward it may make sense to write an adapter or use the java API which may be a bit more stable across releases.

Format does not actually seem to format?

So the tasks are in, they are reporting the klint error, but as far as I understand it
should not the format task format the code in such a way that the lint error dissapears?

Cause for instance i now get RANDOMFILE.kt:10:1: Exceeded max line length (100) (max-line-length)

I expect it to look for a pattern where it should divide it, or is there some of these klint errors
that the formatter does not support?

Tests are missing

This plugin needs some tests, so it will be easier to add a new features and check already existing behaviour.

@JLLeitschuh you can assign it to me, will try to add them when I will have spare time.

Add support for apply-to-idea-project formating command

I added a plugin to the project.
Now every developer in the team must manually run this ktlint command
./ktlint --apply-to-idea-project --android

This is fine, but I wonder can it be achieved without separatley downloading (and keeping) ktlint binaries? I would be nice to provide ability to configure IDE out of the box.

hmm Maybe plugin could somehow link ./ktlint command to project root or add new gradle task that would allow passing parameters to ktlint script ./gradlew ktlint ๐Ÿค”

(we could, of course, add new grade task but I feel this would not be flexible enough if new ktlint parameters will be added in future)

ktlintFormat and ktlintCheck are not working.

I'm trying to apply the plugin to an Android project, but ktlintFormat and ktlinCheck are not working.

For example, let's take this simple Kotlin file that contains an activity and it's not well formatted

package com.gianfranco.stormy

import android.os.Bundle
import android.support.v7.app.AppCompatActivity

    class MainActivity : AppCompatActivity() {
            override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(     savedInstanceState)

                setContentView(R.layout.activity_main)
    }
}

When I run ./gradlew ktlintCheck or ./gradlew ktlintFormat, nothing happens. The output is BUILD SUCCESSFUL.

The build.gradle for the project can be found here

I'm using Gradle 4.8.1 and AGP 3.2.0-beta03.

Get rid of deprecated Gradle features

Hi,
ktlint version "3.0.1"
gradle 4.5.1

STR:
run any default check (e.g. :ktlintMainCheck)
Actual result: warning appears:

Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0.
See https://docs.gradle.org/4.5.1/userguide/command_line_interface.html#sec:command_line_warnings

Expected result: no warning

Gradle: how to run lint automatically with `check`?

I don't know if this is a bug or just my ignorance regarding Gradle, but I can't seem to do:

test.dependsOn ktlintCheck

I get this message:

A problem occurred evaluating root project 'lintsetup'.
  > Could not get unknown property 'ktlintCheck' for root project 'lintsetup' of type org.gradle.api.Project.

I created an otherwise clean project, which has a build.gradle like this:

buildscript {
    ext.kotlin_version = '1.2.21'

    repositories {
        mavenCentral()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

plugins {
    id "org.jlleitschuh.gradle.ktlint" version "3.0.0"
}

group 'lintsetup'
version '1.0-SNAPSHOT'

apply plugin: 'kotlin-platform-jvm'

repositories {
    mavenCentral()
}

dependencies {
    compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
    testCompile "junit:junit:4.12"
    testCompile "org.jetbrains.kotlin:kotlin-test-junit:$kotlin_version"
    testCompile "org.jetbrains.kotlin:kotlin-test:$kotlin_version"
}

test.dependsOn ktlintCheck

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.