How to make Android Studio build fail on lint errors - android-studio

Is it possible to make Android Studio build fail on lint check errors ?
I have problems with ImageViews when I convert icon from .png to vector drawable .xml
Sometimes I forgot to change
android:src="#drawable/ic_minus"
to
app:srcCompat="#drawable/ic_minus"
and the app crashes on older OS devices.
?

If there's a lint check for that you can change the severity to FATAL and then when building the release version of your APK it should fail.
android {
lintOptions {
fatal 'MY_LINT_CHECK_ID'
}
}
Also you can execute the Gradle lint task which will fail. If you also want warnings to let your build fail you can use this.
android {
lintOptions {
warningsAsErrors true
}
}

You can also use the below code inside android block in module/app level build.gradle file
For build.gradle
android {
applicationVariants.all {
// Example lint task, your verification task can be anything
def lintTask = tasks["lint${name.capitalize()}"]
assembleProvider.get().dependsOn(lintTask/*, detekt*/) // add list of all the tasks which should fail the build
}
}
For build.gradle.kts(Kotlin DSL)
android {
applicationVariants.all {
// Example lint task, your verification task can be anything
val lintTask = tasks["lint${name.capitalize()}"]
assembleProvider.get().dependsOn.addAll(listOf(lintTask/*, tasks["detekt"]*/)) // add list of all the tasks which should fail the build
}
}
Above code makes the build assemble task which run when we run build app or run app, depends on the listed verification tasks and hence fails it when those tasks fails
Make sure your verification tasks(in our case lint task) are set to fail the build when they are run and there are some issues found in them. All verification tasks has their own flags to enable this behaviour.
For lint you can enable the build failure on warning as below(build.gradle.kts for Kotlin DSL)
android {
lint {
isWarningsAsErrors = true
}
}

Related

I received an error on the first run of flutter project! `Finished with error: Gradle task assembleDebug failed with exit code 1`

Today I started to learn flutter.
I created new flutter project from Flutter Application in android studio 3.5.3.
I created new android virtual device and then tried to run main.dart.
I remember that my project freezed during initializing gradle in the first run so I had to stop and rerun main.dart and after that it raises following error:
Launching lib\main.dart on AOSP on IA Emulator in debug mode...
Running Gradle task 'assembleDebug'...
FAILURE: Build failed with an exception.
* What went wrong:
A problem occurred configuring root project 'android'.
> Could not resolve all artifacts for configuration ':classpath'.
> Could not find sdk-common.jar (com.android.tools:sdk-common:26.5.0).
Searched in the following locations:
https://dl.google.com/dl/android/maven2/com/android/tools/sdk-common/26.5.0/sdk-common- 26.5.0.jar
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
BUILD FAILED in 2s
Finished with error: Gradle task assembleDebug failed with exit code 1
build.gradle file contains:
buildscript {
ext.kotlin_version = '1.3.50'
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.5.0'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
allprojects {
repositories {
google()
jcenter()
}
}
rootProject.buildDir = '../build'
subprojects {
project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
project.evaluationDependsOn(':app')
}
task clean(type: Delete) {
delete rootProject.buildDir
}
and settings.gradle contains:
include ':app'
def flutterProjectRoot = rootProject.projectDir.parentFile.toPath()
def plugins = new Properties()
def pluginsFile = new File(flutterProjectRoot.toFile(), '.flutter-plugins')
if (pluginsFile.exists()) {
pluginsFile.withReader('UTF-8') { reader -> plugins.load(reader) }
}
plugins.each { name, path ->
def pluginDirectory = flutterProjectRoot.resolve(path).resolve('android').toFile()
include ":$name"
project(":$name").projectDir = pluginDirectory
}
I guess that freezing was because of poor connection at the moment of initializing and sdk-common.jar didn`t download correctly.
As I mentioned above, I'm new to flutter and I don't know how to clean build the project so I repeated step by step several times but error persists.
I have no idea about this problem.
Can anyone kindly help me?
Please tell me if details are not clear enough to understand.
What went wrong:
A problem occurred configuring root project 'android'.
Could not resolve all artifacts for configuration ':classpath'.
Could not find sdk-common.jar (com.android.tools:sdk-common:26.5.0).
add maven to your gradle file to solve this as follows
maven { url 'https://maven.google.com' }
although i would suggest you use API 28
I don't know how to clean build the project
run flutter clean in your project root folder

Lint not aborting build

I created new project (hello world) and did these steps:
added line if (false) Log.d("AA", "BB") (Lint is listing it as control-flow-issue warning)
added lines into build.gradle
android {
lintOptions {
warningsAsErrors true
checkAllWarnings true
abortOnError true
}
}
added gradle-aware make with :app:check (or :app:lint) as first thing while bulding
Why am I able to build this project? Are there different types of warnings/lints? Because it actually does lint-fail on GoogleAppIndexingWarning. But not on simple things like above.
Edit
Looks like AndroidStudio lint is different than gradle lint. Different set of rules. Proved by running ./gradlew lint with no issues.
I eventually want to stop commiting (pre-commit hook I guess) if AndroidStudio lint finds anything. Any solution/advice on that?

Android Gradle running task before building

I've got this task into build.gradle
apply plugin: 'checkstyle'
task checkstyle(type: Checkstyle) {
// Cleaning the old log because of the creation for the new ones
delete fileTree(dir: "${project.rootDir}/app/build/reports")
source 'src'
include '**/*.java'
exclude '**/gen/**'
// empty classpath
classpath = files()
//Do not fail build
ignoreFailures = false
}
I want this to run automatically when i try to build the app and if finds errors to fail the build. I'm not sure how and where to call the task.
project.afterEvaluate{
assembleAcceptanceDebug.dependsOn("checkstyle")
}
This is what's finally worked. I found the task name when i click to run the app then the problem was that this task does not exists before Evaluate so that was the problem. Now it's working. Thank you and thanks to this https://discuss.gradle.org/t/how-to-define-a-preprocessing-task-for-android-build/6147

Android Studio shows inexplicable warnings for build.gradle

I've created an Android library project in Android Studio and prepared the build.gradle to automate deployment to the Maven Central repository, followed the official instructions from Sonatype.
Particularly, I've added metadata according the Metadata Definition and Upload section
uploadArchives {
repositories {
mavenDeployer {
beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) }
//...
pom.project {
name 'Example Application'
description 'A application used as an example on how to set up pushing its components to the Central Repository.'
url 'http://www.example.com/example-application'
scm {
connection 'scm:svn:http://foo.googlecode.com/svn/trunk/'
developerConnection 'scm:svn:https://foo.googlecode.com/svn/trunk/'
url 'http://foo.googlecode.com/svn/trunk/'
}
licenses {
license {
name 'The Apache License, Version 2.0'
url 'http://www.apache.org/licenses/LICENSE-2.0.txt'
}
}
developers {
developer {
id 'manfred'
name 'Manfred Moser'
email 'manfred#sonatype.com'
}
}
}
}
}
}
Android Studio shows warnings like 'name' cannot be applied to '(java.lang.String)' for the entries
pom.project/name,
pom.project/description,
pom.project/licenses/license/name,
pom.project/organization/name and
pom.project/developers/developer/name.
Running ./gradlew --info clean uploadArchives shows no such warnings. The generated pom.xml contains the defined metadata.
These warnings are somewhat annoying, because Android Studio intercepts every commit that includes the build.gradle to inform me about the existence of warnings.
The question: It there actually a problem with the build.gradle or is there something wrong with Android Studio's interpretation? If it is a problem with the build.gradle, how do I fix it?

Orchestrating Gradle build invocations with custom tasks

I’m trying to define two new Gradle tasks, buildAll and pubLocal, to run other tasks in a specific order.
When gradle buildAll is invoked, I want Gradle to do the same thing as if I had executed gradle clean build writePom (see below for writePom).
When gradle pubLocal is executed, I want Gradle to do the same thing as if gradle buildAll install had been executed.
Here’s my best attempt thus far:
// build.gradle
task writePom << {
pom {
project {
groupId 'mygroup'
artifactId 'mylib'
version version
inceptionYear '2015'
licenses {
license {
name 'Blah'
url 'blah'
distribution 'blah'
}
}
}
}.writeTo("build/libs/pom.xml")
}
task buildAll(dependsOn: clean, build, writePom)
task pubLocal(dependsOn: buildAll, install)
When I run gradle buildAll on this, I get:
myuser#mymachine:~/tmp/myapp$./gradlew buildAll
FAILURE: Build failed with an exception.
* Where:
Build file '/Users/myuser/tmp/myapp/build.gradle' line: 67
* What went wrong:
A problem occurred evaluating root project 'myapp'.
> Could not find method buildAll() for arguments [{dependsOn=task ':clean'}, task ':build', task ':writePom'] on root project 'myapp'.
Any ideas as to where I’m going awry?
This may be a left-over from copy-pasting, but your strings are not quoted consistently using standard single- or double-quotes. Example:
}.writeTo(“build/libs/pom.xml")
does not quote the string properly, as it opens with the “ character instead of ". Same with the single-quotes above it.
You can see from the way your code is highlighted, that everything in red is interpreted as a string. If this is the case in your actual code, the buildAll and pubLocal tasks will not be recognized, as they are part of a string rather than code.
UPDATE:
Since the above answer is irrelevant now, here is another possibility. The error message shows that only the "clean" task is listed in the dependsOn parameter. The buildAll task dependencies should be declared like this:
task buildAll(dependsOn: [clean, build, writePom])
Similar with the pubLocal task.
I'm using Gradle 2.4. The following file includes the Maven plugin, uses a list [] in the dependsOn, and ensures that clean must be executed before build:
apply plugin: 'maven'
task writePom << {
pom {
project {
groupId 'mygroup'
artifactId 'mylib'
version version
inceptionYear '2015'
licenses {
license {
name 'Blah'
url 'blah'
distribution 'blah'
}
}
}
}.writeTo("build/libs/pom.xml")
println "TRACER writePom"
}
task clean << { println "TRACER clean" }
task build << { println "TRACER build" }
build.mustRunAfter clean
task install << { println "TRACER install" }
task buildAll(dependsOn: [clean, build, writePom])
task pubLocal(dependsOn: [buildAll, install])
I get this output (minus Gradle 3 warnings):
bash-3.2$ gradle buildAll
:clean
TRACER clean
:build
TRACER build
:writePom
TRACER writePom
:buildAll
BUILD SUCCESSFUL
and this:
bash-3.2$ gradle pubLocal
:clean
TRACER clean
:build
TRACER build
:writePom
TRACER writePom
:buildAll
:install
TRACER install
:pubLocal
BUILD SUCCESSFUL

Resources