How to assign default values for ext based properties in gradle - gradle

I am working on a gradle plugin with a task where it accesses the extra params using the project object itself like
project.extraParam1
project.extraParam2
Now I can use this plugin from another project and pass the parameters in the build.gradle file as
ext {
extraParam1 value1
extraParam2 value2
}
I mean I apply this plugin in another project's build.gradle. Define the ext parameters and call the plugin task and it works. The task is able to access the extra properties. However, I want to set some default values to these, so that even though the project which is using the plugin doesn't define the ext parameter, it has some default values and works for default values.

In your plugin, you can do something like that :
def extraParam1 = project.hasProperty('extraParam1') ? project.extraParam1 : 'default value'

Related

Gradle artifacts declaration

I need some guidance and clarification about how artifacts are declared in gradle tasks, I would like to upload files to maven/artifactory reading these files from any kind of output container instead of having to hardcode the path for each artifact generated.
This is simpler if you have a JAR, ZIP, File, and a few other types, because you can make use of project.artifacts.add(...), but this is not trivial when you have some random file types.
Im going to provide an example to specify and clarify what I need exactly:
if I have:
task generateMyFile {
doLast {
buildDir.mkdirs()
['touch', new File(buildDir, 'myfile.random').absolutePath].execute().waitFor()
}
}
What's the right way to declare myfile.random as the output for generateMyFile ?
How do I declare myfile.random to be a valid artifact that will be used by maven/artifactory later by the 'publish' task ? currently I assume the file was generated in build/myfile.random, but Im looking for a smarter solution, and gradle documentation (or any other source) is not clear about this.
Thanks in advance

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
}

How and when to access in Gradle a property?

I have the following in build.gradle:
PlatformUmbrella platformUmbrella = PlatformUmbrella.create(System.properties['module.status'])
task setClBeforePublish << platformUmbrella.beforePublish
project.tasks.publish.doLast platformUmbrella.afterPublish
and gradle.properties has module.status = snapshot``gradlew properties outputs:
module.status: snapshot
But when either System.properties['module.status'] or gradle.properties['module.status'] is retrieved, null is returned (presumably because properties haven't been processed yet). Accessing gradle.properties['module.status'] inside a gradle.taskGraph.whenReady closure also returns null. What's the right way to access the 'module.status' setting?
Contents of gradle.properties will be automatically loaded into the project's "extra" properties extension, which are accessed via project.ext.
In your case, try project.ext["module.status"] instead.

How do I use inputs.property on a Gradle task, but with a closure for a value?

I'm trying to add an installer builder to my build configuration and I'm having a little trouble getting task inputs set up properly. I have the configuration split into a separate .gradle file and I add it to my project by doing the following.
project.ext.i4jArgs = [ "--verbose" ]
apply from: rootProject.projectDir.absolutePath + "/gradle/install4j.gradle"
To build the installers I'm calling a command line tool via exec. Almost everything is based on convention, but I want to optionally add a couple arguments / switches to the command from my main build file. I do it using the project.ext.i4jArgs property (above).
If I set the project.ext.i4jArgs property before applying my install4j.gradle file, I can use the following for inputs and everything seems to work.
inputs.property("i4jArgs", project.ext.has('i4jArgs') ? project.ext.i4jArgs : null)
However, if I apply my install4j.gradle file first and set the project.ext.i4jArgs property second, the project.ext.i4jArgs property is always null when I'm declaring inputs in my task (obviously). The API for TaskInputs (here) says I can pass a closure as a value. Is there a way I can use a closure to delay the evaluation of the project.ext.i4jArgs long enough to guarantee it's been initialized? I though the following would work, but the closure never gets called.
inputs.property("i4jArgs", {
project.afterEvaluate {
println "has args ${project.ext.has('i4jArgs')}"
project.ext.has('i4jArgs') ? project.ext.i4jArgs : null
}
})
I know writing a plugin that supports all the configuration I want might be a better option for the specific example I've given, but I'd like to figure out what I'm misunderstanding here anyway.
I would remove project.afterEvaluate in the first closure. This is for adding a closure that gets executed after the project has been configured.
What is actually going on is when gradle resolves the inputs, it calls the first closure, which then calls project.afterEvaluate, which adds a closure to the list that will be called when the project is done configuring... which will never be called because it is now in the execution phase.

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