From e352ba8bf4b2f01afc9083ec83eb2bca02aacae2 Mon Sep 17 00:00:00 2001 From: wakingrufus Date: Mon, 23 Oct 2023 07:08:40 -0500 Subject: [PATCH] Drop support for older versions of gradle and ktlint increase minimum supported gradle version to 7.4.1 increase minimum supported ktlint version to 0.47.1 support ktlint 1.0.1 remove retry plugin as it is included in enterprise plugin now upgrade project gradle update code to utilize kotlin-dsl fix ktlint errors upgrade build to gradle 8 and add toolchain resolver update reporter samples to ktlint 1.0.1 --- CHANGELOG.md | 1 + README.md | 5 +- gradle/wrapper/gradle-wrapper.properties | 4 +- plugin/build.gradle.kts | 60 +--------- plugin/gradle/libs.versions.toml | 6 +- .../gradle/wrapper/gradle-wrapper.properties | 4 +- plugin/settings.gradle.kts | 6 +- .../reporter/Ktlint34ReporterProvider.kt | 13 --- .../reporter/SerializableReporterProvider.kt | 38 ------- .../SerializableReportersProviderLoader.kt | 77 ------------- .../SerializableReporterProviderTest.kt | 45 -------- .../ktlint/reporter/Ktlint41Reporter.kt | 30 ----- .../reporter/Ktlint41ReporterProvider.kt | 13 --- .../gradle/ktlint/worker/BaselineLoader45.kt | 9 -- .../ktlint/worker/KtLintInvocation45.kt | 80 ------------- .../gradle/ktlint/worker/BaselineLoader46.kt | 9 -- .../ktlint/worker/KtLintInvocation46.kt | 104 ----------------- .../ktlint/reporter/LegacyKtlintReporter.kt} | 2 +- .../reporter/LegacyKtlintReporterProvider.kt | 16 +++ .../reporter/ReportersProviderLoader.kt | 22 ++-- .../gradle/ktlint/Configurations.kt | 79 +++---------- .../org/jlleitschuh/gradle/ktlint/GitHook.kt | 20 ++-- .../gradle/ktlint/KtLintCompatibility.kt | 21 +--- .../gradle/ktlint/KtlintApplyToIdeaTask.kt | 76 ------------- .../gradle/ktlint/KtlintBasePlugin.kt | 6 +- .../gradle/ktlint/KtlintExtension.kt | 6 +- .../gradle/ktlint/KtlintIdeaPlugin.kt | 44 -------- .../jlleitschuh/gradle/ktlint/KtlintPlugin.kt | 19 ++-- .../jlleitschuh/gradle/ktlint/PluginUtil.kt | 11 +- .../jlleitschuh/gradle/ktlint/TaskCreation.kt | 33 +++--- .../ktlint/android/AndroidPluginsApplier.kt | 10 +- .../ktlint/tasks/BaseKtLintCheckTask.kt | 50 +++------ .../ktlint/tasks/GenerateBaselineTask.kt | 25 ++--- .../ktlint/tasks/GenerateReportsTask.kt | 55 ++++----- .../gradle/ktlint/tasks/LoadReportersTask.kt | 21 ++-- .../gradle/ktlint/worker/KtLintWorkAction.kt | 35 +----- .../gradle/ktlint/ConfigurationCacheTest.kt | 12 +- .../gradle/ktlint/DisabledRulesTest.kt | 106 ++++++------------ .../ktlint/KtLintSupportedVersionsTest.kt | 62 +--------- .../ktlint/KtlintBaselineSupportTest.kt | 80 +++---------- .../gradle/ktlint/KtlintIdeaPluginTest.kt | 54 --------- .../gradle/ktlint/KtlintPluginTest.kt | 98 ++-------------- .../gradle/ktlint/KtlintPluginVersionTest.kt | 8 +- .../gradle/ktlint/ReportersTest.kt | 27 ----- .../gradle/ktlint/UnsupportedGradleTest.kt | 2 +- .../gradle/ktlint/testdsl/TestAnnotations.kt | 11 +- .../gradle/ktlint/testdsl/TestDsl.kt | 6 +- .../ktlint/android/ItemDetailActivity.kt | 5 +- .../ktlint/android/ItemDetailFragment.kt | 3 +- .../gradle/ktlint/android/ItemListActivity.kt | 33 +++--- .../ktlint/android/dummy/DummyContent.kt | 1 - .../ktlint/android/AlternativeSample.kt | 4 +- .../gradle/ktlint/sample/js/Main.kt | 8 +- .../sample/mppandroid/LocationProvider.kt | 4 +- .../ktlint/sample/mpp/CommonInterface.kt | 1 + .../kotlin-reporter-creating/build.gradle.kts | 6 +- .../gradle/ktlint/sample/CsvReporter.kt | 17 +-- .../ktlint/sample/CsvReporterProvider.kt | 10 +- ....cli.reporter.core.api.ReporterProviderV2} | 0 .../kotlin-reporter-using/build.gradle.kts | 9 +- .../kotlin-rulesets-creating/build.gradle.kts | 4 + .../sample/kotlin/CustomRuleSetProvider.kt | 1 - .../gradle/ktlint/sample/kotlin/NoVarRule.kt | 7 +- settings.gradle.kts | 2 +- 64 files changed, 310 insertions(+), 1326 deletions(-) delete mode 100644 plugin/src/adapter34/kotlin/org/jlleitschuh/gradle/ktlint/reporter/Ktlint34ReporterProvider.kt delete mode 100644 plugin/src/adapter34/kotlin/org/jlleitschuh/gradle/ktlint/reporter/SerializableReporterProvider.kt delete mode 100644 plugin/src/adapter34/kotlin/org/jlleitschuh/gradle/ktlint/reporter/SerializableReportersProviderLoader.kt delete mode 100644 plugin/src/adapter34Test/kotlin/org/jlleitschuh/gradle/ktlint/reporter/SerializableReporterProviderTest.kt delete mode 100644 plugin/src/adapter41/kotlin/org/jlleitschuh/gradle/ktlint/reporter/Ktlint41Reporter.kt delete mode 100644 plugin/src/adapter41/kotlin/org/jlleitschuh/gradle/ktlint/reporter/Ktlint41ReporterProvider.kt delete mode 100644 plugin/src/adapter45/kotlin/org/jlleitschuh/gradle/ktlint/worker/BaselineLoader45.kt delete mode 100644 plugin/src/adapter45/kotlin/org/jlleitschuh/gradle/ktlint/worker/KtLintInvocation45.kt delete mode 100644 plugin/src/adapter46/kotlin/org/jlleitschuh/gradle/ktlint/worker/BaselineLoader46.kt delete mode 100644 plugin/src/adapter46/kotlin/org/jlleitschuh/gradle/ktlint/worker/KtLintInvocation46.kt rename plugin/src/{adapter34/kotlin/org/jlleitschuh/gradle/ktlint/reporter/Ktlint34Reporter.kt => adapter47/kotlin/org/jlleitschuh/gradle/ktlint/reporter/LegacyKtlintReporter.kt} (89%) create mode 100644 plugin/src/adapter47/kotlin/org/jlleitschuh/gradle/ktlint/reporter/LegacyKtlintReporterProvider.kt rename plugin/src/{adapter41 => adapter47}/kotlin/org/jlleitschuh/gradle/ktlint/reporter/ReportersProviderLoader.kt (78%) delete mode 100644 plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/KtlintApplyToIdeaTask.kt delete mode 100644 plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/KtlintIdeaPlugin.kt delete mode 100644 plugin/src/test/kotlin/org/jlleitschuh/gradle/ktlint/KtlintIdeaPluginTest.kt rename samples/kotlin-reporter-creating/src/main/resources/META-INF/services/{com.pinterest.ktlint.core.ReporterProvider => com.pinterest.ktlint.cli.reporter.core.api.ReporterProviderV2} (100%) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7d37ef6e..debe480d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/). - update latest version text file manually [#716](https://github.com/JLLeitschuh/ktlint-gradle/pull/716) - Fix configuration cache for relative paths [#722](https://github.com/JLLeitschuh/ktlint-gradle/pull/722) +- Drop support for Gradle 6 and ktlint < 0.47.1 [#720](https://github.com/JLLeitschuh/ktlint-gradle/pull/720) ## [11.6.1] - 2023-10-10 diff --git a/README.md b/README.md index be1fcefd..e71c1137 100644 --- a/README.md +++ b/README.md @@ -64,12 +64,11 @@ open a [new issue](https://github.com/JLLeitschuh/ktlint-gradle/issues/new). 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](https://www.gradle.org) version: `6.8` +Minimal supported [Gradle](https://www.gradle.org) version: `7.4` Minimal supported [Kotlin](https://kotlinlang.org) version: `1.4` -Minimal supported [ktlint](https://github.com/pinterest/ktlint) version: `0.34.0` -(additionally excluding `0.37.0` on Windows OS and `0.38.0`, `0.43.0`, `0.43.1` on all OS types) +Minimal supported [ktlint](https://github.com/pinterest/ktlint) version: `0.47.1` ### Ktlint plugin diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 59250647..5b5c106f 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionSha256Sum=b586e04868a22fd817c8971330fec37e298f3242eb85c374181b12d637f80302 -distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.3-bin.zip +distributionSha256Sum=3e1af3ae886920c3ac87f7a91f816c0c7c436f276a6eefdb3da152100fef72ae +distributionUrl=https\://services.gradle.org/distributions/gradle-8.4-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/plugin/build.gradle.kts b/plugin/build.gradle.kts index f994340f..b9084835 100644 --- a/plugin/build.gradle.kts +++ b/plugin/build.gradle.kts @@ -1,19 +1,18 @@ import com.github.jengelman.gradle.plugins.shadow.tasks.ConfigureShadowRelocation import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar +import com.gradle.enterprise.gradleplugin.testretry.retry import org.gradle.api.tasks.testing.logging.TestExceptionFormat import org.gradle.api.tasks.testing.logging.TestLogEvent import org.jetbrains.kotlin.gradle.tasks.KotlinCompile import org.jetbrains.kotlin.util.prefixIfNot plugins { - kotlin("jvm") id("com.gradle.plugin-publish") - `java-gradle-plugin` + `kotlin-dsl` `maven-publish` id("org.jlleitschuh.gradle.ktlint") id("com.github.johnrengelman.shadow") id("com.github.breadmoirai.github-release") - id("org.gradle.test-retry") } val pluginGroup = "org.jlleitschuh.gradle" @@ -60,22 +59,6 @@ configurations["testImplementation"].extendsFrom(shadowImplementation) sourceSets { val adapter by creating { } - val adapter34 by creating { - compileClasspath += adapter.output - } - val adapter34Test by creating { - compileClasspath += adapter.output + adapter34.output - runtimeClasspath += adapter.output + adapter34.output - } - val adapter41 by creating { - compileClasspath += adapter.output - } - val adapter45 by creating { - compileClasspath += adapter.output - } - val adapter46 by creating { - compileClasspath += adapter.output - } val adapter47 by creating { compileClasspath += adapter.output } @@ -93,10 +76,6 @@ sourceSets { } val adapters = listOf( adapter, - adapter34, - adapter41, - adapter45, - adapter46, adapter47, adapter48, adapter49, @@ -118,10 +97,6 @@ sourceSets { } val adapterSources = listOf( sourceSets.named("adapter"), - sourceSets.named("adapter34"), - sourceSets.named("adapter41"), - sourceSets.named("adapter45"), - sourceSets.named("adapter46"), sourceSets.named("adapter47"), sourceSets.named("adapter48"), sourceSets.named("adapter49"), @@ -132,24 +107,11 @@ tasks.named("shadowJar") { this.from(adapterSources.map { sourceSet -> sourceSet.map { it.output.classesDirs } }) } -val test34Task = tasks.register("test34") { - classpath = sourceSets.named("adapter34Test").get().runtimeClasspath - testClassesDirs = sourceSets.named("adapter34Test").get().output.classesDirs -} -tasks.named("test") { - dependsOn(test34Task) -} - dependencies { - compileOnly(gradleApi()) add("adapterCompileOnly", "com.pinterest.ktlint:ktlint-core:0.34.0") add("adapterImplementation", libs.commons.io) add("adapterImplementation", libs.semver) - add("adapter34Implementation", kotlin("reflect")) - add("adapter34CompileOnly", "com.pinterest.ktlint:ktlint-core:0.34.0") - add("adapter41CompileOnly", "com.pinterest.ktlint:ktlint-core:0.41.0") - add("adapter45CompileOnly", "com.pinterest.ktlint:ktlint-core:0.45.2") - add("adapter46CompileOnly", "com.pinterest.ktlint:ktlint-core:0.46.1") + add("adapter47CompileOnly", "com.pinterest.ktlint:ktlint-core:0.47.1") add("adapter48CompileOnly", "com.pinterest.ktlint:ktlint-core:0.48.2") @@ -184,19 +146,11 @@ dependencies { * https://github.com/JLLeitschuh/ktlint-gradle/issues/9 */ - testImplementation(gradleTestKit()) testImplementation(libs.junit.jupiter) testImplementation(libs.assertj.core) testImplementation(libs.kotlin.reflect) testImplementation(libs.ktlint.core) testImplementation(libs.archunit.junit5) - - add("adapter34TestImplementation", "com.pinterest.ktlint:ktlint-core:0.34.0") - add("adapter34TestImplementation", libs.commons.io) - add("adapter34TestImplementation", gradleTestKit()) - add("adapter34TestImplementation", libs.junit.jupiter) - add("adapter34TestImplementation", libs.assertj.core) - add("adapter34TestImplementation", libs.kotlin.reflect) } kotlin { @@ -212,11 +166,11 @@ kotlin { } // Test tasks loods plugin from local maven repository -tasks.named("test").configure { +tasks.named("test") { dependsOn("publishToMavenLocal") } -tasks.withType().configureEach { +tasks.withType { useJUnitPlatform() maxParallelForks = (Runtime.getRuntime().availableProcessors() / 2).takeIf { it > 0 } ?: 1 doFirst { @@ -224,7 +178,6 @@ tasks.withType().configureEach { } testLogging { events( - TestLogEvent.STARTED, TestLogEvent.FAILED, TestLogEvent.PASSED, TestLogEvent.SKIPPED @@ -392,9 +345,6 @@ pluginBundle { "ktlintPlugin" { displayName = "Ktlint Gradle Plugin" } - "ktlintIdeaPlugin" { - displayName = "Ktlint Gradle IntelliJ Configuration Plugin" - } } } diff --git a/plugin/gradle/libs.versions.toml b/plugin/gradle/libs.versions.toml index ee855385..878e46f8 100644 --- a/plugin/gradle/libs.versions.toml +++ b/plugin/gradle/libs.versions.toml @@ -1,12 +1,12 @@ [versions] kotlin = "1.5.31" -ktlint = "0.45.2" # last version prior to API changes. we can increase this more once we drop support for the old API. +ktlint = "0.47.1" # last version prior to API changes. we can increase this more once we drop support for the old API. androidPlugin = "4.1.0" semver = "1.1.1" jgit = "5.6.0.201912101111-r" sl4fj = "1.7.30" -gradleWrapper = "7.3.3" -gradleWrapperSha = "b586e04868a22fd817c8971330fec37e298f3242eb85c374181b12d637f80302" +gradleWrapper = "8.4" +gradleWrapperSha = "3e1af3ae886920c3ac87f7a91f816c0c7c436f276a6eefdb3da152100fef72ae" junit5 = "5.5.2" assertJ = "3.11.1" commonsIo = "2.8.0" diff --git a/plugin/gradle/wrapper/gradle-wrapper.properties b/plugin/gradle/wrapper/gradle-wrapper.properties index 59250647..5b5c106f 100644 --- a/plugin/gradle/wrapper/gradle-wrapper.properties +++ b/plugin/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionSha256Sum=b586e04868a22fd817c8971330fec37e298f3242eb85c374181b12d637f80302 -distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.3-bin.zip +distributionSha256Sum=3e1af3ae886920c3ac87f7a91f816c0c7c436f276a6eefdb3da152100fef72ae +distributionUrl=https\://services.gradle.org/distributions/gradle-8.4-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/plugin/settings.gradle.kts b/plugin/settings.gradle.kts index 8325a104..653cff13 100644 --- a/plugin/settings.gradle.kts +++ b/plugin/settings.gradle.kts @@ -2,20 +2,18 @@ pluginManagement { val latestRelease = file("VERSION_LATEST_RELEASE.txt").readText().trim() plugins { id("org.jlleitschuh.gradle.ktlint") version latestRelease - id("org.jetbrains.kotlin.jvm") version "1.9.0" + id("org.jetbrains.kotlin.jvm") version "1.9.10" id("com.gradle.plugin-publish") version "0.15.0" `java-gradle-plugin` `maven-publish` id("com.github.johnrengelman.shadow") version "7.0.0" id("com.github.breadmoirai.github-release") version "2.3.7" - id("org.gradle.test-retry") version "1.3.1" } } -enableFeaturePreview("VERSION_CATALOGS") - plugins { `gradle-enterprise` + id("org.gradle.toolchains.foojay-resolver-convention") version "0.7.0" } gradleEnterprise { diff --git a/plugin/src/adapter34/kotlin/org/jlleitschuh/gradle/ktlint/reporter/Ktlint34ReporterProvider.kt b/plugin/src/adapter34/kotlin/org/jlleitschuh/gradle/ktlint/reporter/Ktlint34ReporterProvider.kt deleted file mode 100644 index 7e0470e1..00000000 --- a/plugin/src/adapter34/kotlin/org/jlleitschuh/gradle/ktlint/reporter/Ktlint34ReporterProvider.kt +++ /dev/null @@ -1,13 +0,0 @@ -package org.jlleitschuh.gradle.ktlint.reporter - -import com.pinterest.ktlint.core.ReporterProvider -import java.io.PrintStream - -class Ktlint34ReporterProvider(val reporterProvider: ReporterProvider) : GenericReporterProvider { - override fun get(outputStream: PrintStream, opt: Map): Ktlint34Reporter { - return Ktlint34Reporter(reporterProvider.get(outputStream, opt)) - } - - override val id: String - get() = reporterProvider.id -} diff --git a/plugin/src/adapter34/kotlin/org/jlleitschuh/gradle/ktlint/reporter/SerializableReporterProvider.kt b/plugin/src/adapter34/kotlin/org/jlleitschuh/gradle/ktlint/reporter/SerializableReporterProvider.kt deleted file mode 100644 index eac809ee..00000000 --- a/plugin/src/adapter34/kotlin/org/jlleitschuh/gradle/ktlint/reporter/SerializableReporterProvider.kt +++ /dev/null @@ -1,38 +0,0 @@ -package org.jlleitschuh.gradle.ktlint.reporter - -import com.pinterest.ktlint.core.ReporterProvider -import java.io.IOException -import java.io.ObjectInputStream -import java.io.ObjectOutputStream -import java.io.Serializable -import kotlin.reflect.jvm.jvmName - -/** - * Special wrapper around [ReporterProvider] allowing to serialize/deserialize it into file. - * - * Should be removed once KtLint will add interface implementation into [ReporterProvider]. - */ -class SerializableReporterProvider( - reporterProvider: ReporterProvider -) : Serializable { - @Transient - var reporterProvider: ReporterProvider = reporterProvider - private set - - @Throws(IOException::class) - private fun writeObject(out: ObjectOutputStream) { - out.writeUTF(reporterProvider::class.jvmName) - } - - @Throws(IOException::class, ClassNotFoundException::class) - private fun readObject(oin: ObjectInputStream) { - val reporterProviderClassName = oin.readUTF() - val classLoader = this.javaClass.classLoader - val reporterProviderClass = classLoader.loadClass(reporterProviderClassName) - reporterProvider = reporterProviderClass.newInstance() as ReporterProvider - } - - companion object { - private const val serialVersionUID: Long = 2012021L - } -} diff --git a/plugin/src/adapter34/kotlin/org/jlleitschuh/gradle/ktlint/reporter/SerializableReportersProviderLoader.kt b/plugin/src/adapter34/kotlin/org/jlleitschuh/gradle/ktlint/reporter/SerializableReportersProviderLoader.kt deleted file mode 100644 index 63eb64d8..00000000 --- a/plugin/src/adapter34/kotlin/org/jlleitschuh/gradle/ktlint/reporter/SerializableReportersProviderLoader.kt +++ /dev/null @@ -1,77 +0,0 @@ -package org.jlleitschuh.gradle.ktlint.reporter - -import com.pinterest.ktlint.core.Reporter -import com.pinterest.ktlint.core.ReporterProvider -import java.io.File -import java.io.ObjectInputStream -import java.util.ServiceLoader - -class SerializableReportersProviderLoader : - ReportersLoaderAdapter { - override fun loadAllReporterProviders(): List> = ServiceLoader - .load(ReporterProvider::class.java) - .toList().map { - ReporterProviderWrapper(it.id, SerializableReporterProvider(it)) - } - - override fun loadReporterProviders(serializedReporterProviders: File): List { - return ObjectInputStream( - serializedReporterProviders.inputStream().buffered() - ).use { - @Suppress("UNCHECKED_CAST") - it.readObject() as List - }.map { Ktlint34ReporterProvider(it.reporterProvider) } - } - - override fun loadAllGenericReporterProviders(): List = ServiceLoader - .load(ReporterProvider::class.java) - .toList().map { - Ktlint34ReporterProvider(it) - } - - override fun filterEnabledBuiltInProviders( - enabledReporters: Set, - allProviders: List> - ): List> { - val enabledProviders = allProviders - .filter { reporterProvider -> - enabledReporters.any { - reporterProvider.id == it.reporterName - } - } - return enabledReporters - .map { reporterType -> - val provider = enabledProviders.find { reporterType.reporterName == it.id } - ?: throw RuntimeException( - "KtLint plugin failed to load reporter ${reporterType.reporterName}." - ) - - val options = if (reporterType == ReporterType.PLAIN_GROUP_BY_FILE) { - reporterType.options.associateWith { "true" } - } else { - emptyMap() - } - - LoadedReporter(provider.id, reporterType.fileExtension, options) to provider.reporterProvider - } - } - - override fun filterCustomProviders( - customReporters: Set, - allProviders: List - ): List> { - val customProviders = allProviders - .filter { reporterProvider -> - customReporters.any { reporterProvider.reporterProvider.id == it.reporterId } - } - - return customReporters - .map { customReporter -> - val provider = customProviders.find { customReporter.reporterId == it.reporterProvider.id } - ?: throw RuntimeException( - "KtLint plugin failed to load ${customReporter.reporterId} custom reporter." - ) - LoadedReporter(customReporter.reporterId, customReporter.fileExtension, emptyMap()) to provider - } - } -} diff --git a/plugin/src/adapter34Test/kotlin/org/jlleitschuh/gradle/ktlint/reporter/SerializableReporterProviderTest.kt b/plugin/src/adapter34Test/kotlin/org/jlleitschuh/gradle/ktlint/reporter/SerializableReporterProviderTest.kt deleted file mode 100644 index 3dd679ee..00000000 --- a/plugin/src/adapter34Test/kotlin/org/jlleitschuh/gradle/ktlint/reporter/SerializableReporterProviderTest.kt +++ /dev/null @@ -1,45 +0,0 @@ -package org.jlleitschuh.gradle.ktlint.reporter - -import com.pinterest.ktlint.core.Reporter -import com.pinterest.ktlint.core.ReporterProvider -import org.assertj.core.api.Assertions.assertThat -import org.junit.jupiter.api.Test -import org.junit.jupiter.api.io.TempDir -import java.io.File -import java.io.ObjectInputStream -import java.io.ObjectOutputStream -import java.io.PrintStream - -internal class SerializableReporterProviderTest { - @TempDir - lateinit var temporaryFolder: File - - @Test - internal fun `Should correctly serialize and deserialize ReporterProvider`() { - val reporterProvider: ReporterProvider = TestReporterProvider() - val wrappedReporterProvider = SerializableReporterProvider(reporterProvider) - val serializeIntoFile = temporaryFolder.resolve("reporters.test") - - ObjectOutputStream(serializeIntoFile.outputStream()).use { - it.writeObject(wrappedReporterProvider) - } - - ObjectInputStream(serializeIntoFile.inputStream()).use { - val restoredWrappedReporterProvider = it.readObject() as SerializableReporterProvider - assertThat(restoredWrappedReporterProvider.reporterProvider).isInstanceOf(TestReporterProvider::class.java) - assertThat(restoredWrappedReporterProvider.reporterProvider.id) - .isEqualTo(reporterProvider.id) - } - } - - private class TestReporterProvider : ReporterProvider { - override val id: String = "test-reporter-provider" - - override fun get( - out: PrintStream, - opt: Map - ): Reporter { - TODO("Not yet implemented") - } - } -} diff --git a/plugin/src/adapter41/kotlin/org/jlleitschuh/gradle/ktlint/reporter/Ktlint41Reporter.kt b/plugin/src/adapter41/kotlin/org/jlleitschuh/gradle/ktlint/reporter/Ktlint41Reporter.kt deleted file mode 100644 index ad73b06f..00000000 --- a/plugin/src/adapter41/kotlin/org/jlleitschuh/gradle/ktlint/reporter/Ktlint41Reporter.kt +++ /dev/null @@ -1,30 +0,0 @@ -package org.jlleitschuh.gradle.ktlint.reporter - -import com.pinterest.ktlint.core.Reporter -import org.jlleitschuh.gradle.ktlint.worker.SerializableLintError -import org.jlleitschuh.gradle.ktlint.worker.toCore - -/** - * implementation of GenericReporter for the Reporter ktlint class - */ -class Ktlint41Reporter(val reporter: Reporter) : GenericReporter { - override fun beforeAll() { - reporter.beforeAll() - } - - override fun before(file: String) { - reporter.before(file) - } - - override fun onLintError(file: String, err: SerializableLintError, corrected: Boolean) { - reporter.onLintError(file, err.toCore(), corrected) - } - - override fun after(file: String) { - reporter.after(file) - } - - override fun afterAll() { - reporter.afterAll() - } -} diff --git a/plugin/src/adapter41/kotlin/org/jlleitschuh/gradle/ktlint/reporter/Ktlint41ReporterProvider.kt b/plugin/src/adapter41/kotlin/org/jlleitschuh/gradle/ktlint/reporter/Ktlint41ReporterProvider.kt deleted file mode 100644 index 0f7331db..00000000 --- a/plugin/src/adapter41/kotlin/org/jlleitschuh/gradle/ktlint/reporter/Ktlint41ReporterProvider.kt +++ /dev/null @@ -1,13 +0,0 @@ -package org.jlleitschuh.gradle.ktlint.reporter - -import com.pinterest.ktlint.core.ReporterProvider -import java.io.PrintStream - -class Ktlint41ReporterProvider(val reporterProvider: ReporterProvider) : GenericReporterProvider { - override fun get(outputStream: PrintStream, opt: Map): Ktlint41Reporter { - return Ktlint41Reporter(reporterProvider.get(outputStream, opt)) - } - - override val id: String - get() = reporterProvider.id -} diff --git a/plugin/src/adapter45/kotlin/org/jlleitschuh/gradle/ktlint/worker/BaselineLoader45.kt b/plugin/src/adapter45/kotlin/org/jlleitschuh/gradle/ktlint/worker/BaselineLoader45.kt deleted file mode 100644 index 8d82a82d..00000000 --- a/plugin/src/adapter45/kotlin/org/jlleitschuh/gradle/ktlint/worker/BaselineLoader45.kt +++ /dev/null @@ -1,9 +0,0 @@ -package org.jlleitschuh.gradle.ktlint.worker - -import com.pinterest.ktlint.core.internal.loadBaseline - -class BaselineLoader45 : BaselineLoader { - override fun loadBaselineRules(path: String): Map> { - return loadBaseline(path).baselineRules?.mapValues { it.value.map { it.toSerializable() } } ?: emptyMap() - } -} diff --git a/plugin/src/adapter45/kotlin/org/jlleitschuh/gradle/ktlint/worker/KtLintInvocation45.kt b/plugin/src/adapter45/kotlin/org/jlleitschuh/gradle/ktlint/worker/KtLintInvocation45.kt deleted file mode 100644 index c42e1e18..00000000 --- a/plugin/src/adapter45/kotlin/org/jlleitschuh/gradle/ktlint/worker/KtLintInvocation45.kt +++ /dev/null @@ -1,80 +0,0 @@ -package org.jlleitschuh.gradle.ktlint.worker - -import com.pinterest.ktlint.core.KtLint -import com.pinterest.ktlint.core.LintError -import com.pinterest.ktlint.core.RuleSet -import com.pinterest.ktlint.core.RuleSetProvider -import java.io.File -import java.util.ServiceLoader - -class KtLintInvocation45( - private val editorConfigPath: String?, - private val ruleSets: Set, - private val userData: Map, - private val debug: Boolean -) : KtLintInvocation { - companion object Factory : KtLintInvocationFactory { - fun initialize( - editorConfigPath: String?, - enableExperimental: Boolean, - disabledRules: Set, - userData: Map, - debug: Boolean - ): KtLintInvocation = KtLintInvocation45( - editorConfigPath = editorConfigPath, - ruleSets = loadRuleSetsFromClasspathWithRuleSetProvider() - .filterRules(enableExperimental, disabledRules), - userData = userData, - debug = debug - ) - } - - private fun buildParams(file: File, cb: (LintError, Boolean) -> Unit): KtLint.Params { - val script = !file.name.endsWith(".kt", ignoreCase = true) - return KtLint.Params( - fileName = file.absolutePath, - text = file.readText(), - ruleSets = ruleSets, - userData = userData, - debug = debug, - editorConfigPath = editorConfigPath, - script = script, - cb = cb - ) - } - - override fun invokeLint(file: File): LintErrorResult { - val errors = mutableListOf>() - KtLint.lint( - buildParams(file) { le, boolean -> - errors.add(le.toSerializable() to boolean) - } - ) - return LintErrorResult(file, errors) - } - - override fun invokeFormat(file: File): Pair { - val errors = mutableListOf>() - val newCode = KtLint.format( - buildParams(file) { le, boolean -> - errors.add(le.toSerializable() to boolean) - } - ) - return newCode to LintErrorResult(file, errors) - } - - override fun trimMemory() { - KtLint.trimMemory() - } -} - -private fun loadRuleSetsFromClasspathWithRuleSetProvider(): Map { - return ServiceLoader - .load(RuleSetProvider::class.java) - .associateBy { - val key = it.get().id - // Adapted from KtLint CLI module - if (key == "standard") "\u0000$key" else key - } - .mapValues { it.value.get() } -} diff --git a/plugin/src/adapter46/kotlin/org/jlleitschuh/gradle/ktlint/worker/BaselineLoader46.kt b/plugin/src/adapter46/kotlin/org/jlleitschuh/gradle/ktlint/worker/BaselineLoader46.kt deleted file mode 100644 index 0ea676e5..00000000 --- a/plugin/src/adapter46/kotlin/org/jlleitschuh/gradle/ktlint/worker/BaselineLoader46.kt +++ /dev/null @@ -1,9 +0,0 @@ -package org.jlleitschuh.gradle.ktlint.worker - -import com.pinterest.ktlint.core.internal.loadBaseline - -class BaselineLoader46 : BaselineLoader { - override fun loadBaselineRules(path: String): Map> { - return loadBaseline(path).baselineRules?.mapValues { it.value.map { it.toSerializable() } } ?: emptyMap() - } -} diff --git a/plugin/src/adapter46/kotlin/org/jlleitschuh/gradle/ktlint/worker/KtLintInvocation46.kt b/plugin/src/adapter46/kotlin/org/jlleitschuh/gradle/ktlint/worker/KtLintInvocation46.kt deleted file mode 100644 index 802e7ac8..00000000 --- a/plugin/src/adapter46/kotlin/org/jlleitschuh/gradle/ktlint/worker/KtLintInvocation46.kt +++ /dev/null @@ -1,104 +0,0 @@ -package org.jlleitschuh.gradle.ktlint.worker - -import com.pinterest.ktlint.core.KtLint -import com.pinterest.ktlint.core.LintError -import com.pinterest.ktlint.core.RuleSet -import com.pinterest.ktlint.core.RuleSetProvider -import com.pinterest.ktlint.core.api.DefaultEditorConfigProperties -import com.pinterest.ktlint.core.api.EditorConfigOverride -import java.io.File -import java.util.ServiceLoader - -class KtLintInvocation46( - private val editorConfigPath: String?, - private val ruleSets: Set, - private val userData: Map, - private val debug: Boolean -) : KtLintInvocation { - companion object Factory : KtLintInvocationFactory { - fun initialize( - editorConfigPath: String?, - enableExperimental: Boolean, - disabledRules: Set, - userData: Map, - debug: Boolean - ): KtLintInvocation = KtLintInvocation46( - editorConfigPath = editorConfigPath, - ruleSets = loadRuleSetsFromClasspathWithRuleSetProvider() - .filterRules(enableExperimental, disabledRules), - userData = userData, - debug = debug - ) - } - - private fun buildParams( - file: File, - cb: (LintError, Boolean) -> Unit - ): KtLint.ExperimentalParams { - val script = !file.name.endsWith(".kt", ignoreCase = true) - return KtLint.ExperimentalParams( - fileName = file.absolutePath, - text = file.readText(), - ruleSets = ruleSets, - cb = cb, - script = script, - editorConfigPath = editorConfigPath, - debug = debug, - editorConfigOverride = userDataToEditorConfigOverride(userData) - ) - } - - override fun invokeLint(file: File): LintErrorResult { - val errors = mutableListOf>() - KtLint.lint( - buildParams(file) { le, boolean -> - errors.add(le.toSerializable() to boolean) - } - ) - return LintErrorResult(file, errors) - } - - override fun invokeFormat(file: File): Pair { - val errors = mutableListOf>() - val newCode = KtLint.format( - buildParams(file) { le, boolean -> - errors.add(le.toSerializable() to boolean) - } - ) - return newCode to LintErrorResult(file, errors) - } - - override fun trimMemory() { - KtLint.trimMemory() - } -} - -internal fun LintError.toSerializable(): SerializableLintError { - return SerializableLintError(line, col, ruleId, detail, canBeAutoCorrected) -} - -private fun userDataToEditorConfigOverride(userData: Map): EditorConfigOverride { - val codeStyle = if (userData["android"]?.toBoolean() == true) { - DefaultEditorConfigProperties.CodeStyleValue.android - } else { - DefaultEditorConfigProperties.CodeStyleValue.official - } - if (!userData["disabled_rules"].isNullOrBlank()) { - return EditorConfigOverride.from( - DefaultEditorConfigProperties.codeStyleSetProperty to codeStyle, - DefaultEditorConfigProperties.disabledRulesProperty to userData["disabled_rules"] - ) - } - return EditorConfigOverride.from(DefaultEditorConfigProperties.codeStyleSetProperty to codeStyle) -} - -private fun loadRuleSetsFromClasspathWithRuleSetProvider(): Map { - return ServiceLoader - .load(RuleSetProvider::class.java) - .associateBy { - val key = it.get().id - // Adapted from KtLint CLI module - if (key == "standard") "\u0000$key" else key - } - .mapValues { it.value.get() } -} diff --git a/plugin/src/adapter34/kotlin/org/jlleitschuh/gradle/ktlint/reporter/Ktlint34Reporter.kt b/plugin/src/adapter47/kotlin/org/jlleitschuh/gradle/ktlint/reporter/LegacyKtlintReporter.kt similarity index 89% rename from plugin/src/adapter34/kotlin/org/jlleitschuh/gradle/ktlint/reporter/Ktlint34Reporter.kt rename to plugin/src/adapter47/kotlin/org/jlleitschuh/gradle/ktlint/reporter/LegacyKtlintReporter.kt index 783e45a9..cce983b2 100644 --- a/plugin/src/adapter34/kotlin/org/jlleitschuh/gradle/ktlint/reporter/Ktlint34Reporter.kt +++ b/plugin/src/adapter47/kotlin/org/jlleitschuh/gradle/ktlint/reporter/LegacyKtlintReporter.kt @@ -7,7 +7,7 @@ import org.jlleitschuh.gradle.ktlint.worker.toCore /** * implementation of GenericReporter for the Reporter ktlint class */ -class Ktlint34Reporter(val reporter: Reporter) : GenericReporter { +class LegacyKtlintReporter(val reporter: Reporter) : GenericReporter { override fun beforeAll() { reporter.beforeAll() } diff --git a/plugin/src/adapter47/kotlin/org/jlleitschuh/gradle/ktlint/reporter/LegacyKtlintReporterProvider.kt b/plugin/src/adapter47/kotlin/org/jlleitschuh/gradle/ktlint/reporter/LegacyKtlintReporterProvider.kt new file mode 100644 index 00000000..56fad011 --- /dev/null +++ b/plugin/src/adapter47/kotlin/org/jlleitschuh/gradle/ktlint/reporter/LegacyKtlintReporterProvider.kt @@ -0,0 +1,16 @@ +package org.jlleitschuh.gradle.ktlint.reporter + +import com.pinterest.ktlint.core.Reporter +import com.pinterest.ktlint.core.ReporterProvider +import java.io.PrintStream + +class LegacyKtlintReporterProvider( + val reporterProvider: ReporterProvider +) : GenericReporterProvider { + override fun get(outputStream: PrintStream, opt: Map): LegacyKtlintReporter { + return LegacyKtlintReporter(reporterProvider.get(outputStream, opt)) + } + + override val id: String + get() = reporterProvider.id +} diff --git a/plugin/src/adapter41/kotlin/org/jlleitschuh/gradle/ktlint/reporter/ReportersProviderLoader.kt b/plugin/src/adapter47/kotlin/org/jlleitschuh/gradle/ktlint/reporter/ReportersProviderLoader.kt similarity index 78% rename from plugin/src/adapter41/kotlin/org/jlleitschuh/gradle/ktlint/reporter/ReportersProviderLoader.kt rename to plugin/src/adapter47/kotlin/org/jlleitschuh/gradle/ktlint/reporter/ReportersProviderLoader.kt index 1a0013e2..616da1af 100644 --- a/plugin/src/adapter41/kotlin/org/jlleitschuh/gradle/ktlint/reporter/ReportersProviderLoader.kt +++ b/plugin/src/adapter47/kotlin/org/jlleitschuh/gradle/ktlint/reporter/ReportersProviderLoader.kt @@ -7,32 +7,32 @@ import java.io.ObjectInputStream import java.util.ServiceLoader class ReportersProviderLoader : - ReportersLoaderAdapter { - override fun loadAllReporterProviders(): List> = ServiceLoader + ReportersLoaderAdapter, LegacyKtlintReporter, LegacyKtlintReporterProvider> { + override fun loadAllReporterProviders(): List>> = ServiceLoader .load(ReporterProvider::class.java) .toList().map { ReporterProviderWrapper(it.id, it) } - override fun loadAllGenericReporterProviders(): List = ServiceLoader + override fun loadAllGenericReporterProviders(): List = ServiceLoader .load(ReporterProvider::class.java) .toList().map { - Ktlint41ReporterProvider(it) + LegacyKtlintReporterProvider(it) } - override fun loadReporterProviders(serializedReporterProviders: File): List { + override fun loadReporterProviders(serializedReporterProviders: File): List { return ObjectInputStream( serializedReporterProviders.inputStream().buffered() ).use { @Suppress("UNCHECKED_CAST") - it.readObject() as List - }.map { Ktlint41ReporterProvider(it) } + it.readObject() as List> + }.map { LegacyKtlintReporterProvider(it) } } override fun filterEnabledBuiltInProviders( enabledReporters: Set, - allProviders: List> - ): List> { + allProviders: List>> + ): List>> { val enabledProviders = allProviders .filter { reporterProvider -> enabledReporters.any { @@ -58,8 +58,8 @@ class ReportersProviderLoader : override fun filterCustomProviders( customReporters: Set, - allProviders: List - ): List> { + allProviders: List> + ): List>> { val customProviders = allProviders .filter { reporterProvider -> customReporters.any { reporterProvider.id == it.reporterId } diff --git a/plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/Configurations.kt b/plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/Configurations.kt index e1baf3cf..d3a368bd 100644 --- a/plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/Configurations.kt +++ b/plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/Configurations.kt @@ -4,12 +4,7 @@ import net.swiftzer.semver.SemVer import org.gradle.api.Project import org.gradle.api.artifacts.Configuration import org.gradle.api.artifacts.Dependency -import org.gradle.api.artifacts.component.ModuleComponentIdentifier -import org.gradle.api.artifacts.component.ModuleComponentSelector -import org.gradle.api.artifacts.component.ProjectComponentIdentifier -import org.gradle.api.artifacts.result.ResolvedDependencyResult import org.gradle.api.attributes.Bundling -import org.gradle.util.GradleVersion internal const val KTLINT_CONFIGURATION_NAME = "ktlint" internal const val KTLINT_CONFIGURATION_DESCRIPTION = "Main ktlint-gradle configuration" @@ -34,7 +29,7 @@ internal fun createKtlintConfiguration(target: Project, extension: KtlintExtensi // Starting from KtLint 0.41.0 version published artifact has two variants: "external" and "shadowed" attributes { - it.attribute(Bundling.BUNDLING_ATTRIBUTE, target.objects.named(Bundling::class.java, Bundling.EXTERNAL)) + attribute(Bundling.BUNDLING_ATTRIBUTE, target.objects.named(Bundling::class.java, Bundling.EXTERNAL)) } // Workaround for gradle 6 https://github.com/gradle/gradle/issues/13255 @@ -49,8 +44,9 @@ internal fun createKtlintConfiguration(target: Project, extension: KtlintExtensi target.logger.info("Add dependencies: ktlint version $it") listOf( target.dependencies.create("com.pinterest.ktlint:ktlint-cli:$it"), - // this transitive dep was introduced in ktlint 1.0, but for some reason, it is not picked up automatically - target.dependencies.create("io.github.oshai:kotlin-logging:5.1.0") + // these transitive deps were introduced in ktlint 1.0, but for some reason not picked up automatically + target.dependencies.create("io.github.oshai:kotlin-logging:5.1.0"), + target.dependencies.create("io.github.detekt.sarif4k:sarif4k:0.5.0") ) } } @@ -96,10 +92,21 @@ internal fun createKtLintReporterConfiguration( ensureConsistencyWith(target, ktLintConfiguration) withDependencies { + // this transitive dep was introduced in ktlint 1.0, but for some reason, it is not picked up automatically + dependencies.addAllLater( + target.provider { + if (SemVer.parse(extension.version.get()) >= SemVer(1, 0, 0)) { + listOf(target.dependencies.create("io.github.detekt.sarif4k:sarif4k:0.5.0")) + } else { + listOf() + } + } + ) + extension .reporterExtension .customReporters - .all { + .forEach { dependencies.addLater( target.provider { val reporterDependency = it.dependency @@ -159,13 +166,9 @@ internal fun createKtLintBaselineReporterConfiguration( // this transitive dep was introduced in ktlint 1.0, but for some reason, it is not picked up automatically target.dependencies.create("io.github.oshai:kotlin-logging:5.1.0") ) - } else if (SemVer.parse(ktlintVersion) >= SemVer(0, 41, 0)) { + } else { // Baseline reporter is only available starting 0.41.0 release listOf(target.dependencies.create("com.pinterest.ktlint:ktlint-reporter-baseline:$version")) - } else { - // Adding fake plain reporter as addLater() does not accept `null` value - // Generate baseline tasks anyway will not run on KtLint versions < 0.41.0 - listOf(target.dependencies.create("com.pinterest.ktlint:ktlint-reporter-plain:$version")) } } ) @@ -177,51 +180,5 @@ private fun Configuration.ensureConsistencyWith( target: Project, otherConfiguration: Configuration ) { - if (GradleVersion.version(target.gradle.gradleVersion) >= GradleVersion.version("6.8")) { - shouldResolveConsistentlyWith(otherConfiguration) - } else { - // Inspired by - // https://android.googlesource.com/platform/tools/base/+/refs/heads/mirror-goog-studio-master-dev/build-system/gradle-core/src/main/java/com/android/build/gradle/internal/dependency/ConstraintHandler.kt - incoming.beforeResolve { - val configName = it.name - otherConfiguration.incoming.resolutionResult.allDependencies { dependency -> - if (dependency is ResolvedDependencyResult) { - val id = dependency.selected.id - if (id is ModuleComponentIdentifier) { - // using a repository with a flatDir to stock local AARs will result in an - // external module dependency with no version. - if (!id.version.isNullOrEmpty()) { - if (id.module != "listenablefuture" || - id.group != "com.google.guava" || - id.version != "1.0" - ) { - target.dependencies.constraints.add( - configName, - "${id.group}:${id.module}:${id.version}" - ) { constraint -> - constraint.because("${otherConfiguration.name} uses version ${id.version}") - constraint.version { versionConstraint -> - versionConstraint.strictly(id.version) - } - } - } - } - } else if (id is ProjectComponentIdentifier && - id.build.isCurrentBuild && - dependency.requested is ModuleComponentSelector - ) { - // Requested external library has been replaced with the project dependency, so - // add the project dependency to the target configuration, so it can be chosen - // instead of the external library as well. - // We should avoid doing this for composite builds, so we check if the selected - // project is from the current build. - target.dependencies.add( - configName, - target.dependencies.project(mapOf("path" to id.projectPath)) - ) - } - } - } - } - } + shouldResolveConsistentlyWith(otherConfiguration) } diff --git a/plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/GitHook.kt b/plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/GitHook.kt index 607874ae..af168342 100644 --- a/plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/GitHook.kt +++ b/plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/GitHook.kt @@ -114,12 +114,12 @@ private fun KtlintPlugin.PluginHolder.addInstallGitHookFormatTask() { INSTALL_GIT_HOOK_FORMAT_TASK, KtlintInstallGitHookTask::class.java ) { - it.description = "Adds git hook to run ktlintFormat on changed files" - it.group = HELP_GROUP - it.taskName.set(FORMAT_PARENT_TASK_NAME) + description = "Adds git hook to run ktlintFormat on changed files" + group = HELP_GROUP + taskName.set(FORMAT_PARENT_TASK_NAME) // Format git hook will automatically add back updated files to git commit - it.shouldUpdateCommit.set(true) - it.hookName.set("pre-commit") + shouldUpdateCommit.set(true) + hookName.set("pre-commit") } } @@ -128,11 +128,11 @@ private fun KtlintPlugin.PluginHolder.addInstallGitHookCheckTask() { INSTALL_GIT_HOOK_CHECK_TASK, KtlintInstallGitHookTask::class.java ) { - it.description = "Adds git hook to run ktlintCheck on changed files" - it.group = HELP_GROUP - it.taskName.set(CHECK_PARENT_TASK_NAME) - it.shouldUpdateCommit.set(false) - it.hookName.set("pre-commit") + description = "Adds git hook to run ktlintCheck on changed files" + group = HELP_GROUP + taskName.set(CHECK_PARENT_TASK_NAME) + shouldUpdateCommit.set(false) + hookName.set("pre-commit") } } diff --git a/plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/KtLintCompatibility.kt b/plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/KtLintCompatibility.kt index 889a31b9..f2251dee 100644 --- a/plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/KtLintCompatibility.kt +++ b/plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/KtLintCompatibility.kt @@ -5,16 +5,11 @@ import org.gradle.api.GradleException import org.jlleitschuh.gradle.ktlint.reporter.ReportersLoaderAdapter import org.jlleitschuh.gradle.ktlint.reporter.ReportersProviderLoader import org.jlleitschuh.gradle.ktlint.reporter.ReportersProviderV2Loader -import org.jlleitschuh.gradle.ktlint.reporter.SerializableReportersProviderLoader import org.jlleitschuh.gradle.ktlint.worker.BaselineLoader -import org.jlleitschuh.gradle.ktlint.worker.BaselineLoader45 -import org.jlleitschuh.gradle.ktlint.worker.BaselineLoader46 import org.jlleitschuh.gradle.ktlint.worker.BaselineLoader47 import org.jlleitschuh.gradle.ktlint.worker.BaselineLoader48 import org.jlleitschuh.gradle.ktlint.worker.BaselineLoader49 import org.jlleitschuh.gradle.ktlint.worker.KtLintInvocation100 -import org.jlleitschuh.gradle.ktlint.worker.KtLintInvocation45 -import org.jlleitschuh.gradle.ktlint.worker.KtLintInvocation46 import org.jlleitschuh.gradle.ktlint.worker.KtLintInvocation47 import org.jlleitschuh.gradle.ktlint.worker.KtLintInvocation48 import org.jlleitschuh.gradle.ktlint.worker.KtLintInvocation49 @@ -25,11 +20,7 @@ import java.io.Serializable internal fun selectInvocation(version: String): KtLintInvocationFactory { val semVer = SemVer.parse(version) return if (semVer.major == 0) { - if (semVer.minor < 46) { - KtLintInvocation45 - } else if (semVer.minor == 46) { - KtLintInvocation46 - } else if (semVer.minor == 47) { + if (semVer.minor == 47) { KtLintInvocation47 } else if (semVer.minor == 48) { KtLintInvocation48 @@ -46,11 +37,7 @@ internal fun selectInvocation(version: String): KtLintInvocationFactory { internal fun selectBaselineLoader(version: String): BaselineLoader { val semVer = SemVer.parse(version) return if (semVer.major == 0) { - if (semVer.minor < 46) { - BaselineLoader45() - } else if (semVer.minor == 46) { - BaselineLoader46() - } else if (semVer.minor == 47) { + if (semVer.minor == 47) { BaselineLoader47() } else if (semVer.minor == 48) { BaselineLoader48() @@ -71,9 +58,7 @@ internal fun selectBaselineLoader(version: String): BaselineLoader { internal fun selectReportersLoaderAdapter(version: String): ReportersLoaderAdapter<*, out Serializable, *, *> { val semVer = SemVer.parse(version) return if (semVer.major == 0) { - if (semVer.minor < 41) { - SerializableReportersProviderLoader() - } else if (semVer.minor < 49) { + if (semVer.minor < 49) { ReportersProviderLoader() } else { ReportersProviderV2Loader() diff --git a/plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/KtlintApplyToIdeaTask.kt b/plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/KtlintApplyToIdeaTask.kt deleted file mode 100644 index f5322429..00000000 --- a/plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/KtlintApplyToIdeaTask.kt +++ /dev/null @@ -1,76 +0,0 @@ -package org.jlleitschuh.gradle.ktlint - -import net.swiftzer.semver.SemVer -import org.gradle.api.DefaultTask -import org.gradle.api.file.ConfigurableFileCollection -import org.gradle.api.model.ObjectFactory -import org.gradle.api.provider.Property -import org.gradle.api.tasks.Classpath -import org.gradle.api.tasks.Input -import org.gradle.api.tasks.TaskAction -import javax.inject.Inject - -@Suppress("UnstableApiUsage") -open class KtlintApplyToIdeaTask @Inject constructor( - objectFactory: ObjectFactory -) : DefaultTask() { - - @get:Classpath - val classpath: ConfigurableFileCollection = project.files() - - @get:Input - val android: Property = objectFactory.property() - - @get:Input - val globally: Property = objectFactory.property() - - @get:Input - val ktlintVersion: Property = objectFactory.property() - - @TaskAction - fun generate() { - // this option was removed and will cause errors in ktlint >= 0.47.0 - if (SemVer.parse(ktlintVersion.get()) < SemVer(0, 47, 0)) { - project.javaexec { - it.classpath = classpath - it.main = "com.pinterest.ktlint.Main" - - // Global flags - if (android.get()) { - it.args( - "--android" - ) - } - - // Subcommand - if (globally.get()) { - it.args(getApplyToIdeaCommand()) - } else { - it.args(getApplyToProjectCommand()) - } - - // Subcommand parameters - // -y here to auto-overwrite existing IDEA code style. - it.args("-y") - } - } else { - project.logger.warn( - "Skipping ${this.name}. The applyToIDEA functionality was removed from ktlint in 0.47.0. Use .editorconfig to synchronize formatting rules between IDEA and ktlint." - ) - } - } - - private fun getApplyToIdeaCommand() = - if (SemVer.parse(ktlintVersion.get()) >= SemVer(0, 35, 0)) { - "applyToIDEA" - } else { - "--apply-to-idea" - } - - private fun getApplyToProjectCommand() = - if (SemVer.parse(ktlintVersion.get()) >= SemVer(0, 35, 0)) { - "applyToIDEAProject" - } else { - "--apply-to-idea-project" - } -} diff --git a/plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/KtlintBasePlugin.kt b/plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/KtlintBasePlugin.kt index ce84ff20..86af4757 100644 --- a/plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/KtlintBasePlugin.kt +++ b/plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/KtlintBasePlugin.kt @@ -30,8 +30,8 @@ open class KtlintBasePlugin : Plugin { } val kotlinScriptAdditionalPathApplier: KotlinScriptAdditionalPathApplier = { additionalFileTree -> - val configureAction = Action { task -> - with(task as BaseKtLintCheckTask) { + val configureAction = Action { + with(this as BaseKtLintCheckTask) { source( additionalFileTree.also { it.include("*.kts") @@ -63,6 +63,6 @@ open class KtlintBasePlugin : Plugin { } companion object { - const val LOWEST_SUPPORTED_GRADLE_VERSION = "6.8" + const val LOWEST_SUPPORTED_GRADLE_VERSION = "7.4.2" } } diff --git a/plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/KtlintExtension.kt b/plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/KtlintExtension.kt index 4b2a147a..afd86506 100644 --- a/plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/KtlintExtension.kt +++ b/plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/KtlintExtension.kt @@ -36,7 +36,7 @@ internal constructor( /** * The version of KtLint to use. */ - val version: Property = objectFactory.property { set("0.47.1") } + val version: Property = objectFactory.property { set("1.0.1") } /** * Enable relative paths in reports @@ -104,10 +104,8 @@ internal constructor( } /** - * Provide additional `.editorconfig` file, that are not in the project or project parent folders. + * Provide additional `.editorconfig` properties, that are not in the project or project parent folders. */ - @Deprecated("not supported with ktlint 0.47+") - val additionalEditorconfigFile: RegularFileProperty = objectFactory.fileProperty() val additionalEditorconfig: MapProperty = objectFactory.mapProperty(String::class.java, String::class.java) .apply { diff --git a/plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/KtlintIdeaPlugin.kt b/plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/KtlintIdeaPlugin.kt deleted file mode 100644 index 96e29006..00000000 --- a/plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/KtlintIdeaPlugin.kt +++ /dev/null @@ -1,44 +0,0 @@ -package org.jlleitschuh.gradle.ktlint - -import org.gradle.api.Plugin -import org.gradle.api.Project - -/** - * Adds tasks associated with configuring IntelliJ IDEA. - */ -open class KtlintIdeaPlugin : Plugin { - override fun apply(target: Project) { - val extension = target.plugins.apply(KtlintBasePlugin::class.java).extension - - if (target == target.rootProject) { - /* - * Only add these tasks if we are applying to the root project. - */ - addApplyToIdeaTasks(target, extension) - } - } - - private fun addApplyToIdeaTasks(rootProject: Project, extension: KtlintExtension) { - val ktLintConfig = createKtlintConfiguration(rootProject, extension) - - rootProject.registerTask(APPLY_TO_IDEA_TASK_NAME) { - group = HELP_GROUP - description = "Generates IDEA built-in formatter rules and apply them to the project." + - "It will overwrite existing ones." - classpath.setFrom(ktLintConfig) - android.set(extension.android) - globally.set(rootProject.provider { false }) - ktlintVersion.set(extension.version) - } - - rootProject.registerTask(APPLY_TO_IDEA_GLOBALLY_TASK_NAME) { - group = HELP_GROUP - description = "Generates IDEA built-in formatter rules and apply them globally " + - "(in IDEA user settings folder). It will overwrite existing ones." - classpath.setFrom(ktLintConfig) - android.set(extension.android) - globally.set(rootProject.provider { true }) - ktlintVersion.set(extension.version) - } - } -} diff --git a/plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/KtlintPlugin.kt b/plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/KtlintPlugin.kt index 626b22a5..f3b7c689 100644 --- a/plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/KtlintPlugin.kt +++ b/plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/KtlintPlugin.kt @@ -20,9 +20,6 @@ open class KtlintPlugin : Plugin { override fun apply(target: Project) { val holder = PluginHolder(target) - // Apply the idea plugin - target.plugins.apply(KtlintIdeaPlugin::class.java) - holder.addKotlinScriptTasks() holder.addKtLintTasksToKotlinPlugin() holder.addGenerateBaselineTask() @@ -42,7 +39,7 @@ open class KtlintPlugin : Plugin { private fun PluginHolder.applyKtlintMultiplatform(): (Plugin) -> Unit = { val multiplatformExtension = target.extensions.getByType(KotlinMultiplatformExtension::class.java) - multiplatformExtension.sourceSets.all { sourceSet -> + multiplatformExtension.sourceSets.forEach { sourceSet -> val checkTask = createCheckTask( this, sourceSet.name, @@ -73,7 +70,7 @@ open class KtlintPlugin : Plugin { addGenerateReportsTaskToProjectMetaFormatTask(generateReportsFormatTask) } - multiplatformExtension.targets.all { kotlinTarget -> + multiplatformExtension.targets.forEach { kotlinTarget -> if (kotlinTarget.platformType == KotlinPlatformType.androidJvm) { applyKtLintToAndroid() } @@ -81,16 +78,16 @@ open class KtlintPlugin : Plugin { } private fun PluginHolder.applyKtLint(): (Plugin) -> Unit = { - target.extensions.configure("kotlin") { extension -> - extension.sourceSets.all { sourceSet -> + target.extensions.configure(KotlinProjectExtension::class.java) { + sourceSets.forEach { sourceSet -> val kotlinSourceDirectories = sourceSet.kotlin.sourceDirectories val checkTask = createCheckTask( - this, + this@applyKtLint, sourceSet.name, kotlinSourceDirectories ) val generateReportsCheckTask = createGenerateReportsTask( - this, + this@applyKtLint, checkTask, GenerateReportsTask.LintType.CHECK, sourceSet.name @@ -100,12 +97,12 @@ open class KtlintPlugin : Plugin { setCheckTaskDependsOnGenerateReportsTask(generateReportsCheckTask) val formatTask = createFormatTask( - this, + this@applyKtLint, sourceSet.name, kotlinSourceDirectories ) val generateReportsFormatTask = createGenerateReportsTask( - this, + this@applyKtLint, formatTask, GenerateReportsTask.LintType.FORMAT, sourceSet.name diff --git a/plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/PluginUtil.kt b/plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/PluginUtil.kt index 6a7b19c8..406d5f5c 100644 --- a/plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/PluginUtil.kt +++ b/plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/PluginUtil.kt @@ -15,6 +15,7 @@ import org.gradle.api.provider.Property import org.gradle.api.provider.Provider import org.gradle.api.provider.SetProperty import org.gradle.api.tasks.TaskProvider +import org.gradle.kotlin.dsl.register import org.gradle.language.base.plugins.LifecycleBasePlugin import java.io.File import java.nio.file.Files @@ -26,9 +27,9 @@ internal inline fun Project.registerTask( noinline configuration: T.() -> Unit ): TaskProvider { return tasks - .register(name, T::class.java, *constructorArguments) + .register(name, *constructorArguments) .apply { - configure { configuration(it) } + this.configure(configuration) } } @@ -86,8 +87,6 @@ internal const val FORMATTING_GROUP = "Formatting" internal const val HELP_GROUP = HelpTasksPlugin.HELP_GROUP internal const val CHECK_PARENT_TASK_NAME = "ktlintCheck" internal const val FORMAT_PARENT_TASK_NAME = "ktlintFormat" -internal const val APPLY_TO_IDEA_TASK_NAME = "ktlintApplyToIdea" -internal const val APPLY_TO_IDEA_GLOBALLY_TASK_NAME = "ktlintApplyToIdeaGlobally" internal const val INSTALL_GIT_HOOK_CHECK_TASK = "addKtlintCheckGitPreCommitHook" internal const val INSTALL_GIT_HOOK_FORMAT_TASK = "addKtlintFormatGitPreCommitHook" internal val KOTLIN_EXTENSIONS = listOf("kt", "kts") @@ -125,9 +124,9 @@ internal fun Logger.logKtLintDebugMessage( } internal fun checkMinimalSupportedKtLintVersion(ktLintVersion: String) { - if (SemVer.parse(ktLintVersion) < SemVer(0, 34, 0)) { + if (SemVer.parse(ktLintVersion) < SemVer(0, 47, 1)) { throw GradleException( - "KtLint versions less than 0.34.0 are not supported. " + + "KtLint versions less than 0.47.1 are not supported. " + "Detected KtLint version: $ktLintVersion." ) } diff --git a/plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/TaskCreation.kt b/plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/TaskCreation.kt index 1fc92109..1b9d9c92 100644 --- a/plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/TaskCreation.kt +++ b/plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/TaskCreation.kt @@ -5,6 +5,7 @@ import org.gradle.api.file.FileTree import org.gradle.api.tasks.TaskCollection import org.gradle.api.tasks.TaskProvider import org.gradle.api.tasks.util.PatternSet +import org.gradle.kotlin.dsl.register import org.gradle.language.base.plugins.LifecycleBasePlugin import org.jlleitschuh.gradle.ktlint.tasks.BaseKtLintCheckTask import org.jlleitschuh.gradle.ktlint.tasks.GenerateBaselineTask @@ -16,13 +17,13 @@ import org.jlleitschuh.gradle.ktlint.tasks.LoadReportersTask internal fun KtlintPlugin.PluginHolder.addGenerateReportsTaskToProjectMetaCheckTask( generatesReportsTask: TaskProvider ) { - metaKtlintCheckTask.configure { it.dependsOn(generatesReportsTask) } + metaKtlintCheckTask.configure { dependsOn(generatesReportsTask) } } internal fun KtlintPlugin.PluginHolder.addGenerateReportsTaskToProjectMetaFormatTask( generateReportsTask: TaskProvider ) { - metaKtlintFormatTask.configure { it.dependsOn(generateReportsTask) } + metaKtlintFormatTask.configure { dependsOn(generateReportsTask) } } internal fun createFormatTask( @@ -103,26 +104,25 @@ internal fun KtlintPlugin.PluginHolder.setCheckTaskDependsOnGenerateReportsTask( generateReportsTask: TaskProvider ) { target.plugins.withType(LifecycleBasePlugin::class.java) { - target.tasks.named(LifecycleBasePlugin.CHECK_TASK_NAME).configure { task -> - task.dependsOn(generateReportsTask) + target.tasks.named(LifecycleBasePlugin.CHECK_TASK_NAME) { + dependsOn(generateReportsTask) } } } internal fun createLoadReportersTask( pluginHolder: KtlintPlugin.PluginHolder -): TaskProvider = pluginHolder.target.registerTask( - LoadReportersTask.TASK_NAME -) { - description = LoadReportersTask.DESCRIPTION - - ktLintClasspath.setFrom(pluginHolder.ktlintConfiguration) - reportersClasspath.setFrom(pluginHolder.ktlintReporterConfiguration) - debug.set(pluginHolder.extension.debug) - ktLintVersion.set(pluginHolder.extension.version) - enabledReporters.set(pluginHolder.extension.reporterExtension.reporters) - customReporters.set(pluginHolder.extension.reporterExtension.customReporters) -} +): TaskProvider = + pluginHolder.target.tasks.register(LoadReportersTask.TASK_NAME) { + description = LoadReportersTask.DESCRIPTION + + ktLintClasspath.setFrom(pluginHolder.ktlintConfiguration) + reportersClasspath.setFrom(pluginHolder.ktlintReporterConfiguration) + debug.set(pluginHolder.extension.debug) + ktLintVersion.set(pluginHolder.extension.version) + enabledReporters.set(pluginHolder.extension.reporterExtension.reporters) + customReporters.set(pluginHolder.extension.reporterExtension.customReporters) + } private fun BaseKtLintCheckTask.configureBaseCheckTask( pluginHolder: KtlintPlugin.PluginHolder, @@ -130,7 +130,6 @@ private fun BaseKtLintCheckTask.configureBaseCheckTask( ) { ktLintClasspath.setFrom(pluginHolder.ktlintConfiguration) ktLintVersion.set(pluginHolder.extension.version) - additionalEditorconfigFile.set(pluginHolder.extension.additionalEditorconfigFile) additionalEditorconfig.set(pluginHolder.extension.additionalEditorconfig) debug.set(pluginHolder.extension.debug) ruleSetsClasspath.setFrom(pluginHolder.ktlintRulesetConfiguration) diff --git a/plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/android/AndroidPluginsApplier.kt b/plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/android/AndroidPluginsApplier.kt index ebf38a70..c8c2d7ec 100644 --- a/plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/android/AndroidPluginsApplier.kt +++ b/plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/android/AndroidPluginsApplier.kt @@ -64,19 +64,19 @@ private typealias AndroidCommonExtension = CommonExtension< private fun androidPluginConfigureAction( pluginHolder: KtlintPlugin.PluginHolder ): (Plugin) -> Unit = { - pluginHolder.target.extensions.configure(CommonExtension::class.java) { ext -> - val androidCommonExtension = ext as AndroidCommonExtension + pluginHolder.target.extensions.configure(CommonExtension::class.java) { + val androidCommonExtension = this as AndroidCommonExtension - androidCommonExtension.sourceSets.all { sourceSet -> + androidCommonExtension.sourceSets.all { // https://issuetracker.google.com/u/1/issues/170650362 - val androidSourceSet = sourceSet.java as DefaultAndroidSourceDirectorySet + val androidSourceSet = java as DefaultAndroidSourceDirectorySet // Passing Callable, so returned FileCollection, will lazy evaluate it // only when task will need it. // Solves the problem of having additional source dirs in // current AndroidSourceSet, that are not available on eager // evaluation. pluginHolder.createAndroidTasks( - sourceSet.name, + name, pluginHolder.target.files(Callable { androidSourceSet.srcDirs }) ) } diff --git a/plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/tasks/BaseKtLintCheckTask.kt b/plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/tasks/BaseKtLintCheckTask.kt index 96f87e10..8f2fecd4 100644 --- a/plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/tasks/BaseKtLintCheckTask.kt +++ b/plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/tasks/BaseKtLintCheckTask.kt @@ -1,9 +1,7 @@ package org.jlleitschuh.gradle.ktlint.tasks import groovy.lang.Closure -import net.swiftzer.semver.SemVer import org.gradle.api.DefaultTask -import org.gradle.api.GradleException import org.gradle.api.JavaVersion import org.gradle.api.file.ConfigurableFileCollection import org.gradle.api.file.FileCollection @@ -188,8 +186,6 @@ abstract class BaseKtLintCheckTask @Inject constructor( protected fun runLint( inputChanges: InputChanges ) { - checkDisabledRulesSupportedKtLintVersion() - val editorConfigUpdated = wasEditorConfigFilesUpdated(inputChanges) val filesToCheck = if (editorConfigUpdated) { source.files @@ -219,8 +215,6 @@ abstract class BaseKtLintCheckTask @Inject constructor( inputChanges: InputChanges, formatSnapshot: File ) { - checkDisabledRulesSupportedKtLintVersion() - val editorConfigUpdated = wasEditorConfigFilesUpdated(inputChanges) val filesToCheck = if (editorConfigUpdated) { source.files @@ -269,32 +263,32 @@ abstract class BaseKtLintCheckTask @Inject constructor( // Process isolation is used here to run KtLint in a separate java process. // This allows to better isolate work actions from different projects tasks between each other // and to not pollute Gradle daemon heap, which otherwise greatly increases GC time. - val queue = workerExecutor.processIsolation { spec -> - spec.classpath.from(ktLintClasspath, ruleSetsClasspath) - spec.forkOptions { options -> - options.maxHeapSize = workerMaxHeapSize.get() + val queue = workerExecutor.processIsolation { + classpath.from(ktLintClasspath, ruleSetsClasspath) + forkOptions { + maxHeapSize = workerMaxHeapSize.get() // Work around ktlint triggering reflective access errors from the embedded Kotlin // compiler. See https://youtrack.jetbrains.com/issue/KT-43704 for details. if (JavaVersion.current() >= JavaVersion.VERSION_16) { - options.jvmArgs("--add-opens", "java.base/java.lang=ALL-UNNAMED") + jvmArgs("--add-opens", "java.base/java.lang=ALL-UNNAMED") } } } - queue.submit(KtLintWorkAction::class.java) { params -> - params.filesToLint.from(filesToCheck) - params.enableExperimental.set(enableExperimentalRules) - params.android.set(android) - params.disabledRules.set(disabledRules) - params.debug.set(debug) - params.additionalEditorconfigFile.set(additionalEditorconfigFile) - params.additionalEditorconfig.set(additionalEditorconfig) - params.formatSource.set(formatSources) - params.discoveredErrorsFile.set(discoveredErrors) - params.ktLintVersion.set(ktLintVersion) - params.editorconfigFilesWereChanged.set(editorConfigUpdated) - params.formatSnapshot.set(formatSnapshot) + queue.submit(KtLintWorkAction::class.java) { + val task = this@BaseKtLintCheckTask + filesToLint.from(filesToCheck) + enableExperimental.set(task.enableExperimentalRules) + android.set(task.android) + disabledRules.set(task.disabledRules) + debug.set(task.debug) + additionalEditorconfig.set(task.additionalEditorconfig) + formatSource.set(formatSources) + discoveredErrorsFile.set(task.discoveredErrors) + ktLintVersion.set(task.ktLintVersion) + editorconfigFilesWereChanged.set(editorConfigUpdated) + this.formatSnapshot.set(formatSnapshot) } } @@ -315,12 +309,4 @@ abstract class BaseKtLintCheckTask @Inject constructor( } .map { it.file } .toSet() - - private fun checkDisabledRulesSupportedKtLintVersion() { - if (disabledRules.get().isNotEmpty() && - SemVer.parse(ktLintVersion.get()) < SemVer(0, 34, 2) - ) { - throw GradleException("Rules disabling is supported since 0.34.2 ktlint version.") - } - } } diff --git a/plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/tasks/GenerateBaselineTask.kt b/plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/tasks/GenerateBaselineTask.kt index 0f293246..c78641f1 100644 --- a/plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/tasks/GenerateBaselineTask.kt +++ b/plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/tasks/GenerateBaselineTask.kt @@ -1,6 +1,5 @@ package org.jlleitschuh.gradle.ktlint.tasks -import net.swiftzer.semver.SemVer import org.gradle.api.DefaultTask import org.gradle.api.Task import org.gradle.api.file.ConfigurableFileCollection @@ -50,28 +49,20 @@ abstract class GenerateBaselineTask @Inject constructor( super.onlyIf(spec) } - init { - onlyIf { - val isEnabled = SemVer.parse(ktLintVersion.get()) >= SemVer(0, 41, 0) - if (!isEnabled) logger.warn("Generate baseline only works starting from KtLint 0.41.0 version") - isEnabled - } - } - @Suppress("UnstableApiUsage") @TaskAction fun generateBaseline() { // Classloader isolation is enough here as we just want to use some classes from KtLint classpath // to get errors and generate files/console reports. No KtLint main object is initialized/used in this case. - val queue = workerExecutor.classLoaderIsolation { spec -> - spec.classpath.from(ktLintClasspath, baselineReporterClasspath) + val queue = workerExecutor.classLoaderIsolation { + classpath.from(ktLintClasspath, baselineReporterClasspath) } - - queue.submit(GenerateBaselineWorkAction::class.java) { param -> - param.discoveredErrors.setFrom(discoveredErrors) - param.ktLintVersion.set(ktLintVersion) - param.baselineFile.set(baselineFile) - param.projectDirectory.set(projectLayout.projectDirectory) + val task = this + queue.submit(GenerateBaselineWorkAction::class.java) { + discoveredErrors.setFrom(task.discoveredErrors) + ktLintVersion.set(task.ktLintVersion) + baselineFile.set(task.baselineFile) + projectDirectory.set(projectLayout.projectDirectory) } } diff --git a/plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/tasks/GenerateReportsTask.kt b/plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/tasks/GenerateReportsTask.kt index 934cace7..75077060 100644 --- a/plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/tasks/GenerateReportsTask.kt +++ b/plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/tasks/GenerateReportsTask.kt @@ -1,8 +1,6 @@ package org.jlleitschuh.gradle.ktlint.tasks -import net.swiftzer.semver.SemVer import org.gradle.api.DefaultTask -import org.gradle.api.GradleException import org.gradle.api.file.ConfigurableFileCollection import org.gradle.api.file.DirectoryProperty import org.gradle.api.file.ProjectLayout @@ -125,12 +123,10 @@ abstract class GenerateReportsTask @Inject constructor( @Suppress("UnstableApiUsage") @TaskAction fun generateReports() { - checkBaselineSupportedKtLintVersion() - // Classloader isolation is enough here as we just want to use some classes from KtLint classpath // to get errors and generate files/console reports. No KtLint main object is initialized/used in this case. - val queue = workerExecutor.classLoaderIsolation { spec -> - spec.classpath.from(ktLintClasspath, reportersClasspath) + val queue = workerExecutor.classLoaderIsolation { + classpath.from(ktLintClasspath, reportersClasspath) } val loadedReporters = loadLoadedReporters() @@ -138,31 +134,32 @@ abstract class GenerateReportsTask @Inject constructor( reportsOutputDirectory.file("${reportsName.get()}.${it.fileExtension}") } + val task = this loadedReporters.forEach { (loadedReporter, reporterOutput) -> - queue.submit(GenerateReportsWorkAction::class.java) { param -> - param.discoveredErrorsFile.set(discoveredErrors) - param.loadedReporterProviders.set(loadedReporterProviders) - param.reporterId.set(loadedReporter.reporterId) - param.reporterOutput.set(reporterOutput) - param.reporterOptions.set(generateReporterOptions(loadedReporter)) - param.ktLintVersion.set(ktLintVersion) - param.baseline.set(baseline) - param.projectDirectory.set(projectLayout.projectDirectory) - if (relative.get()) { - param.filePathsRelativeTo.set(rootDir) + queue.submit(GenerateReportsWorkAction::class.java) { + discoveredErrorsFile.set(task.discoveredErrors) + loadedReporterProviders.set(task.loadedReporterProviders) + reporterId.set(loadedReporter.reporterId) + this.reporterOutput.set(reporterOutput) + reporterOptions.set(generateReporterOptions(loadedReporter)) + ktLintVersion.set(task.ktLintVersion) + baseline.set(task.baseline) + projectDirectory.set(task.projectLayout.projectDirectory) + if (task.relative.get()) { + filePathsRelativeTo.set(rootDir) } } } - queue.submit(ConsoleReportWorkAction::class.java) { param -> - param.discoveredErrors.set(discoveredErrors) - param.outputToConsole.set(outputToConsole) - param.ignoreFailures.set(ignoreFailures) - param.verbose.set(verbose) - param.generatedReportsPaths.from(loadedReporters.values) - param.ktLintVersion.set(ktLintVersion) - param.baseline.set(baseline) - param.projectDirectory.set(projectLayout.projectDirectory) + queue.submit(ConsoleReportWorkAction::class.java) { + discoveredErrors.set(task.discoveredErrors) + outputToConsole.set(task.outputToConsole) + ignoreFailures.set(task.ignoreFailures) + verbose.set(task.verbose) + generatedReportsPaths.from(loadedReporters.values) + ktLintVersion.set(task.ktLintVersion) + baseline.set(task.baseline) + projectDirectory.set(projectLayout.projectDirectory) } } @@ -190,12 +187,6 @@ abstract class GenerateReportsTask @Inject constructor( return options.toMap() } - private fun checkBaselineSupportedKtLintVersion() { - if (baseline.isPresent && SemVer.parse(ktLintVersion.get()) < SemVer(0, 41, 0)) { - throw GradleException("Baseline support is only enabled for KtLint versions 0.41.0+.") - } - } - internal enum class LintType( val suffix: String ) { diff --git a/plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/tasks/LoadReportersTask.kt b/plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/tasks/LoadReportersTask.kt index 30314fb6..4f4ca497 100644 --- a/plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/tasks/LoadReportersTask.kt +++ b/plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/tasks/LoadReportersTask.kt @@ -63,22 +63,23 @@ internal abstract class LoadReportersTask @Inject constructor( // Classloader isolation is enough here as we just want to use some classes from KtLint classpath // to load reporters. No KtLint main object is initialized/used in this case. - val queue = workerExecutor.classLoaderIsolation { spec -> - spec.classpath.from(ktLintClasspath, reportersClasspath) + val queue = workerExecutor.classLoaderIsolation { + classpath.from(ktLintClasspath, reportersClasspath) } - queue.submit(LoadReportersWorkAction::class.java) { param -> - param.debug.set(debug) - param.enabledReporters.set( - enabledReporters + queue.submit(LoadReportersWorkAction::class.java) { + val task = this@LoadReportersTask + debug.set(task.debug) + enabledReporters.set( + task.enabledReporters .map { reporters -> reporters.filter { it.isAvailable() } } ) - param.customReporters.set(customReporters) - param.loadedReporters.set(loadedReporters) - param.loadedReporterProviders.set(loadedReporterProviders) - param.ktLintVersion.set(ktLintVersion) + customReporters.set(task.customReporters) + loadedReporters.set(task.loadedReporters) + loadedReporterProviders.set(task.loadedReporterProviders) + ktLintVersion.set(task.ktLintVersion) } } diff --git a/plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/worker/KtLintWorkAction.kt b/plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/worker/KtLintWorkAction.kt index 86e54a25..d0a6fc46 100644 --- a/plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/worker/KtLintWorkAction.kt +++ b/plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/worker/KtLintWorkAction.kt @@ -24,21 +24,11 @@ abstract class KtLintWorkAction : WorkAction() val formattedFiles = mutableMapOf() - if (parameters.additionalEditorconfigFile.isPresent && - parameters.ktLintVersion.map { SemVer.parse(it) }.get() >= SemVer(0, 47) - ) { - logger.warn("additionalEditorconfigFile no longer supported in ktlint 0.47+") - } if (parameters.additionalEditorconfig.isPresent && parameters.additionalEditorconfig.get().isNotEmpty() && parameters.ktLintVersion.map { SemVer.parse(it) }.get() < SemVer(0, 49) @@ -48,31 +38,9 @@ abstract class KtLintWorkAction : WorkAction { - ktlintInvokerFactory.initialize( - editorConfigPath = additionalEditorConfig, - - parameters.enableExperimental.getOrElse(false), - parameters.disabledRules.getOrElse(emptySet()), - - userData = userData, - debug = debug - ) - } - - is KtLintInvocation46.Factory -> { - ktlintInvokerFactory.initialize( - editorConfigPath = additionalEditorConfig, - enableExperimental = parameters.enableExperimental.getOrElse(false), - disabledRules = parameters.disabledRules.getOrElse(emptySet()), - userData = userData, - debug = debug - ) - } - is KtLintInvocation47.Factory -> { ktlintInvokerFactory.initialize( - editorConfigPath = additionalEditorConfig, + editorConfigPath = null, userData = userData, debug = debug, parameters.enableExperimental.getOrElse(false), @@ -173,7 +141,6 @@ abstract class KtLintWorkAction : WorkAction val enableExperimental: Property val debug: Property - val additionalEditorconfigFile: RegularFileProperty val additionalEditorconfig: MapProperty val formatSource: Property val discoveredErrorsFile: RegularFileProperty diff --git a/plugin/src/test/kotlin/org/jlleitschuh/gradle/ktlint/ConfigurationCacheTest.kt b/plugin/src/test/kotlin/org/jlleitschuh/gradle/ktlint/ConfigurationCacheTest.kt index df21eb13..112f8e0b 100644 --- a/plugin/src/test/kotlin/org/jlleitschuh/gradle/ktlint/ConfigurationCacheTest.kt +++ b/plugin/src/test/kotlin/org/jlleitschuh/gradle/ktlint/ConfigurationCacheTest.kt @@ -47,11 +47,7 @@ class ConfigurationCacheTest : AbstractPluginTest() { @CommonTest fun configurationCacheForFormatTasks(gradleVersion: GradleVersion) { project(gradleVersion) { - val sourceFile = "\nval foo = \"bar\"\n" - createSourceFile( - "src/main/kotlin/CleanSource.kt", - sourceFile - ) + withCleanSources() val formatTaskName = KtLintFormatTask.buildTaskNameForSourceSet("main") build( configurationCacheFlag, @@ -92,11 +88,7 @@ class ConfigurationCacheTest : AbstractPluginTest() { } """.trimIndent() ) - val sourceFile = "\nval foo = \"bar\"\n" - createSourceFile( - "src/main/kotlin/CleanSource.kt", - sourceFile - ) + withCleanSources() val formatTaskName = KtLintFormatTask.buildTaskNameForSourceSet("main") build( configurationCacheFlag, diff --git a/plugin/src/test/kotlin/org/jlleitschuh/gradle/ktlint/DisabledRulesTest.kt b/plugin/src/test/kotlin/org/jlleitschuh/gradle/ktlint/DisabledRulesTest.kt index 7c797317..14074344 100644 --- a/plugin/src/test/kotlin/org/jlleitschuh/gradle/ktlint/DisabledRulesTest.kt +++ b/plugin/src/test/kotlin/org/jlleitschuh/gradle/ktlint/DisabledRulesTest.kt @@ -5,11 +5,9 @@ import org.assertj.core.api.Assertions.assertThat import org.gradle.api.logging.Logging import org.gradle.testkit.runner.TaskOutcome import org.gradle.util.GradleVersion -import org.jlleitschuh.gradle.ktlint.tasks.KtLintCheckTask import org.jlleitschuh.gradle.ktlint.testdsl.CommonTest import org.jlleitschuh.gradle.ktlint.testdsl.GradleTestVersions import org.jlleitschuh.gradle.ktlint.testdsl.build -import org.jlleitschuh.gradle.ktlint.testdsl.buildAndFail import org.jlleitschuh.gradle.ktlint.testdsl.project import org.junit.jupiter.api.DisplayName import org.junit.jupiter.params.ParameterizedTest @@ -40,13 +38,7 @@ class DisabledRulesTest : AbstractPluginTest() { "val foo = \"bar\"" ) - if (SemVer.parse(ktLintVersion) < SemVer.parse("0.34.2")) { - buildAndFail(CHECK_PARENT_TASK_NAME) { - assertThat(task(":runKtlintCheckOverMainSourceSet")?.outcome) - .`as`("Rules disabling is supported since 0.34.2 ktlint version") - .isEqualTo(TaskOutcome.FAILED) - } - } else if (SemVer.parse(ktLintVersion) < SemVer.parse("0.48.0")) { + if (SemVer.parse(ktLintVersion) < SemVer.parse("0.48.0")) { build(CHECK_PARENT_TASK_NAME) { assertThat(task(":$mainSourceSetCheckTaskName")?.outcome).isEqualTo(TaskOutcome.SUCCESS) assertThat(output).doesNotContain("Property 'ktlint_disabled_rules' is deprecated") @@ -69,55 +61,43 @@ class DisabledRulesTest : AbstractPluginTest() { @ParameterizedTest(name = "{0} with KtLint {1}: {displayName}") @ArgumentsSource(KtLintSupportedVersionsTest.SupportedKtlintVersionsProvider::class) fun lintDisabledRuleFinalNewlineEditorconfig(gradleVersion: GradleVersion, ktLintVersion: String) { - if (SemVer.parse(ktLintVersion) >= SemVer.parse("0.34.2")) { - // Rules disabling is supported since 0.34.2 ktlint version - project(gradleVersion) { - if (SemVer.parse(ktLintVersion) >= SemVer.parse("0.48.0")) { - // new way of disabling rules introduced in 0.48 - editorConfig.appendText( - """ + project(gradleVersion) { + if (SemVer.parse(ktLintVersion) >= SemVer.parse("0.48.0")) { + // new way of disabling rules introduced in 0.48 + editorConfig.appendText( + """ root = true [*.kt] ktlint_standard_final-newline = disabled - """.trimIndent() - ) - } else if (SemVer.parse(ktLintVersion) >= SemVer.parse("0.47.0")) { - // disabled rules property renamed in 0.47 (disabled_rules is still honored, but will print a warning) - editorConfig.appendText( - """ + """.trimIndent() + ) + } else { + // disabled rules property renamed in 0.47 (disabled_rules is still honored, but will print a warning) + editorConfig.appendText( + """ root = true [*.kt] ktlint_disabled_rules = final-newline - """.trimIndent() - ) - } else { - editorConfig.appendText( - """ - root = true - - [*.kt] - disabled_rules = final-newline - """.trimIndent() - ) - } - //language=Groovy - buildGradle.appendText( - """ - ktlint.version = "$ktLintVersion" """.trimIndent() ) + } + //language=Groovy + buildGradle.appendText( + """ + ktlint.version = "$ktLintVersion" + """.trimIndent() + ) - createSourceFile( - "src/main/kotlin/CleanSource.kt", - "val foo = \"bar\"" - ) + createSourceFile( + "src/main/kotlin/CleanSource.kt", + "val foo = \"bar\"" + ) - build(CHECK_PARENT_TASK_NAME) { - assertThat(task(":$mainSourceSetCheckTaskName")?.outcome).isEqualTo(TaskOutcome.SUCCESS) - assertThat(output).doesNotContain("Property 'ktlint_disabled_rules' is deprecated") - assertThat(output).doesNotContain("Property 'disabled_rules' is deprecated") - } + build(CHECK_PARENT_TASK_NAME) { + assertThat(task(":$mainSourceSetCheckTaskName")?.outcome).isEqualTo(TaskOutcome.SUCCESS) + assertThat(output).doesNotContain("Property 'ktlint_disabled_rules' is deprecated") + assertThat(output).doesNotContain("Property 'disabled_rules' is deprecated") } } } @@ -129,7 +109,7 @@ class DisabledRulesTest : AbstractPluginTest() { //language=Groovy buildGradle.appendText( """ - + ktlint.version = "0.47.1" ktlint.disabledRules = ["final-newline", "no-consecutive-blank-lines"] """.trimIndent() ) @@ -156,6 +136,12 @@ class DisabledRulesTest : AbstractPluginTest() { @CommonTest fun lintRuleDisabledInTheCode(gradleVersion: GradleVersion) { project(gradleVersion) { + //language=Groovy + buildGradle.appendText( + """ + ktlint.version = "0.47.1" + """.trimIndent() + ) createSourceFile( "src/main/kotlin/CleanSource.kt", """ @@ -177,28 +163,4 @@ class DisabledRulesTest : AbstractPluginTest() { } } } - - @DisplayName("Should fail if KtLint version is lower then 0.34.2 and disabled rules configuration is set") - @CommonTest - fun lintShouldFailOnUnsupportedVersion(gradleVersion: GradleVersion) { - project(gradleVersion) { - //language=Groovy - buildGradle.appendText( - """ - - ktlint.version = "0.34.0" - ktlint.disabledRules = ["final-newline"] - """.trimIndent() - ) - - withCleanSources() - - buildAndFail(CHECK_PARENT_TASK_NAME) { - assertThat( - task(":${KtLintCheckTask.buildTaskNameForSourceSet("main")}")?.outcome - ).isEqualTo(TaskOutcome.FAILED) - assertThat(output).contains("Rules disabling is supported since 0.34.2 ktlint version.") - } - } - } } diff --git a/plugin/src/test/kotlin/org/jlleitschuh/gradle/ktlint/KtLintSupportedVersionsTest.kt b/plugin/src/test/kotlin/org/jlleitschuh/gradle/ktlint/KtLintSupportedVersionsTest.kt index 1d9e472e..9ecd938e 100644 --- a/plugin/src/test/kotlin/org/jlleitschuh/gradle/ktlint/KtLintSupportedVersionsTest.kt +++ b/plugin/src/test/kotlin/org/jlleitschuh/gradle/ktlint/KtLintSupportedVersionsTest.kt @@ -6,13 +6,11 @@ import org.gradle.testkit.runner.TaskOutcome import org.gradle.util.GradleVersion import org.jlleitschuh.gradle.ktlint.testdsl.GradleArgumentsProvider import org.jlleitschuh.gradle.ktlint.testdsl.GradleTestVersions -import org.jlleitschuh.gradle.ktlint.testdsl.TestProject import org.jlleitschuh.gradle.ktlint.testdsl.TestVersions import org.jlleitschuh.gradle.ktlint.testdsl.build import org.jlleitschuh.gradle.ktlint.testdsl.buildAndFail import org.jlleitschuh.gradle.ktlint.testdsl.project import org.junit.jupiter.api.DisplayName -import org.junit.jupiter.api.condition.OS import org.junit.jupiter.api.extension.ExtensionContext import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.Arguments @@ -72,39 +70,6 @@ class KtLintSupportedVersionsTest : AbstractPluginTest() { } } - @DisplayName("Lint should use editorconfig file override") - @ParameterizedTest(name = "{0} with KtLint {1}: {displayName}") - @ArgumentsSource(SupportedKtlintVersionsProvider::class) - internal fun `Lint should use editorconfig file override`( - gradleVersion: GradleVersion, - ktLintVersion: String - ) { - project(gradleVersion) { - //language=Groovy - buildGradle.appendText( - """ - - ktlint.version = "$ktLintVersion" - ktlint.additionalEditorconfigFile = project.file("${TestProject.ADDITIONAL_EDITOR_CONFIG}/.editorconfig") - """.trimIndent() - ) - withAdditionalEditorConfig() - withFailingSources() - if (SemVer.parse(ktLintVersion) >= SemVer(0, 47)) { - buildAndFail(CHECK_PARENT_TASK_NAME) { - assertThat(task(":$mainSourceSetCheckTaskName")?.outcome).isEqualTo(TaskOutcome.FAILED) - assertThat(output).contains("additionalEditorconfigFile no longer supported in ktlint 0.47+") - assertThat(output).doesNotContain("additionalEditorconfig not supported until ktlint 0.49") - } - } else { - build(CHECK_PARENT_TASK_NAME) { - assertThat(task(":$mainSourceSetCheckTaskName")?.outcome).isEqualTo(TaskOutcome.SUCCESS) - assertThat(output).doesNotContain("additionalEditorconfig not supported until ktlint 0.49") - } - } - } - } - @DisplayName("Lint should use editorconfig override (standard rule)") @ParameterizedTest(name = "{0} with KtLint {1}: {displayName}") @ArgumentsSource(SupportedKtlintVersionsProvider::class) @@ -208,25 +173,6 @@ class KtLintSupportedVersionsTest : AbstractPluginTest() { class SupportedKtlintVersionsProvider : GradleArgumentsProvider() { private val supportedKtlintVersions = mutableListOf( - "0.34.0", - "0.34.2", - "0.35.0", - "0.36.0", - "0.37.1", - "0.37.2", - "0.38.0", - "0.38.1", - "0.39.0", - "0.40.0", - "0.41.0", - "0.42.0", - "0.42.1", - // "0.43.0" does not work on JDK1.8 - // "0.43.1" asked not to use it - "0.43.2", - "0.44.0", - "0.45.2", - "0.46.1", "0.47.1", "0.48.0", "0.48.1", @@ -234,11 +180,9 @@ class KtLintSupportedVersionsTest : AbstractPluginTest() { // "0.49.0" did not expose needed baseline classes "0.49.1", "0.50.0", - "1.0.0" - ).also { - // "0.37.0" is failing on Windows machines that is fixed in the next version - if (!OS.WINDOWS.isCurrentOs) it.add("0.37.0") - } + "1.0.0", + "1.0.1" + ) override fun provideArguments( context: ExtensionContext diff --git a/plugin/src/test/kotlin/org/jlleitschuh/gradle/ktlint/KtlintBaselineSupportTest.kt b/plugin/src/test/kotlin/org/jlleitschuh/gradle/ktlint/KtlintBaselineSupportTest.kt index 43be8fed..1677a87f 100644 --- a/plugin/src/test/kotlin/org/jlleitschuh/gradle/ktlint/KtlintBaselineSupportTest.kt +++ b/plugin/src/test/kotlin/org/jlleitschuh/gradle/ktlint/KtlintBaselineSupportTest.kt @@ -1,6 +1,5 @@ package org.jlleitschuh.gradle.ktlint -import net.swiftzer.semver.SemVer import org.assertj.core.api.Assertions.assertThat import org.gradle.testkit.runner.TaskOutcome import org.gradle.util.GradleVersion @@ -59,13 +58,12 @@ class KtlintBaselineSupportTest : AbstractPluginTest() { | | | - | - | + | | | - | - | - | + | + | + | | | | @@ -101,49 +99,23 @@ class KtlintBaselineSupportTest : AbstractPluginTest() { } } - @DisplayName("Generate baseline task should work only when KtLint version is higher then 0.41.0") - @CommonTest - fun generateBaselineMinVersion(gradleVersion: GradleVersion) { - project(gradleVersion) { - withFailingSources() - - //language=Groovy - buildGradle.appendText( - """ - - ktlint { - version.set("0.40.0") - } - """.trimIndent() - ) - - build(GenerateBaselineTask.NAME) { - assertThat(task(":${GenerateBaselineTask.NAME}")?.outcome).isEqualTo(TaskOutcome.SKIPPED) - assertThat(output).containsSequence("Generate baseline only works starting from KtLint 0.41.0 version") - } - } - } - @DisplayName("Should consider existing issues in baseline") @ParameterizedTest(name = "{0} with KtLint {1}: {displayName}") @ArgumentsSource(KtLintSupportedVersionsTest.SupportedKtlintVersionsProvider::class) fun existingIssueFilteredByBaseline(gradleVersion: GradleVersion, ktLintVersion: String) { - if (SemVer.parse(ktLintVersion) >= SemVer(0, 41, 0)) { - // baseline support was added in 0.41.0 - project(gradleVersion) { - //language=Groovy - buildGradle.appendText( - """ + project(gradleVersion) { + //language=Groovy + buildGradle.appendText( + """ ktlint.version = "$ktLintVersion" ktlint.debug = true - """.trimIndent() - ) - withFailingSources() + """.trimIndent() + ) + withFailingSources() - build(GenerateBaselineTask.NAME) - build(CHECK_PARENT_TASK_NAME) { - assertThat(task(":$mainSourceSetCheckTaskName")?.outcome).isEqualTo(TaskOutcome.SUCCESS) - } + build(GenerateBaselineTask.NAME) + build(CHECK_PARENT_TASK_NAME) { + assertThat(task(":$mainSourceSetCheckTaskName")?.outcome).isEqualTo(TaskOutcome.SUCCESS) } } } @@ -162,30 +134,6 @@ class KtlintBaselineSupportTest : AbstractPluginTest() { } } - @DisplayName("Should fail the build if baseline file is present and ktlint version is less then 0.41.0") - @CommonTest - fun failBuildOnOldKtlintVersionsAndBaselinePresent(gradleVersion: GradleVersion) { - project(gradleVersion) { - withCleanSources() - build(GenerateBaselineTask.NAME) - - //language=Groovy - buildGradle.appendText( - """ - - ktlint { - version.set("0.40.0") - } - """.trimIndent() - ) - - buildAndFail(CHECK_PARENT_TASK_NAME) { - assertThat(task(":$mainSourceSetCheckTaskName")?.outcome).isEqualTo(TaskOutcome.FAILED) - assertThat(output).contains("Baseline support is only enabled for KtLint versions 0.41.0+.") - } - } - } - private val File.defaultBaselineFile get() = resolve("config") .resolve("ktlint") diff --git a/plugin/src/test/kotlin/org/jlleitschuh/gradle/ktlint/KtlintIdeaPluginTest.kt b/plugin/src/test/kotlin/org/jlleitschuh/gradle/ktlint/KtlintIdeaPluginTest.kt deleted file mode 100644 index 513924bb..00000000 --- a/plugin/src/test/kotlin/org/jlleitschuh/gradle/ktlint/KtlintIdeaPluginTest.kt +++ /dev/null @@ -1,54 +0,0 @@ -package org.jlleitschuh.gradle.ktlint - -import org.assertj.core.api.Assertions.assertThat -import org.gradle.util.GradleVersion -import org.jlleitschuh.gradle.ktlint.testdsl.TestVersions -import org.jlleitschuh.gradle.ktlint.testdsl.build -import org.jlleitschuh.gradle.ktlint.testdsl.project -import org.junit.jupiter.api.DisplayName -import org.junit.jupiter.api.Test - -class KtlintIdeaPluginTest : AbstractPluginTest() { - - @DisplayName("Applying helper plugin does not add KtLint check task") - @Test - fun applyDoesNotAddCheckTask() { - project( - GradleVersion.version(TestVersions.maxSupportedGradleVersion), - projectSetup = { - //language=Groovy - it.resolve("settings.gradle").writeText( - """ - pluginManagement { - repositories { - mavenLocal() - gradlePluginPortal() - } - - plugins { - id 'org.jetbrains.kotlin.jvm' version '${TestVersions.maxSupportedKotlinPluginVersion()}' - id 'org.jlleitschuh.gradle.ktlint-idea' version '${TestVersions.pluginVersion}' - } - } - """.trimIndent() - ) - - //language=Groovy - it.resolve("build.gradle").writeText( - """ - plugins { - id 'org.jetbrains.kotlin.jvm' - id 'org.jlleitschuh.gradle.ktlint-idea' - } - """.trimIndent() - ) - } - ) { - build(":tasks") { - assertThat(output).doesNotContain(CHECK_PARENT_TASK_NAME) - // With space to not interfere with ktlintApplyToIdeaGlobally tasks - assertThat(output).containsIgnoringCase(APPLY_TO_IDEA_TASK_NAME) - } - } - } -} diff --git a/plugin/src/test/kotlin/org/jlleitschuh/gradle/ktlint/KtlintPluginTest.kt b/plugin/src/test/kotlin/org/jlleitschuh/gradle/ktlint/KtlintPluginTest.kt index 1ff5f3ff..47253ce5 100644 --- a/plugin/src/test/kotlin/org/jlleitschuh/gradle/ktlint/KtlintPluginTest.kt +++ b/plugin/src/test/kotlin/org/jlleitschuh/gradle/ktlint/KtlintPluginTest.kt @@ -45,86 +45,6 @@ class KtlintPluginTest : AbstractPluginTest() { } } - @DisplayName("Should generate code style files in project < 0.47.0") - @CommonTest - fun generateIdeaCodeStyle(gradleVersion: GradleVersion) { - project(gradleVersion) { - buildGradle.appendText( - """ - ktlint.version = "0.46.1" - - """.trimIndent() - ) - withCleanSources() - val ideaRootDir = projectPath.resolve(".idea").apply { mkdir() } - - build(APPLY_TO_IDEA_TASK_NAME) { - assertThat(task(":$APPLY_TO_IDEA_TASK_NAME")?.outcome).isEqualTo(TaskOutcome.SUCCESS) - assertThat(ideaRootDir.listFiles()?.isNullOrEmpty()).isFalse() - } - } - } - - @DisplayName("Should not generate code style files in project >= 0.47.0") - @CommonTest - fun generateIdeaCodeStyleNew(gradleVersion: GradleVersion) { - project(gradleVersion) { - buildGradle.appendText( - """ - ktlint.version = "0.47.1" - - """.trimIndent() - ) - withCleanSources() - val ideaRootDir = projectPath.resolve(".idea").apply { mkdir() } - - build(APPLY_TO_IDEA_TASK_NAME) { - assertThat(task(":$APPLY_TO_IDEA_TASK_NAME")?.outcome).isEqualTo(TaskOutcome.SUCCESS) - assertThat(output).contains("Skipping ktlintApplyToIdea. The applyToIDEA functionality was removed from ktlint in 0.47.0.") - assertThat(ideaRootDir.listFiles()?.isNullOrEmpty()).isTrue() - } - } - } - - @DisplayName("Should generate code style file globally < 0.47.0") - @CommonTest - fun generateIdeaCodeStyleGloballyOld(gradleVersion: GradleVersion) { - project(gradleVersion) { - buildGradle.appendText( - """ - ktlint.version = "0.46.1" - - """.trimIndent() - ) - val ideaRootDir = projectPath.resolve(".idea").apply { mkdir() } - - build(APPLY_TO_IDEA_GLOBALLY_TASK_NAME) { - assertThat(task(":$APPLY_TO_IDEA_GLOBALLY_TASK_NAME")?.outcome).isEqualTo(TaskOutcome.SUCCESS) - assertThat(ideaRootDir.listFiles()?.isNullOrEmpty()).isFalse() - } - } - } - - @DisplayName("Should not generate code style file globally >= 0.47.0") - @CommonTest - fun generateIdeaCodeStyleGloballyNew(gradleVersion: GradleVersion) { - project(gradleVersion) { - buildGradle.appendText( - """ - ktlint.version = "0.47.1" - - """.trimIndent() - ) - val ideaRootDir = projectPath.resolve(".idea").apply { mkdir() } - - build(APPLY_TO_IDEA_GLOBALLY_TASK_NAME) { - assertThat(task(":$APPLY_TO_IDEA_GLOBALLY_TASK_NAME")?.outcome).isEqualTo(TaskOutcome.SUCCESS) - assertThat(output).contains("Skipping ktlintApplyToIdeaGlobally. The applyToIDEA functionality was removed from ktlint in 0.47.0.") - assertThat(ideaRootDir.listFiles()?.isNullOrEmpty()).isTrue() - } - } - } - @DisplayName("Should show only plugin meta tasks in task output") @CommonTest fun showOnlyMetaTasks(gradleVersion: GradleVersion) { @@ -137,11 +57,9 @@ class KtlintPluginTest : AbstractPluginTest() { .filter { it.startsWith("ktlint", ignoreCase = true) } .toList() - assertThat(ktlintTasks).hasSize(5) + assertThat(ktlintTasks).hasSize(3) assertThat(ktlintTasks).anyMatch { it.startsWith(CHECK_PARENT_TASK_NAME) } assertThat(ktlintTasks).anyMatch { it.startsWith(FORMAT_PARENT_TASK_NAME) } - assertThat(ktlintTasks).anyMatch { it.startsWith(APPLY_TO_IDEA_TASK_NAME) } - assertThat(ktlintTasks).anyMatch { it.startsWith(APPLY_TO_IDEA_GLOBALLY_TASK_NAME) } assertThat(ktlintTasks).anyMatch { it.startsWith(GenerateBaselineTask.NAME) } } } @@ -159,11 +77,9 @@ class KtlintPluginTest : AbstractPluginTest() { // Plus for main and test sources format and check tasks // Plus two kotlin script tasks - assertThat(ktlintTasks).hasSize(11) + assertThat(ktlintTasks).hasSize(9) assertThat(ktlintTasks).anyMatch { it.startsWith(CHECK_PARENT_TASK_NAME) } assertThat(ktlintTasks).anyMatch { it.startsWith(FORMAT_PARENT_TASK_NAME) } - assertThat(ktlintTasks).anyMatch { it.startsWith(APPLY_TO_IDEA_TASK_NAME) } - assertThat(ktlintTasks).anyMatch { it.startsWith(APPLY_TO_IDEA_GLOBALLY_TASK_NAME) } assertThat(ktlintTasks).anyMatch { it.startsWith(kotlinScriptCheckTaskName) } assertThat(ktlintTasks).anyMatch { it.startsWith( @@ -451,7 +367,7 @@ class KtlintPluginTest : AbstractPluginTest() { """ ktlint.enableExperimentalRules = true - ktlint.version = "0.34.0" + ktlint.version = "0.47.1" """.trimIndent() ) @@ -671,13 +587,13 @@ class KtlintPluginTest : AbstractPluginTest() { """ dependencies { - $KTLINT_RULESET_CONFIGURATION_NAME "com.pinterest.ktlint:ktlint-core:0.34.2" + $KTLINT_RULESET_CONFIGURATION_NAME "com.pinterest.ktlint:ktlint-cli-ruleset-core:1.0.0" } """.trimIndent() ) build(":dependencies", "--configuration", KTLINT_RULESET_CONFIGURATION_NAME) { - assertThat(output).contains("com.pinterest.ktlint:ktlint-core:0.34.2 -> 0.47.1") + assertThat(output).contains("com.pinterest.ktlint:ktlint-cli-ruleset-core:1.0.0 -> 1.0.1") } } } @@ -693,13 +609,13 @@ class KtlintPluginTest : AbstractPluginTest() { """ dependencies { - $KTLINT_REPORTER_CONFIGURATION_NAME "com.pinterest.ktlint:ktlint-core:0.34.2" + $KTLINT_REPORTER_CONFIGURATION_NAME "com.pinterest.ktlint:ktlint-cli-ruleset-core:1.0.0" } """.trimIndent() ) build(":dependencies", "--configuration", KTLINT_REPORTER_CONFIGURATION_NAME) { - assertThat(output).contains("com.pinterest.ktlint:ktlint-core:0.34.2 -> 0.47.1") + assertThat(output).contains("com.pinterest.ktlint:ktlint-cli-ruleset-core:1.0.0 -> 1.0.1") } } } diff --git a/plugin/src/test/kotlin/org/jlleitschuh/gradle/ktlint/KtlintPluginVersionTest.kt b/plugin/src/test/kotlin/org/jlleitschuh/gradle/ktlint/KtlintPluginVersionTest.kt index 7c0d0751..a169e9f0 100644 --- a/plugin/src/test/kotlin/org/jlleitschuh/gradle/ktlint/KtlintPluginVersionTest.kt +++ b/plugin/src/test/kotlin/org/jlleitschuh/gradle/ktlint/KtlintPluginVersionTest.kt @@ -28,12 +28,12 @@ class KtlintPluginVersionTest : AbstractPluginTest() { ) } - @DisplayName("Should allow to use KtLint version 0.34.0") + @DisplayName("Should allow to use KtLint version 0.47.1") @CommonTest fun allowSupportedMinimalKtLintVersion(gradleVersion: GradleVersion) { project(gradleVersion) { withCleanSources() - buildGradle.useKtlintVersion("0.34.0") + buildGradle.useKtlintVersion("0.47.1") build(CHECK_PARENT_TASK_NAME) { assertThat(task(":$mainSourceSetCheckTaskName")?.outcome).isEqualTo(TaskOutcome.SUCCESS) @@ -41,12 +41,12 @@ class KtlintPluginVersionTest : AbstractPluginTest() { } } - @DisplayName("Should fail the build on using KtLint version <0.34.0") + @DisplayName("Should fail the build on using KtLint version <0.47.0") @CommonTest fun failOnUnsupportedOldKtLintVersion(gradleVersion: GradleVersion) { project(gradleVersion) { withCleanSources() - buildGradle.useKtlintVersion("0.33.0") + buildGradle.useKtlintVersion("0.46.1") buildAndFail(CHECK_PARENT_TASK_NAME) { assertThat(task(":${LoadReportersTask.TASK_NAME}")?.outcome).isEqualTo(TaskOutcome.FAILED) } diff --git a/plugin/src/test/kotlin/org/jlleitschuh/gradle/ktlint/ReportersTest.kt b/plugin/src/test/kotlin/org/jlleitschuh/gradle/ktlint/ReportersTest.kt index 15bb6c50..8adb26ff 100644 --- a/plugin/src/test/kotlin/org/jlleitschuh/gradle/ktlint/ReportersTest.kt +++ b/plugin/src/test/kotlin/org/jlleitschuh/gradle/ktlint/ReportersTest.kt @@ -11,8 +11,6 @@ import org.jlleitschuh.gradle.ktlint.testdsl.build import org.jlleitschuh.gradle.ktlint.testdsl.buildAndFail import org.jlleitschuh.gradle.ktlint.testdsl.project import org.junit.jupiter.api.DisplayName -import org.junit.jupiter.api.condition.DisabledOnOs -import org.junit.jupiter.api.condition.OS @GradleTestVersions class ReportersTest : AbstractPluginTest() { @@ -208,31 +206,6 @@ class ReportersTest : AbstractPluginTest() { } } - @DisplayName("Should ignore html reporter on KtLint versions less then 0.36.0") - @CommonTest - @DisabledOnOs(OS.WINDOWS) - internal fun ignoreHtmlOnOldVersions(gradleVersion: GradleVersion) { - project(gradleVersion) { - withCleanSources() - - //language=Groovy - buildGradle.appendText( - """ - - ktlint.version = "0.35.0" - ktlint.reporters { - reporter "html" - } - """.trimIndent() - ) - - build(CHECK_PARENT_TASK_NAME) { - assertThat(task(":$mainSourceSetCheckTaskName")?.outcome).isEqualTo(TaskOutcome.SUCCESS) - assertReportNotCreated(ReporterType.HTML.fileExtension, mainSourceSetCheckTaskName) - } - } - } - @DisplayName("Should allow to set custom location for generated reports") @CommonTest internal fun customReportsLocation(gradleVersion: GradleVersion) { diff --git a/plugin/src/test/kotlin/org/jlleitschuh/gradle/ktlint/UnsupportedGradleTest.kt b/plugin/src/test/kotlin/org/jlleitschuh/gradle/ktlint/UnsupportedGradleTest.kt index 4037623c..13913896 100644 --- a/plugin/src/test/kotlin/org/jlleitschuh/gradle/ktlint/UnsupportedGradleTest.kt +++ b/plugin/src/test/kotlin/org/jlleitschuh/gradle/ktlint/UnsupportedGradleTest.kt @@ -14,7 +14,7 @@ class UnsupportedGradleTest : AbstractPluginTest() { @Test @DisabledOnOs(OS.WINDOWS) internal fun errorOnOldGradleVersion() { - project(GradleVersion.version("5.6.4")) { + project(GradleVersion.version("6.9.2")) { buildAndFail(CHECK_PARENT_TASK_NAME) { assertThat(output).contains( "Current version of plugin supports minimal Gradle version: " + diff --git a/plugin/src/test/kotlin/org/jlleitschuh/gradle/ktlint/testdsl/TestAnnotations.kt b/plugin/src/test/kotlin/org/jlleitschuh/gradle/ktlint/testdsl/TestAnnotations.kt index 290f9bf0..e3416888 100644 --- a/plugin/src/test/kotlin/org/jlleitschuh/gradle/ktlint/testdsl/TestAnnotations.kt +++ b/plugin/src/test/kotlin/org/jlleitschuh/gradle/ktlint/testdsl/TestAnnotations.kt @@ -12,17 +12,10 @@ import kotlin.streams.asStream object TestVersions { const val minSupportedGradleVersion = KtlintBasePlugin.LOWEST_SUPPORTED_GRADLE_VERSION - const val maxSupportedGradleVersion = "8.1.1" + const val maxSupportedGradleVersion = "8.4" val pluginVersion = File("VERSION_CURRENT.txt").readText().trim() const val minSupportedKotlinPluginVersion = "1.4.32" - - fun maxSupportedKotlinPluginVersion( - gradleVersion: GradleVersion = GradleVersion.version(maxSupportedGradleVersion) - ): String = when (gradleVersion) { - in (GradleVersion.version("6.8.3")..GradleVersion.version(maxSupportedGradleVersion)) -> "1.8.10" - in (GradleVersion.version("6.7.1")..GradleVersion.version("7.1.1")) -> "1.7.21" - else -> minSupportedKotlinPluginVersion - } + const val maxSupportedKotlinPluginVersion = "1.9.10" } @Target(AnnotationTarget.FUNCTION, AnnotationTarget.CLASS) diff --git a/plugin/src/test/kotlin/org/jlleitschuh/gradle/ktlint/testdsl/TestDsl.kt b/plugin/src/test/kotlin/org/jlleitschuh/gradle/ktlint/testdsl/TestDsl.kt index a4ec48f0..2594d3ff 100644 --- a/plugin/src/test/kotlin/org/jlleitschuh/gradle/ktlint/testdsl/TestDsl.kt +++ b/plugin/src/test/kotlin/org/jlleitschuh/gradle/ktlint/testdsl/TestDsl.kt @@ -4,6 +4,7 @@ import org.gradle.testkit.runner.BuildResult import org.gradle.testkit.runner.GradleRunner import org.gradle.util.GradleVersion import org.jlleitschuh.gradle.ktlint.AbstractPluginTest +import org.jlleitschuh.gradle.ktlint.testdsl.TestVersions.maxSupportedKotlinPluginVersion import java.io.File fun AbstractPluginTest.project( @@ -154,14 +155,11 @@ fun TestProject.buildAndFail( fun defaultProjectSetup(gradleVersion: GradleVersion): (File) -> Unit = projectSetup("jvm", gradleVersion) -private val GradleVersion.supportedKotlinVersion - get() = TestVersions.maxSupportedKotlinPluginVersion(this) - fun projectSetup( kotlinPluginType: String, gradleVersion: GradleVersion ): (File) -> Unit = { - val kotlinPluginVersion = gradleVersion.supportedKotlinVersion + val kotlinPluginVersion = maxSupportedKotlinPluginVersion //language=Groovy it.resolve("build.gradle").writeText( """ diff --git a/samples/android-app/src/main/java/org/jlleitschuh/gradle/ktlint/android/ItemDetailActivity.kt b/samples/android-app/src/main/java/org/jlleitschuh/gradle/ktlint/android/ItemDetailActivity.kt index 8d0a0fd8..d09736de 100644 --- a/samples/android-app/src/main/java/org/jlleitschuh/gradle/ktlint/android/ItemDetailActivity.kt +++ b/samples/android-app/src/main/java/org/jlleitschuh/gradle/ktlint/android/ItemDetailActivity.kt @@ -44,10 +44,7 @@ class ItemDetailActivity : AppCompatActivity() { // Create the detail fragment and add it to the activity // using a fragment transaction. val arguments = Bundle() - arguments.putString( - ItemDetailFragment.ARG_ITEM_ID, - intent.getStringExtra(ItemDetailFragment.ARG_ITEM_ID) - ) + arguments.putString(ItemDetailFragment.ARG_ITEM_ID, intent.getStringExtra(ItemDetailFragment.ARG_ITEM_ID)) val fragment = ItemDetailFragment() fragment.arguments = arguments supportFragmentManager.beginTransaction() diff --git a/samples/android-app/src/main/java/org/jlleitschuh/gradle/ktlint/android/ItemDetailFragment.kt b/samples/android-app/src/main/java/org/jlleitschuh/gradle/ktlint/android/ItemDetailFragment.kt index 9d0de354..f2e1ccbb 100644 --- a/samples/android-app/src/main/java/org/jlleitschuh/gradle/ktlint/android/ItemDetailFragment.kt +++ b/samples/android-app/src/main/java/org/jlleitschuh/gradle/ktlint/android/ItemDetailFragment.kt @@ -15,7 +15,6 @@ import org.jlleitschuh.gradle.ktlint.android.dummy.DummyContent * on handsets. */ class ItemDetailFragment : Fragment() { - /** * The dummy content this fragment is presenting. */ @@ -40,7 +39,7 @@ class ItemDetailFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, - savedInstanceState: Bundle? + savedInstanceState: Bundle?, ): View? { viewBinding = ItemDetailBinding.inflate(inflater, container, false) diff --git a/samples/android-app/src/main/java/org/jlleitschuh/gradle/ktlint/android/ItemListActivity.kt b/samples/android-app/src/main/java/org/jlleitschuh/gradle/ktlint/android/ItemListActivity.kt index 56b1f868..22f1aeac 100644 --- a/samples/android-app/src/main/java/org/jlleitschuh/gradle/ktlint/android/ItemListActivity.kt +++ b/samples/android-app/src/main/java/org/jlleitschuh/gradle/ktlint/android/ItemListActivity.kt @@ -22,7 +22,6 @@ import org.jlleitschuh.gradle.ktlint.android.dummy.DummyContent * item details side-by-side using two vertical panes. */ class ItemListActivity : AppCompatActivity() { - private var viewBinding: ActivityItemListBinding? = null override fun onCreate(savedInstanceState: Bundle?) { @@ -46,28 +45,36 @@ class ItemListActivity : AppCompatActivity() { } class SimpleItemRecyclerViewAdapter( - private val mValues: List + private val mValues: List, ) : RecyclerView.Adapter() { - private val mOnClickListener: View.OnClickListener init { - mOnClickListener = View.OnClickListener { v -> - val item = v.tag as DummyContent.DummyItem - val intent = Intent(v.context, ItemDetailActivity::class.java).apply { - putExtra(ItemDetailFragment.ARG_ITEM_ID, item.id) + mOnClickListener = + View.OnClickListener { v -> + val item = v.tag as DummyContent.DummyItem + val intent = + Intent(v.context, ItemDetailActivity::class.java).apply { + putExtra(ItemDetailFragment.ARG_ITEM_ID, item.id) + } + v.context.startActivity(intent) } - v.context.startActivity(intent) - } } - override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { - val view = LayoutInflater.from(parent.context) - .inflate(R.layout.item_list_content, parent, false) + override fun onCreateViewHolder( + parent: ViewGroup, + viewType: Int, + ): ViewHolder { + val view = + LayoutInflater.from(parent.context) + .inflate(R.layout.item_list_content, parent, false) return ViewHolder(view) } - override fun onBindViewHolder(holder: ViewHolder, position: Int) { + override fun onBindViewHolder( + holder: ViewHolder, + position: Int, + ) { val item = mValues[position] holder.mIdView.text = item.id holder.mContentView.text = item.content diff --git a/samples/android-app/src/main/java/org/jlleitschuh/gradle/ktlint/android/dummy/DummyContent.kt b/samples/android-app/src/main/java/org/jlleitschuh/gradle/ktlint/android/dummy/DummyContent.kt index edcdc279..7974a04e 100644 --- a/samples/android-app/src/main/java/org/jlleitschuh/gradle/ktlint/android/dummy/DummyContent.kt +++ b/samples/android-app/src/main/java/org/jlleitschuh/gradle/ktlint/android/dummy/DummyContent.kt @@ -10,7 +10,6 @@ import java.util.HashMap * TODO: Replace all uses of this class before publishing your app. */ object DummyContent { - /** * An array of sample (dummy) items. */ diff --git a/samples/android-app/src/main/kotlin/org/jlleitschuh/gradle/ktlint/android/AlternativeSample.kt b/samples/android-app/src/main/kotlin/org/jlleitschuh/gradle/ktlint/android/AlternativeSample.kt index d46d6972..921fee7a 100644 --- a/samples/android-app/src/main/kotlin/org/jlleitschuh/gradle/ktlint/android/AlternativeSample.kt +++ b/samples/android-app/src/main/kotlin/org/jlleitschuh/gradle/ktlint/android/AlternativeSample.kt @@ -1,5 +1,3 @@ package org.jlleitschuh.gradle.ktlint.android -data class AlternativeSample( - val one: Int = 1 -) +data class AlternativeSample(val one: Int = 1) diff --git a/samples/kotlin-js/src/main/kotlin/org/jlleitschuh/gradle/ktlint/sample/js/Main.kt b/samples/kotlin-js/src/main/kotlin/org/jlleitschuh/gradle/ktlint/sample/js/Main.kt index bec537f3..0afc6cec 100644 --- a/samples/kotlin-js/src/main/kotlin/org/jlleitschuh/gradle/ktlint/sample/js/Main.kt +++ b/samples/kotlin-js/src/main/kotlin/org/jlleitschuh/gradle/ktlint/sample/js/Main.kt @@ -3,9 +3,11 @@ package org.jlleitschuh.gradle.ktlint.sample.js import kotlinx.browser.document import org.w3c.dom.Node -val secondDiv: dynamic = document.createElement("div").apply { - innerHTML = "

Hello second time!

" -} +val secondDiv: dynamic = + document.createElement("div") + .apply { + innerHTML = "

Hello second time!

" + } fun main() { val firstDiv = document.createElement("div").apply { innerHTML = "

Hello!

" } diff --git a/samples/kotlin-mpp-android/src/commonMain/kotlin/org/jlleitschuh/gradle/ktlint/sample/mppandroid/LocationProvider.kt b/samples/kotlin-mpp-android/src/commonMain/kotlin/org/jlleitschuh/gradle/ktlint/sample/mppandroid/LocationProvider.kt index 393ca61b..b0a3d529 100644 --- a/samples/kotlin-mpp-android/src/commonMain/kotlin/org/jlleitschuh/gradle/ktlint/sample/mppandroid/LocationProvider.kt +++ b/samples/kotlin-mpp-android/src/commonMain/kotlin/org/jlleitschuh/gradle/ktlint/sample/mppandroid/LocationProvider.kt @@ -2,11 +2,13 @@ package org.jlleitschuh.gradle.ktlint.sample.mppandroid interface LocationProvider { fun startLocationFix() + fun stopLocationFix() + fun getCurrentLocation(): Location data class Location( val latitude: Long, - val longitude: Long + val longitude: Long, ) } diff --git a/samples/kotlin-mpp/src/commonMain/kotlin/org/jlleitschuh/gradle/ktlint/sample/mpp/CommonInterface.kt b/samples/kotlin-mpp/src/commonMain/kotlin/org/jlleitschuh/gradle/ktlint/sample/mpp/CommonInterface.kt index d62b392b..14c2b6d4 100644 --- a/samples/kotlin-mpp/src/commonMain/kotlin/org/jlleitschuh/gradle/ktlint/sample/mpp/CommonInterface.kt +++ b/samples/kotlin-mpp/src/commonMain/kotlin/org/jlleitschuh/gradle/ktlint/sample/mpp/CommonInterface.kt @@ -2,5 +2,6 @@ package org.jlleitschuh.gradle.ktlint.sample.mpp interface CommonInterface { fun init() + fun getName(): String } diff --git a/samples/kotlin-reporter-creating/build.gradle.kts b/samples/kotlin-reporter-creating/build.gradle.kts index 45030a8c..99ebbfbe 100644 --- a/samples/kotlin-reporter-creating/build.gradle.kts +++ b/samples/kotlin-reporter-creating/build.gradle.kts @@ -4,5 +4,9 @@ plugins { } dependencies { - compileOnly(pluginLibs.ktlint.core) + compileOnly("com.pinterest.ktlint:ktlint-cli-reporter-core:1.0.1") +} + +ktlint { + version = "1.0.1" } diff --git a/samples/kotlin-reporter-creating/src/main/kotlin/org/jlleitschuh/gradle/ktlint/sample/CsvReporter.kt b/samples/kotlin-reporter-creating/src/main/kotlin/org/jlleitschuh/gradle/ktlint/sample/CsvReporter.kt index f90cb1fe..581d47a8 100644 --- a/samples/kotlin-reporter-creating/src/main/kotlin/org/jlleitschuh/gradle/ktlint/sample/CsvReporter.kt +++ b/samples/kotlin-reporter-creating/src/main/kotlin/org/jlleitschuh/gradle/ktlint/sample/CsvReporter.kt @@ -1,13 +1,16 @@ package org.jlleitschuh.gradle.ktlint.sample -import com.pinterest.ktlint.core.LintError -import com.pinterest.ktlint.core.Reporter +import com.pinterest.ktlint.cli.reporter.core.api.KtlintCliError +import com.pinterest.ktlint.cli.reporter.core.api.ReporterV2 import java.io.PrintStream -class CsvReporter( - private val out: PrintStream -) : Reporter { - override fun onLintError(file: String, err: LintError, corrected: Boolean) { - out.println("$file;${err.line};${err.col};${err.ruleId};${err.detail};$corrected") +class CsvReporter(private val out: PrintStream) : ReporterV2 { + override fun onLintError( + file: String, + ktlintCliError: KtlintCliError, + ) { + out.println( + "$file;${ktlintCliError.line};${ktlintCliError.col};${ktlintCliError.ruleId};${ktlintCliError.detail}", + ) } } diff --git a/samples/kotlin-reporter-creating/src/main/kotlin/org/jlleitschuh/gradle/ktlint/sample/CsvReporterProvider.kt b/samples/kotlin-reporter-creating/src/main/kotlin/org/jlleitschuh/gradle/ktlint/sample/CsvReporterProvider.kt index 746a3e60..09e5ad31 100644 --- a/samples/kotlin-reporter-creating/src/main/kotlin/org/jlleitschuh/gradle/ktlint/sample/CsvReporterProvider.kt +++ b/samples/kotlin-reporter-creating/src/main/kotlin/org/jlleitschuh/gradle/ktlint/sample/CsvReporterProvider.kt @@ -1,14 +1,14 @@ package org.jlleitschuh.gradle.ktlint.sample -import com.pinterest.ktlint.core.Reporter -import com.pinterest.ktlint.core.ReporterProvider +import com.pinterest.ktlint.cli.reporter.core.api.ReporterProviderV2 +import com.pinterest.ktlint.cli.reporter.core.api.ReporterV2 import java.io.PrintStream -class CsvReporterProvider : ReporterProvider { +class CsvReporterProvider : ReporterProviderV2 { override val id: String = "csv" override fun get( out: PrintStream, - opt: Map - ): Reporter = CsvReporter(out) + opt: Map, + ): ReporterV2 = CsvReporter(out) } diff --git a/samples/kotlin-reporter-creating/src/main/resources/META-INF/services/com.pinterest.ktlint.core.ReporterProvider b/samples/kotlin-reporter-creating/src/main/resources/META-INF/services/com.pinterest.ktlint.cli.reporter.core.api.ReporterProviderV2 similarity index 100% rename from samples/kotlin-reporter-creating/src/main/resources/META-INF/services/com.pinterest.ktlint.core.ReporterProvider rename to samples/kotlin-reporter-creating/src/main/resources/META-INF/services/com.pinterest.ktlint.cli.reporter.core.api.ReporterProviderV2 diff --git a/samples/kotlin-reporter-using/build.gradle.kts b/samples/kotlin-reporter-using/build.gradle.kts index 82b25161..bf60f02e 100644 --- a/samples/kotlin-reporter-using/build.gradle.kts +++ b/samples/kotlin-reporter-using/build.gradle.kts @@ -27,7 +27,10 @@ ktlint { } } -// TODO: fix it -tasks.named("loadKtlintReporters").configure { - dependsOn(projects.samples.kotlinReporterCreating) +tasks.named("loadKtlintReporters") { + dependsOn(":samples:kotlin-rulesets-creating:build") +} + +ktlint { + version = "1.0.1" } diff --git a/samples/kotlin-rulesets-creating/build.gradle.kts b/samples/kotlin-rulesets-creating/build.gradle.kts index 6ca7c02a..a051f354 100644 --- a/samples/kotlin-rulesets-creating/build.gradle.kts +++ b/samples/kotlin-rulesets-creating/build.gradle.kts @@ -8,3 +8,7 @@ dependencies { compileOnly(pluginLibs.kotlin.script.runtime) compileOnly("com.pinterest.ktlint:ktlint-cli-ruleset-core:0.50.0") } + +ktlint { + version = "1.0.1" +} diff --git a/samples/kotlin-rulesets-creating/src/main/kotlin/org/jlleitschuh/gradle/ktlint/sample/kotlin/CustomRuleSetProvider.kt b/samples/kotlin-rulesets-creating/src/main/kotlin/org/jlleitschuh/gradle/ktlint/sample/kotlin/CustomRuleSetProvider.kt index 945e3c8e..2c798e45 100644 --- a/samples/kotlin-rulesets-creating/src/main/kotlin/org/jlleitschuh/gradle/ktlint/sample/kotlin/CustomRuleSetProvider.kt +++ b/samples/kotlin-rulesets-creating/src/main/kotlin/org/jlleitschuh/gradle/ktlint/sample/kotlin/CustomRuleSetProvider.kt @@ -5,7 +5,6 @@ import com.pinterest.ktlint.rule.engine.core.api.RuleProvider import com.pinterest.ktlint.rule.engine.core.api.RuleSetId class CustomRuleSetProvider : RuleSetProviderV3(RuleSetId("custom")) { - override fun getRuleProviders(): Set { return setOf(RuleProvider { NoVarRule() }) } diff --git a/samples/kotlin-rulesets-creating/src/main/kotlin/org/jlleitschuh/gradle/ktlint/sample/kotlin/NoVarRule.kt b/samples/kotlin-rulesets-creating/src/main/kotlin/org/jlleitschuh/gradle/ktlint/sample/kotlin/NoVarRule.kt index 6f373bec..4ea50193 100644 --- a/samples/kotlin-rulesets-creating/src/main/kotlin/org/jlleitschuh/gradle/ktlint/sample/kotlin/NoVarRule.kt +++ b/samples/kotlin-rulesets-creating/src/main/kotlin/org/jlleitschuh/gradle/ktlint/sample/kotlin/NoVarRule.kt @@ -7,14 +7,11 @@ import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.LeafPsiElement import org.jetbrains.kotlin.com.intellij.psi.util.PsiTreeUtil.getNonStrictParentOfType import org.jetbrains.kotlin.psi.KtStringTemplateEntry -class NoVarRule : Rule( - RuleId("test:novar"), - About() -) { +class NoVarRule : Rule(RuleId("test:novar"), About()) { override fun beforeVisitChildNodes( node: ASTNode, autoCorrect: Boolean, - emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit + emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit, ) { if (node is LeafPsiElement && node.textMatches("var") && getNonStrictParentOfType(node, KtStringTemplateEntry::class.java) == null diff --git a/settings.gradle.kts b/settings.gradle.kts index 245ec8cb..ce826a9b 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -24,7 +24,6 @@ pluginManagement { } } -enableFeaturePreview("VERSION_CATALOGS") enableFeaturePreview("TYPESAFE_PROJECT_ACCESSORS") dependencyResolutionManagement { @@ -62,6 +61,7 @@ fun isAndroidSdkInLocalPropertiesSet(): Boolean { } fun isAndroidSdkVariableSet(): Boolean = System.getenv().containsKey("ANDROID_HOME") + fun isAndroidSdkAvailable(): Boolean = isAndroidSdkVariableSet() || isAndroidSdkInLocalPropertiesSet() include("samples:kotlin-ks")