Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add baseline support #302

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 8 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,14 +101,14 @@ plugins {
- Incremental build support and fast parallelization with Gradle Worker API
- Configures from `.editorconfig` when available
- Configurable reporters
- Baseline file _(note: you must generate your baseline file with [`ktlint`](https://github.com/pinterest/ktlint))_

### Tasks

When your project uses one of the supported Kotlin Gradle plugins, Kotlinter adds these tasks:

`formatKotlin`: format Kotlin source code according to `ktlint` rules or warn when auto-format not possible.

`lintKotlin`: report Kotlin lint errors and by default fail the build.
- `formatKotlin`: format Kotlin source code according to `ktlint` rules or warn when auto-format not possible.
- `lintKotlin`: report Kotlin lint errors and by default fail the build.

Also `check` becomes dependent on `lintKotlin`.

Expand Down Expand Up @@ -157,6 +157,7 @@ kotlinter {
reporters = arrayOf("checkstyle", "plain")
experimentalRules = false
disabledRules = emptyArray()
baseline = File("config/baseline.xml")
}
```

Expand All @@ -171,6 +172,7 @@ kotlinter {
reporters = ['checkstyle', 'plain']
experimentalRules = false
disabledRules = []
baseline = "config/baseline.xml"
}
```

Expand All @@ -182,12 +184,14 @@ Reporters behave as described at: https://github.com/pinterest/ktlint

The `experimentalRules` property enables rules which are part of ktlint's experimental rule set.

The `disabledRules` property can includes an array of rule ids you wish to disable. For example to allow wildcard imports:
The `disabledRules` property can include an array of rule ids you wish to disable. For example to allow wildcard imports:
```groovy
disabledRules = ["no-wildcard-imports"]
```
You must prefix rule ids not part of the standard rule set with `<rule-set-id>:<rule-id>`. For example `experimental:annotation`.

The `baseline` property is a path to a baseline file relative to the module being configured. The baseline file needs to be generated via [`ktlint`](https://github.com/pinterest/ktlint)

### Editorconfig

Kotlinter will configure itself using an `.editorconfig` file if one is present.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ open class KotlinterExtension {
const val DEFAULT_EXPERIMENTAL_RULES = false
val DEFAULT_REPORTER = ReporterType.checkstyle.name
val DEFAULT_DISABLED_RULES = emptyArray<String>()
val DEFAULT_BASELINE: String? = null
}

var ignoreFailures = DEFAULT_IGNORE_FAILURES
Expand All @@ -17,4 +18,6 @@ open class KotlinterExtension {
var experimentalRules = DEFAULT_EXPERIMENTAL_RULES

var disabledRules = DEFAULT_DISABLED_RULES

var baseline = DEFAULT_BASELINE
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package org.jmailen.gradle.kotlinter
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.Task
import org.gradle.api.file.RegularFile
import org.gradle.api.tasks.TaskProvider
import org.jmailen.gradle.kotlinter.pluginapplier.AndroidSourceSetApplier
import org.jmailen.gradle.kotlinter.pluginapplier.KotlinSourceSetApplier
Expand Down Expand Up @@ -48,6 +49,7 @@ class KotlinterPlugin : Plugin<Project> {
)
lintTask.experimentalRules.set(provider { kotlinterExtension.experimentalRules })
lintTask.disabledRules.set(provider { kotlinterExtension.disabledRules.toList() })
lintTask.baseline = kotlinterExtension.baseline?.let { File(it) }
}
lintKotlin.configure { lintTask ->
lintTask.dependsOn(lintTaskPerSourceSet)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package org.jmailen.gradle.kotlinter.support

import java.io.File
import java.io.Serializable

data class KtLintParams(
val experimentalRules: Boolean,
val disabledRules: List<String>,
val baselineFile: File?
) : Serializable
10 changes: 10 additions & 0 deletions src/main/kotlin/org/jmailen/gradle/kotlinter/support/LintErrors.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package org.jmailen.gradle.kotlinter.support

import com.pinterest.ktlint.core.LintError

internal fun List<LintError>.doesNotContain(error: LintError): Boolean = none { it.isSameAs(error) }

private fun LintError.isSameAs(lintError: LintError) =
col == lintError.col &&
line == lintError.line &&
ruleId == lintError.ruleId
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,7 @@ import org.gradle.api.model.ObjectFactory
import org.gradle.api.provider.ListProperty
import org.gradle.api.provider.MapProperty
import org.gradle.api.provider.Property
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.InputFiles
import org.gradle.api.tasks.Internal
import org.gradle.api.tasks.PathSensitive
import org.gradle.api.tasks.PathSensitivity
import org.gradle.api.tasks.SourceTask
import org.gradle.api.tasks.*
import org.gradle.internal.exceptions.MultiCauseException
import org.gradle.work.FileChange
import org.gradle.work.Incremental
Expand All @@ -20,6 +15,7 @@ import org.jmailen.gradle.kotlinter.KotlinterExtension.Companion.DEFAULT_DISABLE
import org.jmailen.gradle.kotlinter.KotlinterExtension.Companion.DEFAULT_EXPERIMENTAL_RULES
import org.jmailen.gradle.kotlinter.support.KtLintParams
import org.jmailen.gradle.kotlinter.support.findApplicableEditorConfigFiles
import java.io.File

abstract class ConfigurableKtLintTask(
projectLayout: ProjectLayout,
Expand All @@ -32,6 +28,11 @@ abstract class ConfigurableKtLintTask(
@Input
val disabledRules: ListProperty<String> = objectFactory.listProperty(default = DEFAULT_DISABLED_RULES.toList())

@get:InputFile
@get:PathSensitive(PathSensitivity.RELATIVE)
@Optional
var baseline: File? = null

@get:InputFiles
@get:PathSensitive(PathSensitivity.RELATIVE)
@get:Incremental
Expand All @@ -43,6 +44,7 @@ abstract class ConfigurableKtLintTask(
protected fun getKtLintParams(): KtLintParams = KtLintParams(
experimentalRules = experimentalRules.get(),
disabledRules = disabledRules.get(),
baselineFile = baseline?.let { project.file(it) }
)

protected fun getChangedEditorconfigFiles(inputChanges: InputChanges) =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,13 @@ import com.pinterest.ktlint.core.KtLint
import com.pinterest.ktlint.core.LintError
import com.pinterest.ktlint.core.Reporter
import com.pinterest.ktlint.core.RuleProvider
import com.pinterest.ktlint.core.api.loadBaseline
import org.gradle.api.logging.Logger
import org.gradle.api.logging.Logging
import org.gradle.internal.logging.slf4j.DefaultContextAwareTaskLogger
import org.gradle.workers.WorkAction
import org.jmailen.gradle.kotlinter.support.KotlinterError
import org.jmailen.gradle.kotlinter.support.KtLintParams
import org.jmailen.gradle.kotlinter.support.LintFailure
import org.jmailen.gradle.kotlinter.support.defaultRuleSetProviders
import org.jmailen.gradle.kotlinter.support.*
import org.jmailen.gradle.kotlinter.support.editorConfigOverride
import org.jmailen.gradle.kotlinter.support.reporterFor
import org.jmailen.gradle.kotlinter.support.reporterPathFor
import org.jmailen.gradle.kotlinter.support.resetEditorconfigCacheIfNeeded
import org.jmailen.gradle.kotlinter.support.resolveRuleProviders
import org.jmailen.gradle.kotlinter.tasks.LintTask
Expand All @@ -30,6 +26,13 @@ abstract class LintWorkerAction : WorkAction<LintWorkerParameters> {
private val name: String = parameters.name.get()
private val ktLintParams: KtLintParams = parameters.ktLintParams.get()

private val baselineLintErrorsByFile by lazy {
ktLintParams.baselineFile?.let { baselineFile ->
loadBaseline(baselineFile.absolutePath)
.lintErrorsPerFile
} ?: emptyMap()
}

override fun execute() {
resetEditorconfigCacheIfNeeded(
changedEditorconfigFiles = parameters.changedEditorconfigFiles,
Expand All @@ -52,14 +55,22 @@ abstract class LintWorkerAction : WorkAction<LintWorkerParameters> {
null
}
}
val relativeFilePath = file.path.removePrefix(projectDirectory.path + "/")
val fileBaselineErrors = baselineLintErrorsByFile[relativeFilePath] ?: emptyList()

lintFunc?.invoke(file, ruleSets) { error ->
hasError = true
reporters.onEach { reporter ->
// some reporters want relative paths, some want absolute
val filePath = reporterPathFor(reporter, file, projectDirectory)
reporter.onLintError(filePath, error, false)
if (fileBaselineErrors.doesNotContain(error)) {
hasError = true
reporters.onEach { reporter ->
// some reporters want relative paths, some want absolute
val filePath = reporterPathFor(reporter, file, projectDirectory)
reporter.onLintError(filePath, error, false)
}

logger.quiet("${file.path}:${error.line}:${error.col}: Lint error > [${error.ruleId}] ${error.detail}")
} else {
logger.debug("${file.path}:${error.line}:${error.col}: [Found in baseline; ignoring] Lint error > [${error.ruleId}] ${error.detail}")
}
logger.quiet("${file.path}:${error.line}:${error.col}: Lint error > [${error.ruleId}] ${error.detail}")
}
reporters.onEach { it.after(relativePath) }
}
Expand Down
4 changes: 4 additions & 0 deletions test-project/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,7 @@ plugins {
kotlin("jvm") version "1.7.22"
id("org.jmailen.kotlinter")
}

kotlinter {
baseline = "config/baseline.xml"
}
6 changes: 6 additions & 0 deletions test-project/config/baseline.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<baseline version="1.0">
<file name="src/main/kotlin/org/jmailen/gradle/kotlinter/sample/EmptyClassBodyClassExcludedByBaseline.kt">
<error line="3" column="45" source="no-empty-class-body" />
</file>
</baseline>
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
package org.jmailen.gradle.kotlinter.sample

class EmptyClassBodyClassExcludedByBaseline {
}