Checkstyle Plugin does not add gradle tasks - android

i want to use checkstyle plugin in my gradle project, the gradle documentation says that it will add a few tasks:
https://docs.gradle.org/current/userguide/checkstyle_plugin.html
checkstyleMain, checkstyleTest, checkstyleSourceSet
I added this into my app build.gradle file:
apply plugin: 'checkstyle'
I want to run gradle task from cmd to perform code style check, but there are no one checkstyle task. I checked the whole list by typing:
./gradlew tasks
I also tried to add checkstyle jar as library dependency to app module.
Can anyone tell me what i am doing wrong and how can i get my checkstyle tasks?

Well, the checkstyle plugin adds its tasks in the Other tasks virtual task group. Those are really the tasks which have not been assigned to a task group. So, they are shown only when you run ./gradlew tasks --all (note the --all).
Complete working build.gradle:
apply plugin: 'java';
apply plugin: 'checkstyle';
Then run ./gradlew tasks --all, output:
<...snip...>
Other tasks
-----------
checkstyleMain - Run Checkstyle analysis for main classes
checkstyleTest - Run Checkstyle analysis for test classes
<...snip...>
If you want the Checkstyle tasks to appear without --all, then assign them to a task group, for example:
tasks.withType(Checkstyle).each {
it.group = 'verification'
}

Looking at other Android projects, built with Gradle, that run checkstyle (thanks Square) I found that I needed to do some setup for the task to appear. Without the task declaration I would still see my initial error.
build.gradle:
...
apply plugin: 'checkstyle'
...
checkstyle {
configFile rootProject.file('checkstyle.xml')
ignoreFailures false
showViolations true
toolVersion = "7.8.1"
}
task Checkstyle(type: Checkstyle) {
configFile rootProject.file('checkstyle.xml')
source 'src/main/java'
ignoreFailures false
showViolations true
include '**/*.java'
classpath = files()
}
// adds checkstyle task to existing check task
afterEvaluate {
if (project.tasks.getByName("check")) {
check.dependsOn('checkstyle')
}
}

You also need a checkstyle configuration file, either by placing one at the default location as documented or by configuring it explicitly.
For example:
checkstyle {
config = resources.text.fromFile('config/checkstyle.xml')
}

Related

The use of safeArgs in Android Studio is causing an error and I cannot build the project

I am trying to build my project in Kotlin and I am getting this error:
Execution failed for task ':app:generateSafeArgsDebug'.
Could not read 'F:\Program Files\Android Projects\CityOnApp\crowdapps-mobile-android\app\build\intermediates\metadata_application_id\debug\application-id.txt' as it does not exist.
and when I added in Settings > Build, Execution, Deployment > Compiler > Command Line Options :
--stacktrace --debug -Pandroid.debug.obsoleteApi=true, then I got :
[ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]
Execution failed for task ':app:generateSafeArgsDebug'.
Could not read 'F:\Program Files\Android Projects\CityOnApp\crowdapps-mobile-android\app\build\intermediates\metadata_application_id\debug\application-id.txt' as it does not exist.
I checked the path and the file does not exist there!
I have the latest version in Kotlin and Android Studio.
What I tried and did not work is :
clean build and rebuild/ build
downgrading the version of Android Studio
deleting the .gradle file from the root directory
plugins {
id 'com.android.application' version '7.1.0' apply false
id 'com.android.library' version '7.1.0' apply false
id 'org.jetbrains.kotlin.android' version '1.6.10' apply false
id 'androidx.navigation.safeargs.kotlin' version '2.4.1' apply false
}
To add Safe Args to your project, include the following classpath in your top level build.gradle file:
buildscript {
repositories {
google()
}
dependencies {
def nav_version = "2.3.4"
classpath "androidx.navigation:navigation-safe-args-gradle-plugin:$nav_version"
}
}
You must also apply one of two available plugins.
To generate Java language code suitable for Java or mixed Java and Kotlin modules, add this line to your app or module's build.gradle file:
apply plugin: "androidx.navigation.safeargs"
Alternatively, to generate Kotlin code suitable for Kotlin-only modules add:
apply plugin: "androidx.navigation.safeargs.kotlin"
You must have android.useAndroidX=true in your gradle.properties file as per Migrating to AndroidX.
Source : Official Documentation
Try upgrading/downgrading the gradle plugin.
classpath 'com.android.tools.build:gradle:x.x.x'
Try upgrading/dowgrading gradle wrapper properties
distributionUrl=https\://services.gradle.org/distributions/gradle-x.x.x-bin.zip
Try invalidating caches in Android Studio through the file menu.
Try running Android Studio in admin/sudo.
Check your (git/local)history to see if anything changed that could cause this.
If all else fails, reinstall Android Studio and freshly import your project entirely.
To add safe-args
add this dependencies to build.gradle(project) before plugins{}block on the top
buildscript {
repositories {
google()
}
dependencies {
classpath("androidx.navigation:navigation-safe-args-gradle-plugin:2.4.2")
}}
this to the build.gradle(Module) file inside plugin{}block
id("androidx.navigation.safeargs.kotlin")
After adding Rebuild the project this will implement the safe-args

Task not found in root project

I am confused by gradle build lifecycle for a few days. Refer tells me
A Gradle build has three distinct phases.
Initialization
Configuration
Execution
Is task creation in the third step? If so, how does gradle find all tasks in a project object?
Here is an example.
rootporject
|----app
|----build.gradle
|----checkstyle.gradle
The build.gradle is as simple as normal.checkstyle.gradle file has a task. Here is its content.
apply plugin: 'checkstyle'
task checkstyle(type:Checkstyle) {
description 'Runs Checkstyle inspection against girl sourcesets.'
group = 'Code Quality'
configFile rootProject.file('checkstyle.xml')
ignoreFailures = false
showViolations true
classpath = files()
source 'src/main/java'
}
After ./gradlew -q tasks, there is no task checkstyle.
But if I remove the definition into build.gradle, I get it.
Is there anything wrong?Thanks in advance.
Edit
From doc
There is a one-to-one relationship between a Project and a build.gradle file.
You haven't applied your other script.
In your build.gradle you should add an apply from: 'checkstyle.gradle'.

Why the gradle war task is skipped?

I am a new convert to Gradle. Most of the tasks work fine. However, I see that the war task is always skipped. When I run in the debug mode, I see the following logs -
09:12:34.889 [LIFECYCLE] [class
org.gradle.internal.buildevents.TaskExecutionLogger] :war 09:12:34.889
[DEBUG]
[org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter]
Starting to execute task ':war' 09:12:34.889 [INFO]
**[org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter] Skipping task ':war' as task onlyIf is false.** 09:12:34.889 [DEBUG]
[org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter]
Finished executing task ':war' 09:12:34.889 [LIFECYCLE] [class
org.gradle.internal.buildevents.TaskExecutionLogger] :war SKIPPED
I am not sure why onlyIf is false. I did search on internet. But I did not find anything related.
Here is my Gradle file -
buildscript {
ext {
springBootVersion = '2.0.0.M2'
}
repositories {
mavenCentral()
maven { url "https://repo.spring.io/snapshot" }
maven { url "https://repo.spring.io/milestone" }
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
// Apply the java-library plugin to add support for Java Library
apply plugin: 'java-library'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
apply plugin: 'war'
apply plugin: 'checkstyle'
apply plugin: 'pmd'
apply plugin: 'findbugs'
apply plugin: 'jacoco'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
jcenter()
mavenCentral()
maven { url "https://repo.spring.io/snapshot" }
maven { url "https://repo.spring.io/milestone" }
}
dependencies {
compile('org.springframework.boot:spring-boot-starter')
compile("org.springframework.boot:spring-boot-starter-web")
compile("org.springframework.retry:spring-retry:1.2.1.RELEASE")
compile("org.springframework.data:spring-data-cassandra:2.0.0.M4")
compile("io.reactivex.rxjava2:rxjava:2.1.1")
//compile("javax.persistence:persistence-api:1.0.2")
//compile("org.hibernate.javax.persistence:hibernate-jpa-2.0-api:1.0.1.Final")
compile("org.springframework.boot:spring-boot-starter-data-jpa")
compile("com.zaxxer:HikariCP:2.6.0")
// Test Dependencies
testCompile("org.springframework.boot:spring-boot-starter-test")
testCompile("org.powermock:powermock-mockito-release-full:1.6.4")
testCompile("org.mockito:mockito-core:2.0.3-beta")
testCompile("org.cassandraunit:cassandra-unit:3.1.3.2")
testCompile("org.cassandraunit:cassandra-unit-spring:2.2.2.1")
testCompile("com.h2database:h2:1.4.196")
// This dependency is exported to consumers, that is to say found on their compile classpath.
api 'org.apache.commons:commons-math3:3.6.1'
// This dependency is used internally, and not exposed to consumers on their own compile classpath.
implementation 'com.google.guava:guava:21.0'
testImplementation 'junit:junit:4.12'
}
Here is the image of my project structure -
If you could help me with generating the war file that would be great.
try it
war {
enabled = true
}
I have also faced same issue with jar task, it is skipping the jar generation as it is taking the default value for enabled=false if you dont specify any external value.
Same solution works for jar as well based on #Alexander Servetnik
Enrironment:
SpringBoot 2.x and
gradle 4.4
jar {
baseName = <your-jar name>
enabled=true
}
Try upgrading gradle version
Spring Boot’s Gradle plugin requires Gradle 6 (6.3 or later). Gradle 5.6 is also supported but this support is deprecated and will be removed in a future release.
https://docs.spring.io/spring-boot/docs/current/gradle-plugin/reference/html/
This is because the Springboot Gradle plugin will create a bootJar task and by default will disable jar and war task.
You can enable this, by adding the below code in projectName.gradle
jar {
baseName = 'projectName'
enabled=true
manifest {
....
}
}

Run firebaseUploadReleaseProguardMapping task from app/build.gradle file

Is there any way to run gradle task from app/build.gradle file, so that when I build release APK task "firebaseUploadReleaseProguardMapping" will run automatically.
You can use dependsOn for example (your app/build.gradle):
apply plugin: 'com.android.application'
apply plugin: 'com.google.firebase.firebase-crash'
android {
}
dependencies {
}
task release
task archiveRelease(type: Copy) {
from './build/outputs/apk', './build/outputs/'
into "../releases/${rootProject.ext.configuration.version_code}"
include('app-release.apk', 'mapping/release/mapping.txt')
rename('app-release.apk', "${rootProject.ext.configuration.package}_${rootProject.ext.configuration.version_name}_${rootProject.ext.configuration.version_code}.apk")
}
project.afterEvaluate {
dependencyUpdates.dependsOn clean
assembleRelease.dependsOn clean
def publishApkRelease = project.tasks.getByName("publishApkRelease")
publishApkRelease.dependsOn assembleRelease
release.dependsOn publishApkRelease, firebaseUploadReleaseProguardMapping, archiveRelease
}
I created a new task called release. It depends on publishApkRelease (comes from gradle-play-publisher), firebaseUploadReleaseProguardMapping and archiveRelease. And publishApkRelease depends on assembleRelease.
At the ned you just call ./gradlew release and it will build your release version, uploads the apk to Google play, the mapping file to Firebase and archive a copy of the apk and mapping file.

Get Android gradle plugin & checkstyle working together / command line usage

I'm evaluating the ability of the new gradle-based build system to reproduce our current ant-based build process and, as a gradle beginner, I failed to get checkstyle running with the android gradle plugin.
Environment:
gradle 1.6 running fine on a standard java project (checkstyle check target included)
up-to-date android SDK (22.0.1 with platform tools and build tools 17)
no eclipse, no android studio, only my lovely terminal
Symptom:
The target project is https://github.com/nibua-r/LigoTextDemo and I succeeded to build it using gradle but if I naively add apply plugin: checkstyle to my build.gradle:
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.4.2'
}
}
apply plugin: 'android'
apply plugin: 'checkstyle'
android {
buildToolsVersion '17'
compileSdkVersion 15
testBuildType 'debug'
defaultConfig {
versionCode = 1
versionName = '1.0'
minSdkVersion 12
targetSdkVersion 15
}
buildTypes {
debug {
packageNameSuffix = '.debug'
}
}
}
then gradle check doesn't even complain on not finding the checkstyle.xml file (at the default config/checkstyle location) and returns:
:check UP-TO-DATE
BUILD SUCCESSFUL
What's needed:
First, I just need a running checkstyle target. Then, I need to automate checkstyle running as a dependency of the compilation (but lets get the chekstyle target up and running first).
Assumption:
This may be related to the fact that (from the [user guide][1]):
The Android plugin […] uses its own sourceSets
but I'm not enough gradle-efficient to understand what I'm missing there. Please, gradle Master, enlighten me with your valuable knowledge!
I got pmd, findbugs, and checkstyle working with Gradle 1.12 android plugin 0.12.+ using the following script:
apply plugin: 'checkstyle'
apply plugin: 'findbugs'
apply plugin: 'pmd'
check.dependsOn 'checkstyle', 'findbugs', 'pmd'
task checkstyle(type: Checkstyle) {
configFile file("${project.rootDir}/config/quality/checkstyle/checkstyle.xml")
source 'src'
include '**/*.java'
exclude '**/gen/**'
classpath = files()
}
task findbugs(type: FindBugs) {
ignoreFailures = true
effort = "max"
reportLevel = "high"
excludeFilter = new File("${project.rootDir}/config/quality/findbugs/findbugs-filter.xml")
classes = files("$project.buildDir/intermediates/classes/")
source 'src'
include '**/*.java'
exclude '**/gen/**'
reports {
xml {
destination "$project.buildDir/reports/findbugs/findbugs.xml"
xml.withMessages true
}
}
classpath = files()
}
task pmd(type: Pmd) {
ruleSetFiles = files("${project.rootDir}/config/quality/pmd/pmd-ruleset.xml")
ignoreFailures = true
ruleSets = ["basic", "braces", "strings"]
source 'src'
include '**/*.java'
exclude '**/gen/**'
reports {
xml.enabled = true
html.enabled = false
}
}
Running gradle build in command line will run all code quality plugins and generate xml reports in app/build/reports/ which are then ready to be viewed or parsed by CI tools.
Someone has a great answer to solve integrating PMD, findbugs and checkstyle with Gradle for Android.
Unfortunately, the only solution for now is based on ant :
http://sethrylan.org/2013/07/14/gradle-android-findbugs.html
I wish gradle will one day allow to do as much as maven for Android.
--- Update as of October 2013
With Gradle 1.8 and Android plugin for Gradle 0.6.+, you don't need this anymore. Android sourcesets and configurations are now compatible with the java plugin and all quality plugin work out of the box.
This includes pmd, findbugs, checkstyle and classycle.
--- Update
A configuration, largely inspired from the project mentioned above, is proposed in this open source project as well, plus other tools.
To get this to work with my Android project, I had to declare the task explicitly.
Here's what worked for me:
apply plugin: 'checkstyle'
task checkstyle(type: Checkstyle) {
source 'src'
include '**/*.java'
exclude '**/gen/**'
// empty classpath
classpath = files()
}
Be mindful that the Android plugin may choose to create a task of the same name in the future or work in conjunction with the checkstyle plugin in different ways.
You can try Android Check plugin (https://github.com/noveogroup/android-check):
Checkstyle
PMD
Configuration:
buildscript {
repositories { jcenter() }
dependencies {
...
classpath 'com.noveogroup.android:check:+'
...
}
}
apply plugin: 'com.noveogroup.android.check'
You can use hardcore configuration:
check {
abortOnError true
checkstyle { config hard() }
pmd { config hard() }
}
I found by digging on the web that the Android plugin depends on java-base and not java (i.e. the sourceSets management is specific) and the checkstyle plugin rely on java. As a consequence, some gradle upstream modification are needed to get the thing done. The gradle team is working on that, as seen on twitter:
#anzix Android source sets will be soon understood by the generic code quality plugins. Work on that has already started.— Gradle Build System (#Gradleware) May 26, 2013
Take a look at the Soter Gradle plugin to semlessly add support for Findbugs, Checkstyle and PMD to Android projects.

Categories

Resources