Gradle task dependency order - gradle

I have a problem with a custom gradle task : i would like to copy my android jar library and rename it after that it as executed a 'clean build'
Here is how i defined it :
task('CreateJar', type: Copy, dependsOn: [':mylibmodule:clean', ':mylibmodule:build']){
doLast {
from('build/intermediates/bundles/release/')
into('libs')
include('classes.jar')
rename('classes.jar', 'MyLib.jar')
}
}
The problem is that in the gradle log results, the 'clean' is done after the 'build' task, so that the lib is never copied to the destination folder :
...
:mylibmodule:testReleaseUnitTest
:mylibmodule:test
:mylibmodule:check
:mylibmodule:build
:mylibmodule:clean
:mylibmodule:CreateJar NO-SOURCE
I have also tried to change the order of tasks in the 'dependsOn:[]', but it does not change anything... Does anyone has any idea of where is my mistake ?
Thanks in advance

The dependsOn list does not impose any ordering guarantees. Usually what is listed first is executed first if there are not other relations that actually do impose ordering guarantees.
(One example is if clean depends on build, then it doesn't matter how you define it in that dependsOn attribute, becuase build will always be run before clean. That this is not the case is clear to me, thus in parentheses, just to clarify what I mean.)
To determine why finally build is run before clean I cannot say without seeing the complete build script. From what you posted it is not determinable.
Maybe what you are after is clean.shouldRunAfter build or clean.mustRunAfter build which define an ordering constraint without adding a dependency. So you can run each task alone, but if both are run, then their order is defined as you specified it. The difference between those two is only relevant if parallelizing task execution, then should run after means they could run in parallel iirc, must run after does not allow that.

Related

How to define gradle task dependencies - inputs outputs OR dependsOn?

To get the incremental build support running correctly in gradle it is required to define the "inputs" and "outputs" in each (custom-) tasks.
That's a very neat way of gradle to check if a task can be skipped cause it is up-to-date or not. Sample:
task myTaskA {
def someOutputDir = file("$buildDir/gen")
// define task outputs (input not required here)
outputs.dir someOutputDir
doLast{
// generate something into the defined output directory
new File(someOutputDir, "dummy.txt").text = "Gradle sample"
}
}
task myTaskB {
// Input of this task is dependent on the output of myTaskA
inputs.files myTaskA
doLast{
// do something
}
}
Yes, that is pretty nice and additionally the good thing is, we do not need to declare a explicit dependency instruction (dependsOn) in task "myTaskB".
dependsOn myTaskA
This directive is not necessary cause we have a implicit dependency defined by the inputs-declaration.
I think it is a good style to provide always a inputs/outputs definition in custom tasks to support incremental builds.
BUT: This also means we can completely ignore the dependsOn.
SO: When should we prefer dependsOn over inputs/outputs?
Maybe if there is no inputs or outputs. Yes, but are there other use cases conceivable? I was always working with dependsOn, and this seams to me as obsolete now. What do you think?
Bye have a great day, Tony

Execute more than one command in a task without breaking incremental build

We use gradle incremental builds and want to run two commands (ideally from one task). One of the solutions here worked getting the two commands running... however it breaks incremental builds.. It looks something like:
task myTask() {
inputs.files(inputFiles)
project.exec {
workingDir web
commandLine('mycmd')
}
project.exec {
workingDir web
commandLine('mysecond-cmd')
}
}
if running a single command and incremental builds is working, the task looked similar to this, the thing that seems to make the difference is the workingDir:
task myTask(type: Exec) {
workingDir myDir // this seems to trigger/enable continuos compilation
commandLine ('myCmd')
}
the best alternative so far is create 3 tasks, one for each of the cmdline tasks I want to run and a third one to group them, which seems dirty.
The question is: Is there a way to run two or more commands in one task with incremental builds still working?
I'll try to answer the question from the comments: how can I signal from a task that has no output files that the build should watch certain files. Unfortunately, this is hard to answer without knowing the exact use case.
To start with, Gradle requires some form of declared output that it can check to see whether a task has run or whether it needs to run. Consider that the task may have failed during the previous run, but the input files haven't changed since then. Should Gradle run the task?
If you have a task that doesn't have any outputs, that means you need to think about why that task should run or not in any given build execution. What's it doing if it's not creating or modifying files or interacting with another part of the system?
Assuming that incremental build is the right solution — it may not be — Gradle does allow you to handle unusual scenarios via TaskOutputs.upToDateWhen(Action). Here's an example that has a straightforward task (gen) that generates a file that acts as an input for a task (runIt) with no outputs:
task gen {
ext.outputDir = "$buildDir/stuff"
outputs.dir outputDir
doLast {
new File(outputDir, "test.txt").text = "Hurray!\n"
}
}
task runIt {
inputs.dir gen
outputs.upToDateWhen { !gen.didWork }
doLast {
println "Running it"
}
}
This specifies that runIt will only run if the input files have changed or the task gen actually did something. In this example, those two scenarios equate to the same thing. If gen runs, then the input files for runIt have changed.
The key thing to understand is that the condition you provide to upToDateWhen() is evaluated during the execution phase of the build, not the configuration phase.
Hope that helps, and if you need any clarification, let me know.

Running tasks from an included gradle build in order

I have a gradle composite build project, which runs tasks from an included build. I am not able to make changes to the included build.
For a certain task, I want to first clean the included build and then build it. I.e., I want to do (loosely):
some-project:clean
some-project:build
where some-project is the included build. I tried doing this by setting up tasks which depend on those external tasks:
task cleanIncludedBuild {
dependsOn gradle.includedBuild("some-project").task("clean")
}
task buildIncludedBuild {
dependsOn cleanIncludedBuild
dependsOn gradle.includedBuild("some-project").task("build")
}
However, since there is no ordering between dependencies, this execution order is valid as declared:
some-project:build
some-project:clean
cleanIncludedBuild
buildIncludedBuild
Though this is of course not what I'm after.
I thought of doing something like
gradle.includedBuild("some-project").task("build").dependsOn cleanIncludedBuild
but the value returned by task() above is of type IncludedBuildTaskReference, which essentially are read-only references to the underlying task, and do not allow adding dependencies.

Task with path 'build' not found in root project

I have a multiproject and after the last subproject is built, I'd like to process all jars.
Therefore I created a task in the root-project:
task install(dependsOn: 'build', type: Copy) {
doLast {
println "exec install task"
}
}
Upon calling ./gradlew install in the root directory, I'm facing this error:
FAILURE: Build failed with an exception.
* What went wrong:
Could not determine the dependencies of task ':install'.
> Task with path 'build' not found in root project 'foo'.
However, calling ./gradlew tasks shows me these tasks:
:tasks
------------------------------------------------------------
All tasks runnable from root project
------------------------------------------------------------
Build tasks
-----------
assemble - Assembles the outputs of this project.
build - Assembles and tests this project.
...
How can I achieve the desired functionality?
I assume, that your root project organizes the build, but does not define build action taken by itself. The build task is often defined by language plugins (in most cases via apply plugin: 'java'), but if your root project does not use any of them, it won't have a build task.
The description of the help task tasks, which you used, says:
Displays the tasks runnable from root project 'projectReports' (some of the displayed tasks may belong to subprojects).
The help task followes the same logic as the task activation via the command line. You can provide a task name and any task with the name in any subproject will be executed (thats why gradle build works).
But if you define a dependsOn dependency, the given string is evaluated as task path for a single task. Since each task name can only be used once in a project, the name is unique for tasks in the root project, but many tasks could be found, if subprojects would be considered. Therefor, one can use the syntax :<projectName>:<taskName> to identify tasks in subprojects.
Now, let's face your specific problem: If the install task should depend on the build task of one single subproject, you could use dependsOn ':<mySubproject>:build'. But I assume you want the install task to depend on each subproject build task, so I'd like to propose this approach:
task install(type: Copy) {
dependsOn subprojects*.tasks*.findByName('build').minus(null)
doLast {
println "exec install task"
}
}
This way, for each registered subproject, findByName('build') is called and the result (the found task or null) is put into a list, which is then used as task dependency list. I added the .minus(null) part to remove null entries from the list, because I am not sure how Gradle handles such entries in a dependency collection. If you are sure, that each subproject provides a build task, you can use getByName('build'), too.
EDIT: OP found the optionally recursive getTasksByName method, which suits this case even better than iterating over all subprojects manually:
dependsOn getTasksByName('build', true)

Why do my Gradle tests run repeatedly?

I have a pretty standard Gradle build that's building a Java project.
When I run it for the first time, it compiles everything and runs the tests. When I run it a second time without changing any files, it runs the tests again.
According to this thread, Gradle is supposed to be lazy by defaut and not bother running tests if nothing has changed. Has the default behaviour here been changed?
EDIT:
If I run gradle test repeatedly, the tests only run the first time and are subsequently skipped. However, if I run gradle build repeatedly, the tests get re-run every time, even though all other tasks are marked as up-to-date.
the gradle uptodate check logs on info level why a task is not considered to be up-to-date. please rerun the "gradle build -i" to run with info logging at check the logging output.
cheers,
René
OK, so I got the answer thanks to Rene prompting me to look at the '-i' output...
I actually have 2 test tasks: the 'test' one from the Java plugin, and my own 'integrationTest' one. I didn't mention this in the question because I didn't think it was relevant.
It turns out that these tasks are writing their output (reports, etc.) to the same directory, so Gradle's task-based input and output tracking was thinking that something had changed, and re-running the tests.
So the next question (which I will ask separately) becomes: how do I cleanly (and with minimal Groovy/Gradle code) completely separate two instances of the test task.
You need to create test tasks in your build.gradle and then call those specific tasks to run a specific set of tests. Here is an example that will filter out classes so that they don't get run twice (such as when running a suite and then re-running its child classes independently):
tasks.withType(Test) {
jvmArgs '-Xms128m', '-Xmx1024m', '-XX:MaxPermSize=128m'
maxParallelForks = 4 // this runs tests parallel if more than one class
testLogging {
exceptionFormat "full"
events "started", "passed", "skipped", "failed", "standardOut", "standardError"
displayGranularity = 0
}
}
task runAllTests(type: Test) {
include '**/AllTests.class'
testReportDir = file("${reporting.baseDir}/AllTests")
testResultsDir = file("${buildDir}/test-results/AllTests")
}
task runSkipSuite(type: Test) {
include '**/Test*.class'
testReportDir = file("${reporting.baseDir}/Tests")
testResultsDir = file("${buildDir}/test-results/Tests")
}
Also, concerning your build question. The "build" task includes a clean step which is cleaning tests from your build directory. Otherwise the execution thinks the tests have already been ran.

Resources