Perfectus: detekt Integration
Let’s have a look together at detekt a static analysis tool for Kotlin programming language. In my opinion, it’s a great tool that will help you keep your code clean and readable.
Features
- Code smell analysis for your Kotlin projects
- Highly configurable (rule set or rule level)
- Specify code smell thresholds to break your build or print a warning
- Code Smell baseline and ignore lists for legacy projects
Integration of detekt
You can configure detekt just by doing a few simple steps as described below, or by checking my branch tools/detekt
Open root build.gradel file and add the following line at the end of the file
Create a .detekt folder at the root of your project.
Download default-detekt-config.yml file, rename it to detekt-config.yml, and put in the .detekt folder.
Apply detekt plugin to all projects by putting the code below in the allprojects section of the root build.gradle file
Basically, that’s it, now you can run detekt to analyze your code by simply typing
./gradlew detekt
this command will run detekt for all modules in your project and print out errors in the console.
Cleaning up
Let’s reorganize a bit our code.
Create detekt.gradle file in the .detekt folder
Move the lines which we added to the allproject section to detekt.gradel, so at the end, it looks like:
Apply detekt plugin to all projects by adding one line to the allprojects section
so, in this case, we are just applying the same detekt plugin from the file we just created, with this separation code is way cleaner and readable.
Analyzing detekt issues
After running detekt first time you most probably will get some errors
there are two ways to fix them :)
- Navigate to the source file and fix the error
- Adjust detekt-config file and ignore the errors, in case if for your project given error can be ignored.
In my case, I have two types of errors
- EmptyClassBlock — [IPreferences.kt]
- NewLineAtEndOfFile — [IPreferences.kt] and [Preferences.kt]
Let’s say I will fix EmptyClassBlock issue, but I want to ignore NewLineAtEndOfFile issue, for that open detekt-config.yml file and search there NewLineAtEndOfFile
Now if you change active: true to active: false and run
./gradlew detekt
NewLineAtEndOfFile will disappear, in a similar way you can adjust all other rules to your needs, make them strict, disable or enable.
This was it, few simple steps to have a clean and readable code.
You can read more about detekt here.\
Bonus [Fail build if detekt detects erros]
As a final step let’s add logic to fail the build in the case if detekt found errors. To do that we need to run a detekt task before the build, to do so add
preBuild.dependsOn("detekt")
the line to each gradle.build file.
Now when you press the Run button in the Android Studio or execute ./gradlew build command, the first detekt task will run, and if you have errors in your project, the build will fail.
I hope this was helpful :) If yes clap and star Perfectus project for new cool stuff!