Skip to content

Commit

Permalink
Fix style issues
Browse files Browse the repository at this point in the history
  • Loading branch information
3flex committed Nov 1, 2022
1 parent 91553d9 commit 170f46f
Show file tree
Hide file tree
Showing 12 changed files with 88 additions and 55 deletions.
Expand Up @@ -30,7 +30,7 @@ class DetektAnalysisExtension(
if (spec.loggingSpec.debug) {
log.info("$spec")
}
val matchers = excludes.map { FileSystems.getDefault().getPathMatcher("glob:${it}") }
val matchers = excludes.map { FileSystems.getDefault().getPathMatcher("glob:$it") }
val (includedFiles, excludedFiles) = files.partition { file ->
matchers.none { it.matches(rootPath.relativize(Paths.get(file.virtualFilePath))) }
}
Expand Down
Expand Up @@ -14,6 +14,7 @@ class DetektCommandLineProcessor : CommandLineProcessor {

override val pluginId: String = "detekt-compiler-plugin"

@Suppress("StringLiteralDuplication")
override val pluginOptions: Collection<AbstractCliOption> = listOf(
CliOption(
Options.config,
Expand Down Expand Up @@ -61,7 +62,7 @@ class DetektCommandLineProcessor : CommandLineProcessor {
Options.disableDefaultRuleSets,
"<true|false>",
"Disables all default detekt rulesets and will only run detekt with custom rules " +
"defined in plugins passed in with `detektPlugins` configuration.",
"defined in plugins passed in with `detektPlugins` configuration.",
false
),
CliOption(
Expand All @@ -86,7 +87,7 @@ class DetektCommandLineProcessor : CommandLineProcessor {
Options.report,
"<report-id:path>",
"Generates a report for given 'report-id' and stores it on given 'path'. " +
"Available 'report-id' values: 'txt', 'xml', 'html'.",
"Available 'report-id' values: 'txt', 'xml', 'html'.",
false,
allowMultipleOccurrences = true
)
Expand All @@ -105,7 +106,11 @@ class DetektCommandLineProcessor : CommandLineProcessor {
Options.parallel -> configuration.put(Keys.PARALLEL, value.toBoolean())
Options.rootPath -> configuration.put(Keys.ROOT_PATH, Paths.get(value))
Options.excludes -> configuration.put(Keys.EXCLUDES, value.decodeToGlobSet())
Options.report -> configuration.put(Keys.REPORTS, value.substringBefore(':'), Paths.get(value.substringAfter(':')))
Options.report -> configuration.put(
Keys.REPORTS,
value.substringBefore(':'),
Paths.get(value.substringAfter(':')),
)
else -> throw CliOptionProcessingException("Unknown option: ${option.optionName}")
}
}
Expand Down
Expand Up @@ -5,6 +5,7 @@ import java.nio.file.Path

object Options {

@Suppress("NonBooleanPropertyPrefixedWithIs")
const val isEnabled: String = "isEnabled"
const val debug: String = "debug"
const val config = "config"
Expand Down
Expand Up @@ -20,7 +20,7 @@ internal fun CompilerConfiguration.toSpec(log: MessageCollector) = ProcessingSpe
}
reports {
getMap(Keys.REPORTS).forEach {
report { Pair(it.key, it.value) }
report { it.key to it.value }
}
}
extensions {
Expand Down
Expand Up @@ -16,6 +16,7 @@ internal class DetektService(
) {

@OptIn(UnstableApi::class)
@Suppress("ForbiddenComment")
fun analyze(files: Collection<KtFile>, context: BindingContext) {
val detekt = DetektProvider.load().get(spec)
val result = detekt.run(files, context)
Expand Down
Expand Up @@ -8,12 +8,17 @@ import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSourceLocation
import org.jetbrains.kotlin.cli.common.messages.MessageCollector
import org.jetbrains.kotlin.cli.common.messages.MessageUtil

fun MessageCollector.info(msg: String) = this.report(CompilerMessageSeverity.INFO, msg)
fun MessageCollector.info(msg: String) {
this.report(CompilerMessageSeverity.INFO, msg)
}

fun MessageCollector.warn(msg: String, location: CompilerMessageSourceLocation? = null) =
fun MessageCollector.warn(msg: String, location: CompilerMessageSourceLocation? = null) {
this.report(CompilerMessageSeverity.WARNING, msg, location)
}

fun MessageCollector.error(msg: String) = this.report(CompilerMessageSeverity.ERROR, msg)
fun MessageCollector.error(msg: String) {
this.report(CompilerMessageSeverity.ERROR, msg)
}

fun MessageCollector.reportFindings(result: Detektion) {
for ((ruleSetId, findings) in result.findings.entries) {
Expand Down
Expand Up @@ -16,7 +16,7 @@ class CompilerTest {
println(x)
}
}
"""
""".trimIndent()
)

assertThat(result)
Expand All @@ -38,7 +38,7 @@ class CompilerTest {
println(x)
}
}
"""
""".trimIndent()
)

assertThat(result)
Expand All @@ -51,13 +51,14 @@ class CompilerTest {
fun `with a source file that does not contain violations`() {
val result = compile(
"""
class KClass {
fun foo() {
println("Hello world :)")
}
}
"""
|class KClass {
| fun foo() {
| println("Hello world :)")
| }
|}
|
|
""".trimMargin()
)

assertThat(result)
Expand Down
@@ -1,7 +1,8 @@
package io.github.detekt.compiler.plugin.util

import com.tschuchort.compiletesting.KotlinCompilation
import com.tschuchort.compiletesting.KotlinCompilation.ExitCode.*
import com.tschuchort.compiletesting.KotlinCompilation.ExitCode.COMPILATION_ERROR
import com.tschuchort.compiletesting.KotlinCompilation.ExitCode.OK
import org.assertj.core.api.AbstractObjectAssert

fun assertThat(result: KotlinCompilation.Result) = CompilationAssert(result)
Expand All @@ -17,16 +18,18 @@ class CompilationAssert(private val result: KotlinCompilation.Result) :
private val detektViolations = detektMessages
.mapNotNull { line -> regex.find(line)?.groupValues?.get(1) }

fun passCompilation(expectedStatus : Boolean = true) = apply {
fun passCompilation(expectedStatus: Boolean = true) = apply {
val expectedErrorCode = if (expectedStatus) OK else COMPILATION_ERROR
if (result.exitCode != expectedErrorCode) {
failWithActualExpectedAndMessage(result.exitCode, expectedErrorCode,
"Expected compilation to finish with " +
"code $expectedErrorCode but was ${result.exitCode}")
failWithActualExpectedAndMessage(
result.exitCode,
expectedErrorCode,
"Expected compilation to finish with code $expectedErrorCode but was ${result.exitCode}"
)
}
}

fun passDetekt(expectedStatus : Boolean = true) = apply {
fun passDetekt(expectedStatus: Boolean = true) = apply {
// The status message is `i: Success?: false`
val status = detektMessages
.first { "Success?" in it }
Expand All @@ -36,26 +39,32 @@ class CompilationAssert(private val result: KotlinCompilation.Result) :
.toBoolean()

if (status != expectedStatus) {
failWithActualExpectedAndMessage(status, expectedStatus,
"Expected detekt to finish with " +
"success status: $expectedStatus but was $status")
failWithActualExpectedAndMessage(
status,
expectedStatus,
"Expected detekt to finish with success status: $expectedStatus but was $status",
)
}
}

fun withNoViolations() = withViolations(0)

fun withViolations(expectedViolationNumber: Int) = apply {
if (detektViolations.size != expectedViolationNumber) {
failWithActualExpectedAndMessage(detektViolations.size, expectedViolationNumber,
"Expected detekt violations to be " +
"$expectedViolationNumber but was ${detektViolations.size}")
failWithActualExpectedAndMessage(
detektViolations.size,
expectedViolationNumber,
"Expected detekt violations to be $expectedViolationNumber but was ${detektViolations.size}",
)
}
}

fun withRuleViolation(vararg expectedRuleName: String) = apply {
if (expectedRuleName.any { it !in detektViolations }) {
failWithMessage("Expected rules ${expectedRuleName.toList()} to raise a violation " +
"but not all were found. Found violations are instead $detektViolations")
failWithMessage(
"Expected rules ${expectedRuleName.toList()} to raise a violation but not all were found. " +
"Found violations are instead $detektViolations"
)
}
}
}
Expand Up @@ -18,4 +18,4 @@ object CompilerTestUtils {
commandLineProcessors = listOf(DetektCommandLineProcessor())
}.compile()
}
}
}
Expand Up @@ -27,12 +27,15 @@ class DetektKotlinCompilerPlugin : KotlinCompilerPluginSupportPlugin {
target.pluginManager.apply(ReportingBasePlugin::class.java)

val extension =
target.extensions.findByType(DetektExtension::class.java) ?: target.extensions.create(DETEKT_NAME, DetektExtension::class.java)
target.extensions.findByType(DetektExtension::class.java) ?: target.extensions.create(
DETEKT_NAME,
DetektExtension::class.java
)

extension.reportsDir = target.extensions.getByType(ReportingExtension::class.java).file("detekt")

val defaultConfigFile =
target.file("${target.rootProject.layout.projectDirectory.dir(DetektPlugin.CONFIG_DIR_NAME)}/${DetektPlugin.CONFIG_FILE}")
target.file("${target.rootProject.layout.projectDirectory.dir(CONFIG_DIR_NAME)}/$CONFIG_FILE")
if (defaultConfigFile.exists()) {
extension.config = target.files(defaultConfigFile)
}
Expand Down Expand Up @@ -113,22 +116,28 @@ class DetektKotlinCompilerPlugin : KotlinCompilerPluginSupportPlugin {

override fun getPluginArtifact(): SubpluginArtifact {
// Other Gradle plugins can also have a versions.properties.
val distinctVersions = this::class.java.classLoader.getResources("versions.properties").toList().mapNotNull { versions ->
Properties().run {
val inputStream = versions.openConnection()
/*
* Due to https://bugs.openjdk.java.net/browse/JDK-6947916 and https://bugs.openjdk.java.net/browse/JDK-8155607,
* it is necessary to disallow caches to maintain stability on JDK 8 and 11 (and possibly more).
* Otherwise, simultaneous invocations of Detekt in the same VM can fail spuriously. A similar bug is referenced in
* https://github.com/detekt/detekt/issues/3396. The performance regression is likely unnoticeable.
* Due to https://github.com/detekt/detekt/issues/4332 it is included for all JDKs.
*/
.apply { useCaches = false }
.getInputStream()
load(inputStream)
getProperty("detektCompilerPluginVersion")
val distinctVersions = this::class
.java
.classLoader
.getResources("versions.properties")
.toList()
.mapNotNull { versions ->
Properties().run {
val inputStream = versions.openConnection()
/*
* Due to https://bugs.openjdk.java.net/browse/JDK-6947916 and https://bugs.openjdk.java.net/browse/JDK-8155607,
* it is necessary to disallow caches to maintain stability on JDK 8 and 11 (and possibly more).
* Otherwise, simultaneous invocations of Detekt in the same VM can fail spuriously. A similar bug is referenced in
* https://github.com/detekt/detekt/issues/3396. The performance regression is likely unnoticeable.
* Due to https://github.com/detekt/detekt/issues/4332 it is included for all JDKs.
*/
.apply { useCaches = false }
.getInputStream()
load(inputStream)
getProperty("detektCompilerPluginVersion")
}
}
}.distinct()
.distinct()
val version = distinctVersions.singleOrNull() ?: error(
"You're importing two Detekt compiler plugins which have different versions. " +
"(${distinctVersions.joinToString()}) Make sure to align the versions."
Expand Down
Expand Up @@ -17,11 +17,6 @@ open class KotlinCompileTaskDetektExtension(project: Project) {
reports.create("sarif")
}

fun getXml() = reports.getByName("xml")
fun getHtml() = reports.getByName("html")
fun getTxt() = reports.getByName("txt")
fun getSarif() = reports.getByName("sarif")

private val objects: ObjectFactory = project.objects

val isEnabled: Property<Boolean> = objects.property(Boolean::class.java)
Expand All @@ -35,4 +30,8 @@ open class KotlinCompileTaskDetektExtension(project: Project) {
val config: ConfigurableFileCollection = objects.fileCollection()
val excludes: SetProperty<String> = objects.setProperty(String::class.java)

fun getXml() = reports.getByName("xml")
fun getHtml() = reports.getByName("html")
fun getTxt() = reports.getByName("txt")
fun getSarif() = reports.getByName("sarif")
}
Expand Up @@ -15,7 +15,10 @@ class DetektPlugin : Plugin<Project> {
override fun apply(project: Project) {
project.pluginManager.apply(ReportingBasePlugin::class.java)
val extension =
project.extensions.findByType(DetektExtension::class.java) ?: project.extensions.create(DETEKT_EXTENSION, DetektExtension::class.java)
project.extensions.findByType(DetektExtension::class.java) ?: project.extensions.create(
DETEKT_EXTENSION,
DetektExtension::class.java
)

extension.reportsDir = project.extensions.getByType(ReportingExtension::class.java).file("detekt")

Expand Down

0 comments on commit 170f46f

Please sign in to comment.