我希望能够在使用 android studio 构建项目时运行 lint 任务,以确保遵循 lint 规则。
我曾尝试使用任务依赖项,但没有运气。我的 TeamCity 构建服务器使用运行 lint 任务的构建任务,因此效果很好。但是,当我选择了调试构建变体时,android studio 似乎可以互换使用generateDebugSources
和任务。compileDebugJava
这是我在 build.gradle 中尝试过的:
assemble.dependsOn lint
我希望能够在使用 android studio 构建项目时运行 lint 任务,以确保遵循 lint 规则。
我曾尝试使用任务依赖项,但没有运气。我的 TeamCity 构建服务器使用运行 lint 任务的构建任务,因此效果很好。但是,当我选择了调试构建变体时,android studio 似乎可以互换使用generateDebugSources
和任务。compileDebugJava
这是我在 build.gradle 中尝试过的:
assemble.dependsOn lint
如果您只想配置您的 Android Studio 项目以在默认运行配置之前运行 lint 检查而不影响您的 gradle 任务的配置方式,您可以按照以下步骤操作。
:app:check
)check
现有Gradle-aware make
步骤之前现在,如果发生任何 lint 错误,Android Studio 将运行 lint 检查并导致构建失败。
To runt lint and analyze your project, simply select Analyze > Inspect Code
.
You should get a nice window with all issues.
Also check Run lint in Android Studio for more information.
I did a little more research, try adding this to your build.gradle
.
lintOptions {
abortOnError true
}
There are many options that you can apply to the build.gradle
要在 build.gradle 中执行此操作,请将以下行添加到您的 build.gradle:
android {
applicationVariants.all { variant ->
variant.outputs.each { output ->
def lintTask = tasks["lint${variant.name.capitalize()}"]
output.assemble.dependsOn lintTask
}
}
...
}
这使得您的所有 assemble 任务都依赖于 lint 任务,在 Android Studio 执行的每个 assemble 调用之前有效地运行它们。
编辑
对于 Android Gradle Plugin 3.3 和 Gradle 5.x,这是使用 Kotlin 脚本的修订版:
applicationVariants.all {
val lintTask = tasks["lint${name.capitalize()}"]
assembleProvider.get().dependsOn.add(lintTask)
}
只需运行“检查”任务
./gradlew clean check assembleRelease
这是我的解决方案,当您在 Android Studio 中单击Build - Make Project时也可以使用:
android {
..
afterEvaluate {
applicationVariants.all {
variant ->
// variantName: e.g. Debug, Release
def variantName = variant.name.capitalize()
// now we tell gradle to always start lint after compile
// e.g. start lintDebug after compileDebugSources
project.tasks["compile${variantName}Sources"].doLast {
project.tasks["lint${variantName}"].execute()
}
}
}
}
如果您想强制 Android Studio 项目在默认运行配置之前运行 lint 检查而不影响您的 gradle 任务的配置方式,并且您想在 gradle 构建系统中执行此操作,那么您可以在该块之外添加以下android
块在 app 模块的 build.gradle 中如下:
android {
....
lintOptions {
abortOnError true
}
}
tasks.whenTaskAdded { task ->
if (task.name == 'compileDevDebugSources') {
task.dependsOn lint
task.mustRunAfter lint
}
}
替换compileDevDebugSources
为您已经定义的所需构建变体,例如。compileReleaseSources
, compileDebugSources
,compileStagingDebugSources
等
这是在 Android Studio 3.0 上测试的
只是修改@Yoel Gluschnaider 的答案
对我来说,如果我使用 Val,它会显示如下错误:无法为类型对象设置未知属性 'lintTask' com.android.build.gradle.internal.api.ApplicationVariantImpl
。
所以我替换它
applicationVariants.all {
def lintTask = tasks["lint${name.capitalize()}"]
assembleProvider.get().dependsOn.add(lintTask)
}
它工作正常!