Разный lint.xml для разных типов сборки в Android Studio?
Я хочу использовать разные файлы lint.xml для выпуска и debug типов сборки в Android Studio. Итак, как это можно достичь?
Когда я помещаю lint.xml в файлы someModule/src/debug и someModule/src/release (также эти папки содержат только этот файл lint.xml и ничего более) gradle реагирует, поскольку нет никакого lint.xml файл, если я помещаю один файл lint.xml в папку основного модуля (someModule/) - gradle распознает его, но в этом случае я не могу использовать разные настройки в зависимости от типа сборки...
Ответы
Ответ 1
Я не пробовал, но, возможно, что-то подобное может помочь вам.
tasks.whenTaskAdded { task ->
if (task.name == 'lintDebug') {
task.ext.lintXmlFileName = "lint-debug.xml"
} else if (task.name == 'lintDemo') {
task.ext.lintXmlFileName = "lint-demo.xml"
}
}
EDIT: комментарии отзывов:
- task.ext.xxxx - это пространство имен, которое вы можете использовать: см. https://docs.gradle.org/current/dsl/org.gradle.api.plugins.ExtraPropertiesExtension.html
- "lintXmlFileName" - это сделанное имя. Вы не найдете документа об этом.
- in android {... lintOptions {... lintConfig file ( "lint.xml" )}} вам нужно прочитать "lintXmlFileName", используя ".ext.get(" lintXmlFileName ")" и установить его для "lintConfig файл()"
- Я не тестировал его, но я предполагаю, что "whenTaskAdded" выходит за пределы "android" в вашем приложении build.gradle.
Ответ 2
Вот что сработало для меня:
tasks.whenTaskAdded { task ->
if (task.name.startsWith("lint")) {
if (task.name.toLowerCase().endsWith("release")) {
task.doFirst {
android.lintOptions.abortOnError = true
}
} else {
task.doFirst {
android.lintOptions.abortOnError = false
}
}
}
}
В моем случае мне нужно было включить abortOnError
для сборки релиза, чтобы я мог свободно развиваться, но быстро ломал ошибки lint на моем CI (если они поскользнулись).
Ответ 3
Это резюме из руководства по новой системе Android, поддержка lint.
Поддержка Lint
Начиная с версии 0.7.0 вы можете запустить lint для конкретного варианта или для всех вариантов, и в этом случае он создает отчет, в котором описываются конкретные варианты, к которым относится данная проблема.
Вы можете настроить lint, добавив раздел lintOptions, как показано ниже. Обычно вы указываете только некоторые из них; в этом разделе показаны все доступные параметры.
android {
lintOptions {
// set to true to turn off analysis progress reporting by lint
quiet true
// if true, stop the gradle build if errors are found
abortOnError false
// if true, only report errors
ignoreWarnings true
// if true, emit full/absolute paths to files with errors (true by default)
//absolutePaths true
// if true, check all issues, including those that are off by default
checkAllWarnings true
// if true, treat all warnings as errors
warningsAsErrors true
// turn off checking the given issue id's
disable 'TypographyFractions','TypographyQuotes'
// turn on the given issue id's
enable 'RtlHardcoded','RtlCompat', 'RtlEnabled'
// check *only* the given issue id's
check 'NewApi', 'InlinedApi'
// if true, don't include source code lines in the error output
noLines true
// if true, show all locations for an error, do not truncate lists, etc.
showAll true
// Fallback lint configuration (default severities, etc.)
lintConfig file("default-lint.xml")
// if true, generate a text report of issues (false by default)
textReport true
// location to write the output; can be a file or 'stdout'
textOutput 'stdout'
// if true, generate an XML report for use by for example Jenkins
xmlReport false
// file to write report to (if not specified, defaults to lint-results.xml)
xmlOutput file("lint-report.xml")
// if true, generate an HTML report (with issue explanations, sourcecode, etc)
htmlReport true
// optional path to report (default will be lint-results.html in the builddir)
htmlOutput file("lint-report.html")
// set to true to have all release builds run lint on issues with severity=fatal
// and abort the build (controlled by abortOnError above) if fatal issues are found
checkReleaseBuilds true
// Set the severity of the given issues to fatal (which means they will be
// checked during release builds (even if the lint target is not included)
fatal 'NewApi', 'InlineApi'
// Set the severity of the given issues to error
error 'Wakelock', 'TextViewEdits'
// Set the severity of the given issues to warning
warning 'ResourceAsColor'
// Set the severity of the given issues to ignore (same as disabling the check)
ignore 'TypographyQuotes'
}
}
EDIT: добавьте реальный и работоспособный пример
Как мы все знаем, новая система сборки Android основана на gradle. Основным компонентом системы сборки gradle является task
. Существуют разные задачи с lint, если у проекта есть другой вариант сборки. Вы можете получить эти задания из студии android studio All task list
или из командной строки ./gradlew tasks
. Пример показывает, как показано ниже, два варианта сборки demo
и full
.
lint - Runs lint on all variants.
lintDemoDebug - Runs lint on the DemoDebug build
lintDemoRelease - Runs lint on the DemoRelease build
lintFullDebug - Runs lint on the FullDebug build
lintFullRelease - Runs lint on the FullRelease build
Эти задачи lint зависят от других задач, здесь скажем preBuild
.
Прежде чем запускать задачу lint, сначала будет выполняться задача preBuild
. Задача preBuild
- уже существующая задача, но мы можем манипулировать этой заданной задачей и добавлять к ней больше действий. Свойство android lintOptions
будет добавлено и изменено динамически на основе разных вариантов сборки, как показано в следующем примере кода в файле app/build.gradle
.
preBuild.doFirst {
android.applicationVariants.each { variant ->
if (variant.name == 'demoDebug') {
println variant.name
android.lintOptions.quiet = true
android.lintOptions.lintConfig = new File('app/lint_demo_debug.xml')
// you can add more properties
} else if (variant.name == 'fullDebug') {
println variant.name
android.lintOptions.quiet = false
android.lintOptions.lintConfig = new File('app/lint_full_debug.xml')
// you can add more properties
} // more variants...
}
Чтобы успешно выполнить код выше, соответствующий файл конфигурации lint должен существовать в каталоге приложения.
Ответ 4
С помощью скриптов сборки kotlin (build.gradle.kts
):
tasks.withType<LintBaseTask>().configureEach {
// doFirst is required else we get a Null Pointer Exception on lintOption
doFirst {
// This will override the lintOptions from the android extension
lintOptions.run {
if (name.toLowerCase().contains("debug")) {
// Do your configuration here
// isAbortOnError = true
// baselineFile = file("baseline.xml")
// isWarningsAsErrors = true
// isCheckDependencies = true
// ignore("MissingTranslation")
// setLintConfig(file("lint.xml"))
}
}
}
}