Skip to content

Commit

Permalink
Support Kotlin 1.4 (detekt#2981)
Browse files Browse the repository at this point in the history
* Update to Gradle 6.6

* Update to Kotlin 1.4

* Upgrade to prerelease of KtLint 0.38

* Fix testcase by unwrapping the original descriptor

* Increase max heap for dokka on Java 11

* Update minimal supported Gradle version to 5.3

* Do not run warningsAsErrors on CI due to Gradle not supporting Kotlin 1.4

* Remove new line testing as it fails on windows

* Require Gradle 5.4 to reflect Kotlin's required version from their website
  • Loading branch information
arturbosch authored Aug 20, 2020
1 parent f3877b4 commit ee49144
Show file tree
Hide file tree
Showing 29 changed files with 65 additions and 84 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/deploy-snapshot.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ jobs:
java-version: 8

- name: Build detekt
run: ./gradlew build --build-cache --parallel -PwarningsAsErrors=true
run: ./gradlew build --build-cache --parallel

- name: Deploy Snapshot
env:
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/pre-merge.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ jobs:


- name: Build detekt
run: ./gradlew build :detekt-cli:shadowJarExecutable -PwarningsAsErrors=true --parallel
run: ./gradlew build :detekt-cli:shadowJarExecutable --parallel
- name: Run detekt-cli --help
run: java -jar ./detekt-cli/build/run/detekt --help
- name: Run detekt-cli with argsfile
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ You can find [other ways to install detekt here](https://detekt.github.io/detekt

#### with Gradle

Gradle 5.0+ is required:
Gradle 5.4+ is required:

```kotlin
buildscript {
Expand Down
2 changes: 1 addition & 1 deletion buildSrc/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ repositories {
}

object Plugins {
const val KOTLIN = "1.3.72"
const val KOTLIN = "1.4.0"
const val DETEKT = "1.11.2"
const val GITHUB_RELEASE = "2.2.12"
const val ARTIFACTORY = "4.15.1"
Expand Down
3 changes: 1 addition & 2 deletions buildSrc/src/main/kotlin/detekt.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ plugins {
val analysisDir = file(projectDir)
val baselineFile = file("$rootDir/config/detekt/baseline.xml")
val configFile = file("$rootDir/config/detekt/detekt.yml")
val formatConfigFile = file("$rootDir/config/detekt/format.yml")
val statisticsConfigFile = file("$rootDir/config/detekt/statistics.yml")

val kotlinFiles = "**/*.kt"
Expand Down Expand Up @@ -53,7 +52,7 @@ val detektFormat by tasks.registering(Detekt::class) {
buildUponDefaultConfig = true
autoCorrect = true
setSource(analysisDir)
config.setFrom(listOf(statisticsConfigFile, formatConfigFile))
config.setFrom(listOf(statisticsConfigFile, configFile))
include(kotlinFiles)
include(kotlinScriptFiles)
exclude(resourceFiles)
Expand Down
2 changes: 2 additions & 0 deletions config/detekt/detekt.yml
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@ formatting:
autoCorrect: true
MaximumLineLength:
active: false
ParameterListWrapping:
active: false

naming:
MemberNameEqualsClassName:
Expand Down
6 changes: 0 additions & 6 deletions config/detekt/format.yml

This file was deleted.

2 changes: 1 addition & 1 deletion detekt-bom/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ plugins {
dependencies {
val version = object {
val spek = "2.0.13-alpha.0.3+3b5f071"
val ktlint = "0.37.2"
val ktlint = "0.38.0-alpha01"
}

constraints {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,6 @@ class DetektProgressListener : FileProcessListener {

override fun onFinish(files: List<KtFile>, result: Detektion) {
val middlePart = if (files.size == 1) "file was" else "files were"
outPrinter.appendln("\n\n${files.size} kotlin $middlePart analyzed.")
outPrinter.appendLine("\n\n${files.size} kotlin $middlePart analyzed.")
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -34,14 +34,14 @@ private fun CliArgs.validate(jCommander: JCommander) {
val violations = StringBuilder()

if (createBaseline && baseline == null) {
violations.appendln("Creating a baseline.xml requires the --baseline parameter to specify a path.")
violations.appendLine("Creating a baseline.xml requires the --baseline parameter to specify a path.")
}

if (!createBaseline && baseline != null) {
if (Files.notExists(checkNotNull(baseline))) {
violations.appendln("The file specified by --baseline should exist '$baseline'.")
violations.appendLine("The file specified by --baseline should exist '$baseline'.")
} else if (!Files.isRegularFile(checkNotNull(baseline))) {
violations.appendln("The path specified by --baseline should be a file '$baseline'.")
violations.appendLine("The path specified by --baseline should be a file '$baseline'.")
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,6 @@ class AstPrinter(
}

val ktFile = KtCompiler().compile(input, input)
outPrinter.appendln(ElementPrinter.dump(ktFile))
outPrinter.appendLine(ElementPrinter.dump(ktFile))
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,6 @@ class ConfigExporter(
override fun execute() {
val configPath = Paths.get(arguments.config ?: "detekt.yml")
DefaultConfigurationProvider.load().copy(configPath)
outputPrinter.appendln("Successfully copied default config to ${configPath.toAbsolutePath()}")
outputPrinter.appendLine("Successfully copied default config to ${configPath.toAbsolutePath()}")
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ class ElementPrinter : DetektVisitor() {

companion object {
fun dump(file: KtFile): String = ElementPrinter().run {
sb.appendln("0: " + file.javaClass.simpleName)
sb.appendLine("0: " + file.javaClass.simpleName)
visitKtFile(file)
sb.toString()
}
Expand All @@ -39,14 +39,14 @@ class ElementPrinter : DetektVisitor() {
val currentLine = element.line
if (element.isContainer()) {
indent++
sb.appendln(element.dump)
sb.appendLine(element.dump)
} else {
if (lastLine == currentLine) {
indent++
sb.appendln(element.dump)
sb.appendLine(element.dump)
indent--
} else {
sb.appendln(element.dump)
sb.appendLine(element.dump)
}
}
lastLine = currentLine
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,6 @@ import io.github.detekt.tooling.api.VersionProvider
class VersionPrinter(private val outputPrinter: Appendable) : Executable {

override fun execute() {
outputPrinter.appendln(VersionProvider.load().current())
outputPrinter.appendLine(VersionProvider.load().current())
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,14 @@ package io.gitlab.arturbosch.detekt.cli.runners
import io.github.detekt.test.utils.StringPrintStream
import org.assertj.core.api.Assertions.assertThat
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe

class VersionPrinterSpec : Spek({

describe("version printer") {
test("prints the version") {
val printStream = StringPrintStream()

it("prints the version") {
val printStream = StringPrintStream()
VersionPrinter(printStream).execute()

VersionPrinter(printStream).execute()

assertThat(printStream.toString()).isEqualTo("1.6.0" + System.lineSeparator())
}
assertThat(printStream.toString()).contains("1.6.0")
}
})
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
package io.gitlab.arturbosch.detekt.core

import org.jetbrains.kotlin.cli.common.messages.AnalyzerWithCompilerReport
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageLocation
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSourceLocation
import org.jetbrains.kotlin.cli.common.messages.PlainTextMessageRenderer
import org.jetbrains.kotlin.cli.common.messages.PrintingMessageCollector
import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment
Expand All @@ -16,7 +16,7 @@ import org.jetbrains.kotlin.resolve.lazy.declarations.FileBasedDeclarationProvid
internal fun generateBindingContext(
environment: KotlinCoreEnvironment,
classpath: List<String>,
files: List<KtFile>
files: List<KtFile>,
): BindingContext {
if (classpath.isEmpty()) {
return BindingContext.EMPTY
Expand All @@ -38,11 +38,11 @@ internal fun generateBindingContext(

private object DetektMessageRenderer : PlainTextMessageRenderer() {
override fun getName() = "detekt message renderer"
override fun getPath(location: CompilerMessageLocation) = location.path
override fun getPath(location: CompilerMessageSourceLocation) = location.path
override fun render(
severity: CompilerMessageSeverity,
message: String,
location: CompilerMessageLocation?
location: CompilerMessageSourceLocation?,
): String {
if (!severity.isError) return ""
return super.render(severity, message, location)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ class OutputFacade(
for (extension in extensions) {
val output = extension.render(result)
if (!output.isNullOrBlank()) {
settings.outputChannel.appendln(output)
settings.outputChannel.appendLine(output)
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ internal fun Throwable.printStacktraceRecursively(logger: Appendable) {
is PrintStream -> this.printStackTrace(logger)
is PrintWriter -> this.printStackTrace(logger)
else -> {
stackTrace.forEach { logger.appendln(it.toString()) }
stackTrace.forEach { logger.appendLine(it.toString()) }
cause?.printStacktraceRecursively(logger)
}
}
Expand All @@ -33,17 +33,17 @@ internal class LoggingFacade(
override val errorChannel: Appendable = spec.errorChannel

override fun info(msg: String) {
outputChannel.appendln(msg)
outputChannel.appendLine(msg)
}

override fun error(msg: String, error: Throwable) {
errorChannel.appendln(msg)
errorChannel.appendLine(msg)
error.printStacktraceRecursively(errorChannel)
}

override fun debug(msg: () -> String) {
if (spec.debug) {
outputChannel.appendln(msg())
outputChannel.appendLine(msg())
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import io.github.detekt.test.utils.StringPrintStream
import io.github.detekt.test.utils.createTempFileForTest
import io.github.detekt.test.utils.resourceAsPath
import io.gitlab.arturbosch.detekt.core.DetektResult
import io.gitlab.arturbosch.detekt.core.NL
import io.gitlab.arturbosch.detekt.core.createNullLoggingSpec
import io.gitlab.arturbosch.detekt.core.tooling.withSettings
import io.gitlab.arturbosch.detekt.test.createFinding
Expand Down Expand Up @@ -42,9 +41,9 @@ internal class OutputFacadeSpec : Spek({
spec.withSettings { OutputFacade(this).run(defaultResult) }

assertThat(printStream.toString()).contains(
"Successfully generated ${TxtOutputReport().name} at $plainOutputPath$NL",
"Successfully generated ${XmlOutputReport().name} at $xmlOutputPath$NL",
"Successfully generated ${HtmlOutputReport().name} at $htmlOutputPath$NL"
"Successfully generated ${TxtOutputReport().name} at $plainOutputPath",
"Successfully generated ${XmlOutputReport().name} at $xmlOutputPath",
"Successfully generated ${HtmlOutputReport().name} at $htmlOutputPath"
)
}
})
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,9 @@ object MultiVersionTest : Spek({

private fun getGradleVersionsUnderTest() =
if (getJdkVersion() < 13) {
listOf("5.0", "6.4.1")
listOf("5.4", "6.6")
} else {
listOf("6.4.1")
listOf("6.6")
}

private fun getJdkVersion(): Int {
Expand Down
4 changes: 3 additions & 1 deletion detekt-parser/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import org.jetbrains.kotlin.gradle.plugin.getKotlinPluginVersion

dependencies {
api(kotlin("compiler-embeddable"))
implementation(project(":detekt-psi-utils"))
testImplementation(project(":detekt-test-utils"))
}

tasks.withType<Test> {
systemProperty("kotlinVersion", embeddedKotlinVersion)
systemProperty("kotlinVersion", getKotlinPluginVersion() ?: embeddedKotlinVersion)

doFirst {
systemProperty("testClasspath", classpath.joinToString(";"))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,9 @@ class UnusedPrivateMember(config: Config = Config.empty) : Rule(config) {
override val defaultRuleIdAliases: Set<String> = setOf("UNUSED_VARIABLE", "UNUSED_PARAMETER", "unused")

override val issue: Issue = Issue("UnusedPrivateMember",
Severity.Maintainability,
"Private member is unused.",
Debt.FIVE_MINS)
Severity.Maintainability,
"Private member is unused.",
Debt.FIVE_MINS)

private val allowedNames by LazyRegex(ALLOWED_NAMES_PATTERN, "(_|ignored|expected|serialVersionUID)")

Expand Down Expand Up @@ -99,11 +99,11 @@ private class UnusedFunctionVisitor(
} else {
emptyList()
}
val referenceDescriptors = (references + referencesViaOperator).mapNotNull {
it.getResolvedCall(bindingContext)?.resultingDescriptor
}
functions.filter {
bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, it] !in referenceDescriptors
val referenceDescriptors = (references + referencesViaOperator)
.mapNotNull { it.getResolvedCall(bindingContext)?.resultingDescriptor }
.map { it.original }
functions.filterNot {
bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, it] in referenceDescriptors
}
}
references.isEmpty() -> functions
Expand Down Expand Up @@ -204,7 +204,7 @@ private class UnusedParameterVisitor(allowedNames: Regex) : UnusedMemberVisitor(
private fun KtNamedFunction.isRelevant() = !isAllowedToHaveUnusedParameters()

private fun KtNamedFunction.isAllowedToHaveUnusedParameters() =
isAbstract() || isOpen() || isOverride() || isOperator() || isMainFunction() || isExternal() || isExpect()
isAbstract() || isOpen() || isOverride() || isOperator() || isMainFunction() || isExternal() || isExpect()
}

private class UnusedPropertyVisitor(allowedNames: Regex) : UnusedMemberVisitor(allowedNames) {
Expand All @@ -214,9 +214,11 @@ private class UnusedPropertyVisitor(allowedNames: Regex) : UnusedMemberVisitor(a

override fun getUnusedReports(issue: Issue): List<CodeSmell> {
return properties
.filter { it.nameAsSafeName.identifier !in nameAccesses }
.map { CodeSmell(issue, Entity.from(it),
"Private property ${it.nameAsSafeName.identifier} is unused.") }
.filter { it.nameAsSafeName.identifier !in nameAccesses }
.map {
CodeSmell(issue, Entity.from(it),
"Private property ${it.nameAsSafeName.identifier} is unused.")
}
}

override fun visitParameter(parameter: KtParameter) {
Expand All @@ -236,8 +238,8 @@ private class UnusedPropertyVisitor(allowedNames: Regex) : UnusedMemberVisitor(a
override fun visitPrimaryConstructor(constructor: KtPrimaryConstructor) {
super.visitPrimaryConstructor(constructor)
constructor.valueParameters
.filter { (it.isPrivate() || !it.hasValOrVar()) && it.containingClassOrObject?.isExpect() == false }
.forEach { maybeAddUnusedProperty(it) }
.filter { (it.isPrivate() || !it.hasValOrVar()) && it.containingClassOrObject?.isExpect() == false }
.forEach { maybeAddUnusedProperty(it) }
}

override fun visitSecondaryConstructor(constructor: KtSecondaryConstructor) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1157,7 +1157,7 @@ class UnusedPrivateMemberSpec : Spek({
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).hasSize(1).hasSourceLocations(
SourceLocation(3,5)
SourceLocation(3, 5)
)
}
}
Expand Down
2 changes: 1 addition & 1 deletion docs/pages/gettingstarted/gradle.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ redirect_from:
summary:
---

detekt requires Gradle 5.0 or higher.
detekt requires Gradle 5.4 or higher.

#### <a name="tasks">Available plugin tasks</a>

Expand Down
2 changes: 2 additions & 0 deletions gradle.properties
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,7 @@ systemProp.file.encoding=UTF-8
org.gradle.parallel=true
org.gradle.workers.max=4
org.gradle.caching=true
# increase max heap for dokka on Java 11
org.gradle.jvmargs=-Xmx1024m
# Needed for https://github.com/gradle/gradle/issues/11412
systemProp.org.gradle.internal.publish.checksums.insecure=true
Binary file modified gradle/wrapper/gradle-wrapper.jar
Binary file not shown.
2 changes: 1 addition & 1 deletion gradle/wrapper/gradle-wrapper.properties
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.4.1-all.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-6.6-all.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Loading

0 comments on commit ee49144

Please sign in to comment.