How to execute tasks dynamically in Gradle 5? - gradle

In gradle 5, the execute() method is removed. What is the quickest way to migrate a gradle 4 tasks. I cannot use dependsOn because execution is dynamic based on e.g. the environmentName or another condition:
task clearData() {
doLast {
if ( environmentName in nonProductionEnvironments ) {
clearTask1.execute()
clearTask2.execute()
} else {
throw new GradleException("Not allowed to clear data in this environment.")
}
}
}

I'm not familiar with execute method from tasks, but if it must be dynamic then I suggest adding a listener somewhere depending what you're trying to react to.
There are:
Build listeners: https://docs.gradle.org/current/javadoc/org/gradle/BuildListener.html
Task listeners: https://docs.gradle.org/current/javadoc/org/gradle/api/execution/TaskExecutionGraph.html
There are more, but I believe one of those may solve your issue. Since dependsOn does not work for you, then doing whatever work you're trying to do as a Task does not sound like the right approach.

Related

Is it possible to run groovy method in stage block without wrapping it in a steps block (Declarative syntax)

I'm trying to get a Jenkinsfile to "generate" stages with the help of groovy methods. The main issue I have is that it does not allow you to run the method call in the stage without wrapping it in a 'steps' block, which makes it impossible to use it for defining an agent that uses docker, or to create dynamic stages (because they are not allowed in the steps block). The main reason I need this is because the Jenkinsfile we have currently has a lot of stages (each step requires a docker agent/worker) which causes way too much code duplication and makes it hard to maintain and add new stuff.
My experimental file looks like this
def generateStage(bar) {
agent {
docker {
image 'ubuntu:latest'
}
}
stage ("${bar}") {
steps {
sh "echo running in ${bar}"
}
}
}
pipeline {
agent any
stages {
stage('Main') {
steps {
generateStage("foo")
}
}
}
}
Is there a way to hack around this?
Jenkins throws this error when you remove the 'steps' block wrapping generateStage("foo")
Starting with version 0.5, steps in a stage must be in a ‘steps’ block.

Cannot have different system properties values for different tasks

I am trying to create 2 tasks to execute the sonarcube task. I want to be able to specify different properties depending on the task
task sonarqubePullRequest(type: Test){
System.setProperty( "sonar.projectName", "sonarqubePullRequest")
System.setProperty("sonar.projectKey", "sonarqubePullRequest")
System.setProperty("sonar.projectVersion", serviceVersion)
System.setProperty("sonar.jacoco.reportPath",
"${project.buildDir}/jacoco/test.exec")
tasks.sonarqube.execute()
}
task sonarqubeFullScan(type: Test){
System.setProperty("sonar.projectName", "sonarqubeFullScan")
System.setProperty("sonar.projectKey", "sonarqubeFullScan")
System.setProperty("sonar.projectVersion", serviceVersion)
System.setProperty("sonar.jacoco.reportPath",
"${project.buildDir}/jacoco/test.exec")
tasks.sonarqube.execute()
}
The tasks work but there seems to be an issue with the properties I am setting
if I run the first task which is sonarqubePullRequest then everything is fine, but if run sonarqubeFullScan then if uses the values specified in the sonarqubePullRequest. so the project name is set sonarqubePullRequest
it is as if those properties are set at run time and cannot be updated. I feel like I am missing something obvious any suggestions greatly received.
First of all: NEVER use execute() on tasks. The method is not part of the public Gradle API and therefor, its behaviour can change or be undefined. Gradle will execute the tasks on its own, either because you specified them (command line or settings.gradle) or as task dependencies.
The reason, why your code does not work, is the difference between the configuration phase and the execution phase. In the configuration phase, all the (configuration) code in your task closures is executed, but not the tasks. So, you'll always overwrite the system properties. Only (internal) task actions, doFirst and doLast closures are executed in the execution phase. Please note, that every task is only executed ONCE in a build, so your approach to parametrize a task twice will never work.
Also, I do not understand why you are using system properties to configure your sonarqube task. You can simply configure the task directly via:
sonarqube {
properties {
property 'sonar.projectName', 'sonarqubePullRequest'
// ...
}
}
Now you can configure the sonarqube task. To distinguish between your two cases, you can add a condition for different property values. The next example makes use of a project property as condition:
sonarqube {
properties {
// Same value for both cases
property 'sonar.projectVersion', serviceVersion
// Value based on condition
if (project.findProperty('fullScan') {
property 'sonar.projectName', 'sonarqubeFullScan'
} else {
property 'sonar.projectName', 'sonarqubePullRequest'
}
}
}
Alternatively, you can add another task of the type SonarQubeTask. This way, you could parametrize both tasks differently and call them (via command line or dependency) whenever you need them:
sonarqube {
// Generated by the plugin, parametrize like described above
}
task sonarqubeFull(type: org.sonarqube.gradle.SonarQubeTask) {
// Generated by your build script, parametrize in the same way
}

gradle: how do I list tasks introduced by a certain plugin

Probably a simple question but I can't find a way to list which tasks are introduced by the plugins that get applied in a build.gradle file.
So, say that your build.gradle is simply:
apply plugin: 'java'
is there a simple way to make gradle list all the tasks introduced by that plugin?
PS: that would come handy in case of messy and large build files with dozens of applied plugins
PS2: I'm not asking about the dependencies of the tasks. My question is different and quite clear. Each plugin that I apply introduces some tasks of its own (never mind what depends on what). The question is which are the newly introduced tasks in the first place?
I'm afraid it is not possible because of the nature how gradle plugins are applied.
If you take a look at Plugin interface, you will see it has a single apply(Project p) method. Plugin responsibility is to configure a project - it can add specific tasks / configurations / etc. For example, gradle JavaPlugin is stateless, so you can't get tasks from it.
The only solution that comes to mind is to get a difference of tasks after the plugin is applied:
build.gradle
def tasksBefore = [], tasksAfter = []
project.tasks.each { tasksBefore.add(it.name) } // get all tasks
apply(plugin: 'idea') // apply plugin
project.tasks.each { tasksAfter.add(it.name) } // get all tasks
tasksAfter.removeAll(tasksBefore); // get the difference
println 'idea tasks: ' + tasksAfter;
This will print tasks that were added by Idea plugin:
idea tasks: [cleanIdea, cleanIdeaModule, cleanIdeaProject,
cleanIdeaWorkspace, idea, ideaModule, ideaProject, ideaWorkspace]
You can play a bit with this code and build an acceptable solution.
In some cases origin from specific plugin can be restored by checking the task's group and name:
tasks.findAll { it.group == 'verification' && it.name.startsWith('jacoco') }.each { task ->
println(task.name)
}

Gradle - how to set up-to-date parameters on a predefined task?

I could really use some help with this!
The gradle docs say that to make the up-to-date logic to function, just do this:
task transform {
ext.srcFile = file('mountains.xml')
ext.destDir = new File(buildDir, 'generated')
inputs.file srcFile
outputs.dir destDir
This is all well and good for tasks you are defining. However, I am using the eclipse plugin to do some modification to the .classpath file. Up-to-date does not work. That is, it runs the task over and over again out of the box (at least for me). Here is what I have:
eclipse {
classpath {
//eclipseClasspath.inputs.file // something like this??? but what to set it to?
//eclipseClasspath.outputs.file // here too
file {
withXml {
def node = it.asNode()
// rest of my stuff here
I tried a couple of things where I have the two commented out lines. Since those didn't work, I realized I didn't really have a clue and could use some help! Thanks in advance!
In my experience, the Eclipse tasks should not rerun every single time. That makes me think that you are doing something to cause either the inputs or outputs to change. If you are modifying your Eclipse project after Gradle generates it or changing dependencies, etc, you would naturally be triggering the upToDate checks.
If you really do need to force it to run every time, you might be able to get it to work with this. I'm not sure if I've ever tried using this when other outputs are already defined.
eclipseClasspath {
outputs.upToDateWhen { true } //there isn't an equivalent for inputs
}
One important note is that what you were using is the Eclipse model that describes your project, not the actual task itself:
eclipse { //this is the eclipse model
classpath {
}
}
eclipseClasspath {
//this is a task
}
eclipseProject {
//this is a task
}

Dynamically configuring a task in a parent build.gradle

I have a multi-project C++ Gradle build, which produces a number of libraries and executables. I'm trying to get the executables (but not the libraries) subprojects to get compiled in with a 'fingerprint' object. This works fine if I sprinkle smth like this in individual subprojects' build.gradle:
compileMain.doFirst {
// code to generate a 'BuildInfo.cpp' from from a template.
// embeds name of executable in so has to be generated anew for each exe
}
Following DRY principles, I'd much rather do this once and for all in a top level build.gradle. This is my attempt, to apply it to just the subprojects that use the cpp-exe plugin, following these instructions:
configure(subprojects.findAll { it.plugins.hasPlugin('cpp-exe') }) {
compileMain.doFirst {
// same code as above
}
}
Alas, this doesn't get triggered. However, if I put smth like this in a less restrictive configure, block, this demonstrates that the idea of querying the plugin should work:
configure(subprojects.findAll { true }) {
task mydebug << {
if ( project.plugins.hasPlugin( 'cpp-exe' ) ) {
println ">>> $project.name has it!"
}
}
}
Could it be that the plugins don't get applied to the subprojects at the time the configure closure is evaluated (in the top-level build.gradle)? There may well be a much simpler way of achieving this altogether?
You probably apply the cpp-exe plugin in the child projects' build scripts. By default, a parent build script gets evaluated before its children, which explains why it's not finding any projects that have cpp-exe applied.
There are several ways to solve this problem. One way is to move all configuration that's specific to a cpp-exe project (like applying the plugin and adding the action) to the same spot. Either you do all such configuration from the parent build script (for example by enumerating the cpp-exe subprojects and configuring them with a single configure(cppExeProjects) { ... }), or you move the cpp-exe specific configuration into its own build script (say gradle/cpp-exe.gradle) and apply it from selected subprojects like so: apply from: "$rootDir/gradle/cpp-exe.gradle".
Another solution is to change the evaluation order of build scripts. But I would only use this as a last resort, and it is certainly not necessary here.
Gradle 1.5 is recently out, I am not sure if this is a new feature but as it looks, you can solve the issue by using afterEvaluate.
Take a look at section 53.6.1 in http://www.gradle.org/docs/current/userguide/build_lifecycle.html
Something like:
subprojects {subProject ->
afterEvaluate {
if ( subProject.plugins.hasPlugin('cpp-exe')){
println "Project $subProject.name has plugin cpp-exe"
}
}
}
would give you a start.

Resources