一、版本
android studio:2020.3.1 patch 3
gradle:6.5
gradle tool:4.1.1
detekt:1.13.1
二、配置
项目级build.gradle
plugins {
id("io.gitlab.arturbosch.detekt").version("1.13.1")
}
allprojects {
repositories {
...
}
apply plugin: 'io.gitlab.arturbosch.detekt'
}
detekt {
failFast = true // fail build on any finding
buildUponDefaultConfig = true //Applies the config files on top of detekt's default config file. `false` by default.
config = files("$projectDir/config/detekt/detekt.yml")
// point to your custom config defining rules to run, overwriting default behavior
// baseline = file("${rootProject.projectDir}/config/baseline.xml")
// a way of suppressing issues before introducing detekt
reports {
html.enabled = true // observe findings in your browser with structure and code snippets
xml.enabled = true // checkstyle like format mainly for integrations like Jenkins
txt.enabled = true
// similar to the console output, contains issue signature to manually edit baseline files
}
}
subprojects {
detekt {
baseline = file("${projectDir}/config/baseline.xml")
}
}
三、执行
1、运行运行./gradlew tasks查看相关任务是否被加进去了:
detekt
detektBaseline - Creates a detekt baseline on the given --baseline path.
detektGenerateConfig - Generate a detekt configuration file inside your project.
detektIdeaFormat - Uses an external idea installation to format your code.
detektIdeaInspect - Uses an external idea installation to inspect your code.
2、运行检查
./gradlew detekt
3、生成自定义配置文件 config/detekt/detekt.yml
./gradlew detektGenerateConfig
在配置文件中可以看到对各种规则的开关状态, 编辑它可以进行定制.
四、和git hook 配合(commit之前检查代码规范)
1、项目级目录中添加hooks文件夹
2、执行
git config core.hooksPath hooks
3、pre-commit文件内容,文件名不可修改
#!/usr/bin/env bash
#
# 方案一: https://arturbosch.github.io/detekt/git-pre-commit-hook.html
# 将该文件放到project根目录的.git/hooks/目录下,执行 chmod +x pre-commit 为脚本添加可执行权限即可,
# 之后的每次commit都会先执行 checkstyle task 进行代码检查
#
# 方案二: https://stackoverflow.com/questions/427207/can-git-hook-scripts-be-managed-along-with-the-repository
# 从git 2.9开始, 可以设置:core.hooksPath了.
# 可以在repo里面添加一个目录hooks, 然后把git hooks文件放进去track.
# 在命令行跑:
# git config core.hooksPath [文件路径]
# 把找hook文件的目录设置成指定目录就好了.
echo "执行 kotlin 代码规范检查..."
./gradlew detekt
EXIT_CODE=$?
if [ $EXIT_CODE -ne 0 ]; then
echo "***********************************************"
echo " Detekt failed "
echo " Please fix the above issues before committing "
echo "***********************************************"
exit $EXIT_CODE
fi
#echo "执行 checkstyle 任务 "
#./gradlew checkstyle
五、代码忽略检查
./gradlew detektBaseline
1、执行之后会在每一个module的config目录中生成baseline.xml,后面再执行代码检查的时候会忽略之前的代码,只检查增量代码。
2、部分代码截图