https://kotlinlang.org logo
Join SlackCommunities
Powered by
# detekt
  • a

    ashdavies

    10/19/2024, 11:54 PM
    But basically, with each bump of Detekt, I'm getting an error
    Copy code
    Execution failed for task ':app-launcher:common:detektAndroidRelease'.
    > Provided path '' is empty.
  • a

    ashdavies

    10/19/2024, 11:54 PM
    Because the source set contains no source files
  • a

    ashdavies

    10/19/2024, 11:55 PM
    I've seen some projects just set Detekt to the root source set, but this has an issue with Type Resolution?
  • a

    ashdavies

    10/21/2024, 11:23 PM
    Found I was making
    detektAll
    depend on all
    Detekt
    tasks, defining it as a new task of type
    Detekt
    that takes the project source set seems to work better
    👍 1
  • f

    Fergus Hewson

    10/24/2024, 7:22 AM
    I have an error running detekt after a few changes to a file. Any ideas what is going on here?
    Copy code
    Location: java.base/java.util.concurrent.CompletableFuture.encodeThrowable(CompletableFuture.java:315)
              The original exception message was: org.jetbrains.kotlin.com.intellij.psi.PsiInvalidElementAccessException: Element: class org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.LeafPsiElement #kotlin  because: different providers: org.jetbrains.kotlin.com.intellij.psi.DummyHolderViewProvider{vFile=LightVirtualFile: /DummyHolder, content=VirtualFileContent{size=0}, eventSystemEnabled=false}(3ecbbc63); org.jetbrains.kotlin.com.intellij.psi.SingleRootFileViewProvider{vFile=LightVirtualFile: /DummyHolder, content=VirtualFileContent{size=0}, eventSystemEnabled=true}(5e048bdd)
    • 1
    • 1
  • a

    Atul Gupta

    11/01/2024, 5:57 PM
    @Colton Idle seems like a bug in
    UnnecessaryLet
    . If still reproducible can you create an issue in Detekt with the sample code?
  • r

    ralf

    11/04/2024, 4:18 PM
    Is it possible to exclude inner classes in the exclude rules? E.g. I have
    Copy code
    UndocumentedPublicFunction:
        active: true
        excludes: [
          '**/src/**/*Component.kt',
        ]
    Which excludes all classes with the
    Component
    suffix. Now I’d like to exclude all inner classes with this suffix, too. I tried these two without success:
    Copy code
    '**/src/**/*$Component.kt',
          '**/src/**/*.Component.kt',
    Any suggestion?
    b
    • 2
    • 2
  • p

    Peter

    11/14/2024, 12:25 PM
    is there a rule, that prevents
    Pair
    as return type 🤔
    s
    • 2
    • 1
  • e

    Emil Kantis

    11/20/2024, 12:06 PM
    https://detekt.dev/docs/rules/performance/#foreachonrange (and other perf rules) references blog posts that are 7 years old. (Kotlin 1.1) Are they still relevant?
    s
    • 2
    • 4
  • j

    João Silva

    11/21/2024, 5:33 PM
    Hi guys! Do you think it makes sense to skip the
    LongMethod
    rule for
    @Composable
    functions? I've had the need to suppress it multiple times the more I write compose. It can happen because of multiple lambdas, decision making, or any other reason. Do you think it would be a good addition to change the current function to accept a new config like
    ignoredAnnotations
    so that we can configure it? What are your toughts? Thank you!
    b
    • 2
    • 4
  • s

    Sebastian Schuberth

    11/22/2024, 10:58 AM
    Are the detekt tasks with type resolution not cached by Gradle? Even if a single file only changes, all task (even in unrelated projects) seem to be rerun.
    b
    • 2
    • 1
  • g

    GMachine

    11/24/2024, 1:42 PM
    Hello everyone! I’m considering switching from the Detekt Gradle plugin to the CLI in our CI environment to improve performance. Has anyone here had experience with this transition? Would you recommend it? Also, how well does the CLI handle type resolution?
    b
    • 2
    • 1
  • a

    Antonis Radz

    11/26/2024, 4:42 PM
    hey, I know this question was asked many times, but I can not still find clear answer. How to properly setup Detekt for KMP project? Currently I did in project `build.gradle.kts`:
    Copy code
    tasks.withType<io.gitlab.arturbosch.detekt.Detekt> detekt@{
        config.setFrom(files("$rootDir/detekt-config.yml"))
        baseline.set(file("$rootDir/detekt-baseline.xml"))
        setSource(files(rootDir))
        include("**/*.kt")
        exclude("**/*.kts")
        exclude("**/resources/**")
        exclude("**/build/**")
    }
    But this seems to be really slow, on CI it runs around 20mins, and project isn't big. Any ideas? Before CI was running around 5mins
  • g

    GMachine

    11/27/2024, 2:55 PM
    Hi everyone! 👋 I've set up Detekt with type resolution via CLI for our Android project, but I'm encountering some false positives. For example, in the snippet below, Detekt flags
    productArgs.favoriteLink!!.id
    as
    UnnecessaryNotNullOperator
    , even though
    productArgs.favoriteLink
    is in another module and cannot be smart casted (Android Studio confirms this).
    if (productArgs.favoriteLink != null) {
    println(productArgs.favoriteLink!!.id) // Reported as UnnecessaryNotNullOperator
    println(productArgs.favoriteLink.id)  // Compiler error: smart cast not possible
    }
    Here’s how I resolve my classpath using a Gradle task:
    tasks.register("resolveClasspath") {
    def resolvedClasspath = providers.provider {
    def classpathFiles = files()
    // Iterate over application variants during the configuration phase
    android.applicationVariants.all { variant ->
    classpathFiles += variant.javaCompileProvider.get().classpath.filter { it.exists() }
    }
    // Convert classpath to a comma-separated string for later use
    classpathFiles.files.collect { it.absolutePath }.join(",")
    }
    doLast {
    println(resolvedClasspath.get())
    }
    }
    Any ideas why Detekt might generate false positives in this setup? Am I missing something in my configuration? 🤔
    b
    • 2
    • 4
  • e

    eygraber

    11/27/2024, 8:21 PM
    Once type resolution is working for non jvm targets, would that work on any host like publishing from any host, or would that target's detekt task have to be run on a native host (e.g. ios on a mac)?
  • a

    arve

    12/02/2024, 1:46 PM
    Is there a way to get project statistics and complexity report in console with CLI, without first generating and modifying a
    detekt.yaml
    ? (or even better, to the txt report)
    b
    • 2
    • 1
  • h

    hfhbd

    12/03/2024, 8:18 AM
    Currently, the report configuration on the detekt extension is deprecated and you should configure the tasks directly. But looking forward regarding dcl, I would still prefer configuring it in the extension and remove direct task configuration. Are you open to discuss it?
  • l

    Louis

    12/04/2024, 5:35 PM
    Hello 👋 I want to setup detekt on a project with 400 modules and run it using a git hook on staged files only. So I used detekt cli, which works well except for rules using type resolution. The only way I've found is to use the gradle plugin. But unless I'm mistaken, I have to run it on every sub projects, which takes a long time. detekt cli was much faster and allows me to specify only a few files. I'd like to get close to detekt-cli performance with rules that use type resolution. I've also tried making a gradle task (detektAll) but it's the same as cli, the classpaths are missing. How can I speed up the task ? Or how can I retrieve relevant classpaths for detekt cli ? 🙂 Here is my configuration with gradle plugin:
    Copy code
    subprojects {
     apply {
      plugin("io.gitlab.arturbosch.detekt")
     }
    
     detekt {
      source.setFrom("src/main/kotlin", "src/main/java")
    
      buildUponDefaultConfig = true
      config.setFrom("$rootDir/detekt/config.yml")
      baseline = file("$projectDir/detekt/baseline.xml")
      autoCorrect = true
      parallel = true
      ignoreFailures = false
      buildUponDefaultConfig = true
      autoCorrect = true
      ignoredBuildTypes = ["release", "benchmarkDebug", "benchmarkRelease"]
      basePath = rootDir
     }
    
     dependencies {
      detektPlugins("io.gitlab.arturbosch.detekt:detekt-formatting:1.23.7")
      detektPlugins("io.nlopez.compose.rules:detekt:0.4.17")
     }
    }
    ➕ 1
    b
    • 2
    • 3
  • e

    Eric

    01/21/2025, 3:25 PM
    is there a rule for multi-line expression bodies? I'm fine with
    fun foo() = "blah"
    but I'd like to enforce that multi-line expression bodies have a line break after the
    =
    or at least have it consistent within a single class/file
    b
    • 2
    • 2
  • l

    Louis

    01/22/2025, 10:11 AM
    Hello, I'm trying to use the detekt plugin on Android studio but unfortunately I have an error on config.yml. However I use the same file with detekt-cli or the gradle plugin and it works fine. Here's the error, do you know why?
    Copy code
    Unexpected error while running detekt analysis
    
    io.gitlab.arturbosch.detekt.api.Config$InvalidConfigurationError: Provided configuration file is invalid: Structure must be from type Map<String,Any>!
    while constructing a mapping
     in reader, line 1, column 1:
        build:
        ^
    found duplicate key formatting
     in reader, line 1056, column 1:
        formatting:
        ^
  • z

    Zsolt.bertalan

    02/13/2025, 9:41 PM
    I saw the discussions on Github about detekt 2.0.0, but it died down somewhat. Is this still in the works?
    g
    • 2
    • 1
  • c

    Czerwinskimarek88

    02/14/2025, 8:56 AM
    Hi everyone 👋 I want to configure detekt so that the MaximumLineLength rule still blocks long lines, but makes an exception for logging code, such as:
    Copy code
    <http://logger.info|logger.info> { "This is a very long logging message that exceeds the character limit, but I want Detekt to ignore it." }
    I’ve tried various approaches, but I couldn’t find an in-built option to ignore specific function calls (like
    <http://logger.info|logger.info>
    ,
    logger.debug
    ,
    logger.warn
    ). Is there a way to achieve this? Maybe there's a configuration option or a custom rule I could create? Thanks in advance for your help! 🚀
  • b

    Brian Hartvigsen

    02/21/2025, 6:53 PM
    Can someone help me understand why the
    MissingUseCall
    rule detects the following as not using
    use
    ?
    Copy code
    val code = """
                fun <T> MyCloseable.useMe(block: (object) -> T) = use { block(this) }
                fun MyCloseable.useMe() = use {}
    
    
    
                fun test() {
                    MyCloseable(0).use {}
                    MyCloseable(1).useMe()
                    MyCloseable(2).useMe { it.doStuff() }
                }
    
                ${myClosable(clazz)}
            """.trimIndent()
    These are obviously contrived, we have a pattern that would look more like:
    Copy code
    MyCloseable(0).use { it.subPropertyClosable.use { sub -> sub.doStuff() } }
    I was trying to shorthand that to something like the
    useMe
    block except it's more like
    fun <T> MyCloseable.useMe(block: () -> T ) = use { subPropertyCloseable.use { block() } }
    , but I get an error that
    MyCloseable
    is doesn't call
    use
    to access the
    Closeable
    .
  • k

    Kim

    02/24/2025, 3:48 AM
    Is pre-commit framework support planned for detekt? Of course I could write a local script and link via
    repo: local
    as in the guides but would be nice to have some sensible default hooks support with
    .pre-commit-hooks.yaml
    at the repo top level.
    g
    • 2
    • 3
  • e

    eygraber

    03/05/2025, 11:49 PM
    Is it possible to exclude a specific
    ForbiddenMethodCall
    value for tests instead of the whole rule?
    g
    • 2
    • 2
  • m

    Max

    03/21/2025, 3:44 PM
    Hey! I'm trying to use type resolution for my custom rule. I saw, that I should annotate the rule by
    @RequiresFullAnalysis
    , but I don't see it in api. I use
    1.23.8
    version. Has something changed? How can I use it?
    b
    • 2
    • 2
  • d

    David Glasser

    03/26/2025, 10:11 PM
    Hi. We're just getting started with Detekt and have set it up with Gradle integration, including a custom plugin that is built within our repo. Is the IntelliJ plugin supposed to support this sort of setup? I installed it but it doesn't seem to be detecting any issues.
    • 1
    • 1
  • d

    Doug McCluer

    03/31/2025, 3:14 PM
    Can I write a rule that will report usages of Context Receivers? ex:
    Copy code
    context(Activity)
    fun finishWithContextReceiver(){
        finish()
    }
    b
    • 2
    • 2
  • h

    Håkon Pettersen

    04/04/2025, 4:21 AM
    I'm trying to add a rule to forbid the use of
    @Suppress("all")
    like this:
    Copy code
    ForbiddenSuppress:
      active: true
      rules: ["all", "CyclomaticComplexMethod"]
    Currently,
    @Suppress("all")
    isn't being caught, whereas
    "CyclomaticComplexMethod"
    works as expected. Has anyone encountered this issue? docs: https://detekt.dev/docs/rules/style/#forbiddensuppress
    s
    • 2
    • 7
  • m

    maarten ha

    05/02/2025, 12:03 PM
    How can I setup Detekt with ktlint correctly that when I use the reformat shortcut in Intelij it formats to the Detekt configuration? Both Detekt and ktlint plugins are installed in my IDE. Current gradle configuration
    Copy code
    tasks {
        withType<io.gitlab.arturbosch.detekt.Detekt> {
            parallel = true
            config.setFrom(files("/config/detekt/detekt.yml"))
            buildUponDefaultConfig = true
            jvmTarget = "$projectJvmTarget"
            autoCorrect = true
    
            setSource(files("src/main/kotlin", "src/test/kotlin"))
            setOf(
                "**/*.kt",
                "**/*.kts",
                ".*/resources/.*",
                ".*/build/.*",
                "/versions.gradle.kts",
            ).forEach {
                include(it)
            }
    
            reports {
                html.required.set(true)
                html.outputLocation.set(file("reports/detekt/detekt.html"))
    
                sarif.required.set(true)
                sarif.outputLocation.set(file("reports/detekt/detekt.sarif"))
            }
    
            outputs.dir("reports/detekt/")
        }
    }
    
    dependencies {
    ...
     detektPlugins("io.gitlab.arturbosch.detekt:detekt-formatting:1.23.8")
    }
    For the detekt config I just ran the generate config task. Have not changed anything in it
    s
    d
    • 3
    • 2