Detekt is a powerful tool to keeping code clean and smell free. Generally, after simple configuration, you can run to check by gradel command.
./gradlew detekt
Or
./gradlew detektMain
If you need to run checks that required type resolution. Today, I want to show two additional way to use Detekt more effective.
Detekt plugin for IDE
Plugins help to extend functionality of IDE. Detekt plugin helps to highlight some problem before running gradle command and during writing code. What do you need for that, just add the plugin in settings. This is how looks like simple warning in Android Studio
Pre-commit hook
Very often, checking code with Detekt is part of CI/CD. In most of the cases, it runs on code pushing to branch or creating PR. Periodically, I faced with a situation when developer forgot to remove additional spacing and PR's pipeline failed. Then he created new commit and rerun new pipeline. Depends on project complexity, this loop can require more than one hour.
You can avoid that, just run Detekt before committing or pushing. To reduce possibility to forget about that, I like to do additional checks on pre-commit or pre-push hooks. Hooks are a git mechanism that helps run some scripts before specific git actions. More about it, you can read here.
First, you should go to hooks folder inside .git
folder
cd .git/hooks
From a list of available samples, choose required, open in editor and insert script that should run before action. After editing, just remove .sample
part. My pre-commit
hook looks like this:
#!/usr/bin/env bash
echo "Running detekt check..."
OUTPUT="/tmp/detekt-$(date +%s)"
./gradlew detektMain > $OUTPUT
EXIT_CODE=$?
if [ $EXIT_CODE -ne 0 ]; then
cat $OUTPUT
rm $OUTPUT
echo "***********************************************"
echo " detekt failed "
echo " Please fix the above issues before committing "
echo "***********************************************"
exit $EXIT_CODE
fi
rm $OUTPUT
Sorry, I didn't remember of original author of this code. It is all. Now, before committing Detekt will be run and if some issues will be defined, commit will be not create, and you will have chance to save time.
So, without efforts, we made Detekt more useful. We just added IDE plugin and script in pre-commit hook.
You can find me in X, GitHub or LinkedIn. Thanks for your time and see you in next post.
Top comments (0)