Make The Sonar Runner Gradle Task Depend On One Of My Tasks - osgi

I am trying out the new Sonar Runner task recently released in gradle 1.5. What I would like to do is be able to make the sonar runner task dependent on another task so that I can set the Sonar properties correctly for this project (i.e. sonar.sources, sonar.binaries, sonar.libraries, sonar.java.source, sonar.java.target).
Specifically I am using an osgi build tool called bnd which will provide these values when an ant init task is executed (note that whilst I include the default bnd build.xml file, my complete build is really being done using gradle).
I thought I would be able to customize the sonar runner task by doing this (this is a multi-module build):
subprojects {
sonarRunner.dependsOn init
}
Eventually adding something like this (from what I understand of the bnd ant variables):
subprojects {
sonarRunner {
sonarProperties {
property "sonar.java.source", ant.property["project.sourcepath"]
property "sonar.java.target", ant.property["project.output"]
property "sonar.sources", ant.property["project.allsourcepath"]
property "sonar.libraries", ant.property["project.buildpath"]
}
}
sonarRunner.dependsOn init
}
Unfortunately when I try to add the dependsOn I get the error:
* What went wrong:
A problem occurred evaluating root project 'myproject'.
> Could not find property 'init' on project ':com.company.myproject.mymodule'.
If I try to make sonarRunner depend on a gradle task I get the following error:
* What went wrong:
A problem occurred evaluating root project 'myproject'.
> Could not find method dependsOn() for arguments [task ':gradletask'] on org.gradle.api.sonar.runner.SonarRunnerExtension_Decorated#c4d7c0c.
Am I missing something obvious here? If someone could point me in the right direction it would be a big help.

Your problem with not being able to call dependsOn() on sonarRunner task comes from the fact that the plugin defines both both sonarRunner extension and a sonarRunner task. It looks like extensions take precedence over tasks when objects are resolved by name in a gradle build file, hence your stacktrace points out that you are trying to call dependsOn() on an instance of org.gradle.api.sonar.runner.SonarRunnerExtension_Decorated instead of caling it on a SonarRunner task instance.
I think that if you retrieved the task from the task container explicitly you should be ok:
tasks.sonarRunner.dependsOn init

The root project gradle file is evaluated before the child project gradle files, that means init does not exist on the location you try to address it.
A workaround if you want to declare dependencies in the root project is to use afterEvaluate as described in http://www.gradle.org/docs/current/userguide/build_lifecycle.html, try:
subprojects {
afterEvaluate{
sonarRunner.dependsOn init
}
}
Another solution would be to add the dependency in the sub projects, directly or by applying another root gradle file.
apply from: '../sonardependency.gradle'

If anyone is interested, this is one way of getting the bnd information to be set correctly in Sonar for each subproject (I am sure there are better ways):
subprojects {
afterEvaluate {
sonarRunner {
sonarProperties {
ant.taskdef(resource:"aQute/bnd/ant/taskdef.properties",
classpath: "../cnf/plugins/biz.aQute.bnd/biz.aQute.bnd-2.0.0.jar");
def projectDir = project.rootDir.toString() + "/" + project.name;
ant.bndprepare(basedir:projectDir,print:"false",top:null);
def binaries = ant.properties['project.buildpath'].split(':') as ArrayList;
binaries.remove(0);
def binariesString = binaries.join(',');
properties["sonar.java.source"] = ant.properties['javac.source'];
properties["sonar.java.target"] = ant.properties['javac.target'];
properties["sonar.binaries"] = ant.properties['project.output'].replace(':',',');
properties["sonar.sources"] = ant.properties['project.sourcepath'].replace(':',',');
properties["sonar.libraries"] = binariesString;
}
}
}
}

Related

How to execute gradle task during project import in Intellij Idea

Let's assume my build.gradle file contains task generateSources which as name suggests generates additional java files. It's easy to ensure that generateSources is executed before compileJava: compileJava.dependsOn generateSources. How can I make sure generateSources is called when importing project into Intellij Idea as well?
To elaborate on #vladimir-sitnikov's answer: I added the idea-ext-plugin to my root project:
apply plugin: 'org.jetbrains.gradle.plugin.idea-ext'
// ...
buildscript {
dependencies {
classpath "org.jetbrains.gradle.plugin.idea-ext:org.jetbrains.gradle.plugin.idea-ext.gradle.plugin:0.7"
}
}
Because without that I wasn't able to use it in my sub project, but now it works like this:
idea.project.settings.taskTriggers {
beforeSync tasks.getByName("generateSources")
}
Adding the plugin to the sub-project only didn't do it.
Note: The plugin's documentation is kind of limited, but in "DSL spec v. 0.2" is stated
beforeSync - before each Gradle project sync. Will NOT be executed on initial import
Didn't try that, but it works with existing projects.
This can be done via id("org.jetbrains.gradle.plugin.idea-ext") plugin (https://github.com/JetBrains/gradle-idea-ext-plugin).
See sample code in Gradle sources: https://github.com/gradle/gradle/blob/135fb4751faf2736c231636e8a2a92d47706a3b9/buildSrc/subprojects/ide/src/main/kotlin/org/gradle/gradlebuild/ide/IdePlugin.kt#L147
You can set the task in Gradle tool window: Execute Before Sync:

Wrong order of task execution in gradle 3.3

I want to define methods inside my script file, and use them to define build tasks for each project individual (custom library).
ext.buildDockerImage = { imageName ->
def distDir = "${getProject().getBuildDir()}/docker"
copy {
from "${project.getProjectDir()}/src/docker/"
into distDir
}
println 'Build docker image'
}
In my project build.gradle I have created a task:
apply plugin: "war"
apply plugin: "jacoco"
dependency {
// all dependencies
}
task buildDocker() {
apply from: "${project.getRootDir()}/docker/scripts.gradle"
buildDockerImage("admin")
}
The problem is that whenever I am running gradle build, this tasks executes also:
$ gradle build -xtest
Build docker image
# rest of build
As you can see , all I want is to create a custom library that will hold methods, used to create tasks for each project. But currently I cannot import those methods without breaking the build. Method buildDockerImage will work only after war file is added to build directory, so this task must be executed on demand only, I don't want to be included in the process all the time.
My questions:
how make my task to only run when I execute task manually
why, when I execute my build, script executes as first?
Your task buildDocker() defines everything in configuration phase. So when you run your gradle build this will always run.
task buildDocker() {
apply from: "${project.getRootDir()}/docker/scripts.gradle"
buildDockerImage("admin")
}
If you want to run this task as a standalone task, define your stuff in execution phase of the task. something like below
task buildDocker() {
apply from: "${project.getRootDir()}/docker/scripts.gradle"
doLast{
buildDockerImage("admin")
}
}
Read This article
This might help

Execute Gradle task after subprojects are configured

I have a multi-project Gradle build where subprojects are assigned version numbers independent of the root project. I'd like to inject this version number into a few resource files in each subproject. Normally, I'd do this by configuring the processResources task for each subproject in the root build. However, the problem is that Gradle appears to be executing the processResources task before loading the subprojects' build files and is injecting "unspecified" as the version.
Currently, my project looks like this:
/settings.gradle
include 'childA' // ... and many others
/build.gradle
subprojects {
apply plugin: 'java'
apply plugin: 'com.example.exampleplugin'
}
subprojects {
// This has to be configured before processResources
customPlugin {
baseDir = "../common"
}
processResources {
// PROBLEM: version is "unspecified" here
inputs.property "version", project.version
// Inject the version:
from(sourceSets.main.resources.srcDirs) {
include 'res1.txt', 'res2.txt', 'res3.txt'
expand 'version':project.version
}
// ...
}
}
/childA/build.gradle
version = "0.5.424"
I looked into adding evaluationDependsOnChildren() at the beginning of root's build.gradle, but that causes an error because childA/build.gradle runs before customPlugin { ... }. I've tried using dependsOn, mustRunAfter, and other techniques, but none seem have the desired effect. (Perhaps I don't fully understand the lifecycle, but it seems like the root project is configured and executed before the subprojects. Shouldn't it configure root, then configure subprojects, and then execute?)
How can I get inject the version of each subproject into the appropriate resource files without a lot of copy/paste or boilerplate?
You could try using this method, with a hook:
gradle.projectsEvaluated({
// your code
})
I got this figured out for myself. I'm using a init.gradle file to apply something to the rootProject, but I need data from a subproject.
First option was to evaluate each subproject before I modified it:
rootProject {
project.subprojects { sub ->
sub.evaluate()
//Put your code here
But I wasn't sure what side effects forcing the sub project to evaluate would have so I did the following:
allprojects {
afterEvaluate { project ->
//Put your code here
Try doing it like this:
subprojects { project ->
// your code
}
Otherwise project will refer to your root project where no version has been specified.

Reading Gradle build parameters

I have a Gradle project with subprojects that I can issue separate build commands if I don't want to build all the subprojects at once. For example,
parent
subprojectA
subprojectB
subprojectC
I can then issue commands like ./gradlew :subprojectA:assemble :subprojectC:assemble. What I like to do is construct a meaning git tag from each subproject group and version values for those subprojects that are being built, i.e., group and version for only subprojectA and subprojectC in this case. I am thinking of writing a standalone plugin to do this but unsure where / how to get this information at build time. Any suggestions would be much appreciated.
Both group and version (as well as any other project property) is available globally in your build script.
task myTask << {
println group + "-" + version
}
If you are writing a binary plugin you can also access properties off the Project object itself via the property() method.
def group = project.property('group')
Edit
If you want to determine if a particular project is being built you can inspect the TaskExecutionGraph.
gradle.taskGraph.whenReady { graph ->
if (graph.hasTask(':subprojectA:assemble')) {
println 'Will build subprojectA'
}
}

Unable to overwrite a property in Gradle in Multi-Project build

I've setup a multi-module Gradle build, with several modules inside. What I'm trying to do is very simple - when I create a distribution, I'd always like to use a directory called "dist/lib", with the exception of one project, for which it should just be "dist".
The obvious solution - make a variable called "distLibDir", and overwrite it for the specific project in question, does not appear to be working.
Here's the code for the sub-module:
project.version = '1.1'
project.ext.distLibDir = 'dist'
dependencies {
....
}
And here's the code for the top-level project:
subprojects {
apply plugin: 'java'
apply plugin: 'eclipse'
if (! project.hasProperty('distLibDir')) {
project.ext.distLibDir = 'dist/lib'
}
task copyLib(type: Copy) {
into project.distLibDir
from configurations.runtime
}
task dist(type: Copy, dependsOn: [clean, jar, copyLib]) {
from 'build/libs'
into project.distLibDir
}
}
No matter what I try, the directory always comes out to be "dist/lib" and I can't overwrite it to be different for just that one module. Does anyone have insight into what is going wrong here?
By default, build scripts of parent projects get evaluated before build scripts of child projects. Hence the property doesn't exist at the time that you check for its existence.
There are several solutions. One is to set the property's value in the parent script's suprojects block, based on the name or path of the current project (e.g. if (project.path == ":foo") {...} else {...}). Another is to move the body of the subprojects block (or at least the part that makes use of the property) into a script plugin and apply that plugin from every build script (e.g. apply from: "$rootDir/gradle/foo.gradle"). This gives you a chance to set the property's value before applying the script plugin. Yet another solution (which I personally try to avoid) is to keep things as they are and call evaluationDependsOnChildren() before accessing the property from the parent build script.

Resources