Giter Club home page Giter Club logo

detekt's Introduction

detekt

Join the chat at #detekt on KotlinLang Visit the website at detekt.dev/ Maven Central Gradle Plugin Revved up by Develocity License

Pre Merge Checks Codecov Awesome Kotlin Badge FOSSA Status

Meet detekt, a static code analysis tool for the Kotlin programming language. Visit the project website for installation guides, rule descriptions, configuration options and more.

detekt in action

Features

  • Code smell analysis for your Kotlin projects.
  • Highly configurable rule sets.
  • Generate baselines to suppress existing issues for legacy projects while making sure no new issues are introduced.
  • Suppress issues in source files using @Suppress annotations.
  • Support for different report formats: HTML, Markdown, SARIF, XML (Checkstyle) and custom reports.
  • Extend detekt with custom rule sets and reports.
  • Complexity reports based on lines of code, cyclomatic complexity and number of code smells.
  • First party integration with Gradle with our Gradle plugin.
  • A community of third party plugins that adds more rules and features to detekt.

Quick-Links

Quick Start ...

with the command-line interface

curl -sSLO https://github.com/detekt/detekt/releases/download/v[version]/detekt-cli-[version]-all.jar
java -jar detekt-cli-[version]-all.jar --help

You can find other ways to install detekt here

with Gradle

plugins {
    id("io.gitlab.arturbosch.detekt") version "[version]"
}

repositories {
    mavenCentral()
}

detekt {
    buildUponDefaultConfig = true // preconfigure defaults
    allRules = false // activate all available (even unstable) rules.
    config.setFrom("$projectDir/config/detekt.yml") // point to your custom config defining rules to run, overwriting default behavior
    baseline = file("$projectDir/config/baseline.xml") // a way of suppressing issues before introducing detekt
}

tasks.withType<Detekt>().configureEach {
    reports {
        html.required.set(true) // observe findings in your browser with structure and code snippets
        xml.required.set(true) // checkstyle like format mainly for integrations like Jenkins
        txt.required.set(true) // similar to the console output, contains issue signature to manually edit baseline files
        sarif.required.set(true) // standardized SARIF format (https://sarifweb.azurewebsites.net/) to support integrations with GitHub Code Scanning
        md.required.set(true) // simple Markdown format
    }
}

// Groovy DSL
tasks.withType(Detekt).configureEach {
    jvmTarget = "1.8"
}
tasks.withType(DetektCreateBaselineTask).configureEach {
    jvmTarget = "1.8"
}

// or

// Kotlin DSL
tasks.withType<Detekt>().configureEach {
    jvmTarget = "1.8"
}
tasks.withType<DetektCreateBaselineTask>().configureEach {
    jvmTarget = "1.8"
}

See maven central for releases and sonatype for snapshots.

If you want to use a SNAPSHOT version, you can find more info on this documentation page.

Requirements

Gradle 6.8.3+ is the minimum requirement. However, the recommended versions together with the other tools recommended versions are:

Detekt Version Gradle Kotlin AGP Java Target Level JDK Max Version
1.23.6 8.7 1.9.23 8.3.1 1.8 17

The list of recommended versions for previous detekt version is listed here.

Adding more rule sets

detekt itself provides a wrapper over ktlint as the formatting rule set which can be easily added to the Gradle configuration:

dependencies {
    detektPlugins("io.gitlab.arturbosch.detekt:detekt-formatting:[version]")
}

Similarly, there are extra rule sets available for detekt from detekt:

dependencies {
    detektPlugins("io.gitlab.arturbosch.detekt:detekt-rules-libraries:[version]")
    detektPlugins("io.gitlab.arturbosch.detekt:detekt-rules-ruleauthors:[version]")
}

For more info visit the Detekt Marketplace.

Likewise custom extensions can be added to detekt.

Contributing

See CONTRIBUTING

Thanks to all the people who contributed to detekt!

Profile images of all the contributors

Mentions

androidweekly androidweekly

As mentioned in...

Integrations:

Custom rules and reports from 3rd parties can be found on our Detekt Marketplace.

Credits

detekt's People

Contributors

3flex avatar arturbosch avatar atulgpt avatar braisgabin avatar chao2zhang avatar cortinico avatar dependabot-preview[bot] avatar dependabot[bot] avatar dzirbel avatar egor-n avatar epeee avatar geralt-encore avatar goooler avatar lummax avatar marschwar avatar mauin avatar mishkun avatar mkobit avatar pavlospt avatar poisonedyouth avatar renovate[bot] avatar rock3r avatar schalkms avatar sowmyav24 avatar sschuberth avatar t-kameyama avatar tagantroy avatar twisterrob avatar vanniktech avatar vitalyvpinchuk avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

detekt's Issues

java 9 - reflection cannot make constructor private

A Java 9 issue related to reflection. I ran java -jar .../detekt-cli.jar -p . against a simple Kotlin project, using Java 9 (build 9-ea+159):

Caused by: java.lang.reflect.InaccessibleObjectException: Unable to make private jdk.internal.reflect.ConstructorAccessor java.lang.reflect.Constructor.acquireConstructorAccessor() accessible: module java.base does not "opens java.lang.reflect" to unnamed module @34c4973
        at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(Unknown Source)
        at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(Unknown Source)
        at java.base/java.lang.reflect.Method.checkCanSetAccessible(Unknown Source)
        at java.base/java.lang.reflect.Method.setAccessible(Unknown Source)
        at com.intellij.util.ReflectionUtil.findMethod(ReflectionUtil.java:265)
        at com.intellij.util.ReflectionUtil.getDeclaredMethod(ReflectionUtil.java:279)
        at com.intellij.util.ReflectionUtil.<clinit>(ReflectionUtil.java:422)
        ... 14 more

Prototype gradle plugin

Before M3 I think the kotlin compiler throw a strange exception when running as a gradle plugin...

Add Support For GSK

Support is needed for GSK (Gradle Script Kotlin) which is used by some Kotlin projects, and there are some which provide support for it (eg Spek). Currently GSK is at version 0.9.1 which means now would be a good opportunity to start supporting GSK before it reaches a stable version.

Allow different naming conventions for tests

In tests, I like to have very specific method names that are human readable.

For example:

fun `With input X, the output should be Y`()

However, this is not valid in Android apps.

As such, it would be nice if I could specify a different configuration for the tests in my project.

Rule: SingleExpression statements with multiple return paths

Format:

inline fun <T> to(block: () -> T): Try<T> {
    try {
        return Try(block.invoke(), null)
    } catch (any: Throwable) {
        return Try(null, any)
    }
}

to

inline fun <T> to(block: () -> T) =
    try {
        Try(block.invoke(), null)
    } catch (any: Throwable) {
        Try(null, any)
    }

IDEA Plugin

It would be awesome if the analysis could be done in the background directly in IDEA in order to see/fix every problem before even compiling anything!

Optimise console output

It'd be cool if the console output could be optimized a bit. For instance given the following line:

ComplexCondition - 5/3 - [timesFor] - Line/Column=(44,11) - Path=main/java/io/sunnyspots/android/io/model/Time.kt

it would be beneficial to change a few things:

  • include the project dir in the file (in my case app/src/)
  • remove the Path= so that the file will be clickable in iTerm2 for instance
  • Make use of the line number and column

I'd propose to change it to the following

-ComplexCondition - 5/3 - [timesFor] - Line/Column=(44,11) - Path=main/java/io/sunnyspots/android/io/model/Time.kt
+ComplexCondition - 5/3 - [timesFor] at app/src/main/java/io/sunnyspots/android/io/model/Time.kt:44:11

Rule: Expression syntax

Hi there! I have a couple ideas for rules that would help my team a lot, and hopefully would help others, too.

Always use expression syntax in functions when possible

Suppose you have

fun foo(): String {
  return ""
}

If there's only one statement and the method has a non-void return value, it should always be turned into the equivalent expression version:

fun foo(): String = ""

While just a style issue, this is something we end up calling out in our code reviews constantly and...we'd like to not have to do that ๐Ÿ˜‰

Remainder was split off into #36.

Rule: UnusedPrivateMember

Check if private fields, methods, parameter and locale variables are unused.

Idea:

  1. Visit KtFile and store names of fields and methods in a Map<String, Int>
  2. Visit methods look for references, increment reference map
  3. If field/method have same name as local or parameter, check positions.

Rule: Max line length

I would like to be able to enforce a maximum line length on the files being linted

Allow Indentation check to handle "align when multiline" option

https://github.com/arturbosch/detekt/blob/master/detekt-formatting/src/main/kotlin/io/gitlab/arturbosch/detekt/formatting/Indentation.kt seems to assume every line will be indented by some multiple of 4 spaces.

In Android Studio, I have these options checked:
screen shot 2017-05-08 at 14 22 42

The result is code that looks like:

fun example(arg0: String, arg1: String,
                      arg2: String) {

This is not a multiple of 4 spaces.

In general, I want to ensure that all code is indented properly, but it's not always going to be a multiple of 4 spaces.

Naming Convetion Violation ignoring patterns

Hey,

I have encountered this problem and cannot find a way to fix it.
style:
active: true
WildcardImport:
active: true
NamingConventionViolation:
active: true
variablePattern: '^()?[a-z$][a-zA-Z$0-9]*$'
constantPattern: '^([A-Z0-9
]|serialVersionUID)$'
methodPattern: '^[a-z$][a-zA-Z$0-9]
$'
classPattern: '[A-Z$][a-zA-Z0-9$]*'

Even if i delete all the patterns, i get the NamingConventionViolation in my report, when i try to modify these patterns, no changes are detected in process. The only thing that works for me is activate or deactivate.

Update to Kotlin 1.1.1

Problems:

  • migrate configurations kotlin to kotlinCompile
  • hamKrest is on 1.0 and uses moved reflection packages

Configuration file with all possible rules and their values

Right now I'm seeing two configuration files in the project. #1 & #2.

I'm not sure now whether there are any more rules or not that I could make use of. Plus whether some rules might have some more attributes that can be configured or not.

Is something like an aggregated configuration file with proper documentation planned?

Decouple/Rewrite/Publish smell-baseline-format

There is an unpublished dependency on smell-baseline-format in detekt. As Java9 does not preload the module java.xml.bind, every start of detekt needs an additional parameter which can confuse users.

There are three possibilities:

  1. Publish the dependency as it is now to jcenter (it just works)
  2. Use another preloaded xml module/rewrite and publish to jcenter
  3. Rewrite as 2. and integrate the format into detekt

Rule: Expression-syntax line breaks

Split off from #35.

Expression-syntax line breaks

Another more nuanced (and admittedly, somewhat arbitrary) rule is the following:
When using expression syntax:

  1. If the expression is a one-liner, the = should be on the same line as the expression, and both should be on the line following the method prototype.
  2. Otherwise, the = should be right after the method prototype, and the rest of the expression should be on the following lines.

Example:

fun foo(): String
    = " Hello World ".trim()

fun bar(): String =
    foo()
        .baz()
        .bat()

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.