How to find Gradle task that creates some specific output? - gradle

I'd like to create a task that would take as input the #OutputFile of some other task. I know the output file that needs to be taken as input but not the task that creates that output file so that the task that uses the output can dependsOn the output creator. How do I find which task creates that output?
More concretely:
$unknownTask creates someKnownOutput
newTask uses someKnownOutput
newTask would like to dependsOn $unknownTask
How can the value of $unknownTask be found?

The following should print out the tasks whose output is thisIsTheOne:
task findTaskCreatingSpecificOutput() {
doLast {
subprojects { subproject ->
subproject.tasks.findAll { task ->
task.outputs.getFiles().getFiles().findAll { output ->
output == 'thisIsTheOne'
}
}.flatten().each { println it }
}
}
}

Related

Executing task on its own is working but not when executed from another one

I have three Gradle tasks if I execute them one by one on its own then its working. But when I execute them from another task then its not working. Here is how my task looks like
import com.github.gradle.node.npm.task.NpmTask
plugins {
id("com.github.node-gradle.node") version "3.4.0"
}
// Executing this task on its own is working
tasks.register<NpmTask>("buildFrontEnd") {
workingDir.set(file("${projectDir}/frontend"))
args.set(listOf("run", "build"))
}
// Executing this task on its own is working
tasks.register<Delete>("cleanFrontEnd") {
delete(
fileTree("${projectDir}/backend/main/resources/static/js"),
)
}
// Executing this task on its own is working
tasks.register<Copy>("copyFrontEnd") {
into("$projectDir")
copy {
from("${projectDir}/frontend/dist/css")
into("${projectDir}/backend/main/resources/static/css")
}
copy {
from("${projectDir}/frontend/dist/js")
into("${projectDir}/backend/main/resources/static/js")
}
}
// This tasks is not executing "copyFrontEnd"
tasks.register("frontEndBuild") {
dependsOn("buildFrontEnd", "cleanFrontEnd", "copyFrontEnd")
tasks.findByName("copyFrontEnd")?.mustRunAfter("buildFrontEnd", "cleanFrontEnd")
// Tried this too but it is not working
// tasks.findByName("cleanFrontEnd")?.mustRunAfter("buildFrontEnd")
// tasks.findByName("copyFrontEnd")?.mustRunAfter("cleanFrontEnd")
}
This is the output
> Task :cleanFrontEnd
> Task :copyFrontEnd NO-SOURCE
> Task :frontEndBuild
BUILD SUCCESSFUL in 20s
2 actionable tasks: 2 executed
For :copyFrontEnd it is saying NO-SOURCE but if that is the case then why its working when executing on its own? Is there anyway to fix this.
When you register a task, the bit inside the { } block configures the task. This block will always run whenever the task is required.
tasks.register<Copy>("copyFrontEnd") {
into("$projectDir")
// these copy actions will ALWAYS run whenever Gradle configures this task
copy {
from("${projectDir}/frontend/dist/css")
into("${projectDir}/backend/main/resources/static/css")
}
copy {
from("${projectDir}/frontend/dist/js")
into("${projectDir}/backend/main/resources/static/js")
}
}
Because you've used register when creating the task, Gradle won't execute the task configuration block won't unless the task is required. But when it is, those copy actions will run immediately.
To add task actions, which will actually do the work of the task, add them using doLast { } or doFirst { }.
tasks.register<Copy>("copyFrontEnd") {
into("$projectDir")
doLast {
copy {
from("${projectDir}/frontend/dist/css")
into("${projectDir}/backend/main/resources/static/css")
}
copy {
from("${projectDir}/frontend/dist/js")
into("${projectDir}/backend/main/resources/static/js")
}
}
}
Now those copy actions will only run when the task runs.
This still won't work however...
NO-SOURCE
Task did not need to execute its actions.
Task has inputs and outputs, but no sources
https://docs.gradle.org/current/userguide/more_about_tasks.html#sec:task_outcomes
When you register a Copy task, you need to specify what the source is.
tasks.register<Copy>("copyFrontEnd") {
into("$projectDir")
// from(...) // no from, no source - Gradle thinks "this task doesn't need to run"
}
In your case, you can specify the source as "${projectDir}/frontend/dist/css" and get rid of the two separate copy actions.
tasks.register<Copy>("copyFrontEnd") {
from("${projectDir}/frontend/dist/")
into("${projectDir}/backend/main/resources/static/css")
}
You might want to fiddle around with includes to only copy the css/ and js/ directories - https://docs.gradle.org/current/userguide/working_with_files.html#sec:copying_directories_example
Typesafe references
This last bit is unrelated, but I thought I'd include it as it can help make your buildscript clearer.
While you can reference task by their names, it's nicer to reference them by a variable. When you register a task, it returns a handle to that task.
You can use that handle to specify task dependencies.
val buildFrontEndTask: TaskProvider<NpmTask> = tasks.register<NpmTask>("buildFrontEnd") {
// ...
}
val cleanFrontEndTask: TaskProvider<Delete> = tasks.register<Delete>("cleanFrontEnd") {
// ...
}
val copyFrontEndTask: TaskProvider<Copy> = tasks.register<Copy>("copyFrontEnd") {
// ...
}
tasks.register("frontEndBuild") {
// here you can set the task dependencies based on the task providers
dependsOn(buildFrontEndTask, cleanFrontEndTask, copyFrontEndTask)
}

Error using dependsOn to call task from another gradle file

I am working with a build.gradle file that has multiple ways to specify executions for a task - setup. To call a task from another gradle file - runtests.gradle, I created a task - testTask and added task dependency using dependsOn, but this implementation does not seem to work and giving out an error like :
Could not find property 'testTask' on root project 'GradleFile
My build file looks like this :
build.gradle
task setup(dependsOn: testTask) <<
{
println "In main execution"
}
// new task
task testTask(type: GradleBuild) {
if (getEnvironmentVariable('RUN_TEST').equalsIgnoreCase("true")) {
buildFile = "../Behave/runtests.gradle"
tasks = ['mainTask']
}
else {
println "Exiting runTests Task"
}
}
setup.doFirst {
println "In first execution"
}
setup.doLast {
println "In last execution"
}
D:\>gradle -q GradleFile/build.gradle setup
I am not looking to make much changes to existing tasks, so is there any other workaround I should try?
I have been through many links but could not find anything that suits this scenario. Looking for suggestions please.
Gradle is sensitive to the ordering of tasks in the build script if a task instance is given in the dependsOn. The task setup depends on task (instance) testTask which, at the moment the build script is compiled, doesn't exist yet. The most common options to solve the issue are:
Define task setup below testTask:
task testTask(type: GradleBuild) {
}
task setup(dependsOn: testTask) {
}
Use a relative path to the task, i.e. the task's name, in the dependsOn
task setup(dependsOn: 'testTask') {
}
task testTask(type: GradleBuild) {
}
Please find more details in Javadoc of Task.

Creating a task that runs before all other tasks in gradle

I need to create an initialize task that will run before all other task when I execute it.
task A {
println "Task A"
}
task initializer {
println "initialized"
}
If I execute gradle -q A, the output will be:
>initialized
>Task A
Now if i'll add:
task B {
println "Task B"
}
Execute gradle -q B, and I get:
>initialized
>Task B
So it doesn't matter which task I execute, it always get "initialized" first.
You can make every Task who's name is NOT 'initializer' depend on the 'initializer' task. Eg:
task initializer {
doLast { println "initializer" }
}
task task1() {
doLast { println "task1" }
}
// make every other task depend on 'initializer'
// matching() and all() are "live" so any tasks declared after this line will also depend on 'initializer'
tasks.matching { it.name != 'initializer' }.all { Task task ->
task.dependsOn initializer
}
task task2() {
doLast { println "task2" }
}
Or you could add a BuildListener (or use one of the convenience methods eg: Gradle.buildStarted(...))
Seems like you aim execution phase, and you want a task precursing each task or just run as a first task in the execution phase?
If you want a task to always execute in every project before each other task after its being evaluated you can add a closure to he main build.gradle:
allprojects {
afterEvaluate {
for(def task in it.tasks)
if(task != rootProject.tasks.YourTask)
task.dependsOn rootProject.tasks.YourTask
}
}
or
tasks.matching {it != YourTask}.all {it.dependsOn YourTask}
You can also use the Task Execution Graph to define the lifecycle. There are few ways of achieving your goal, depending on your needs and a project structure.
The previously suggested solution with dependsOn works fine, but I don't like about it that it changes and clutters the task dependencies. The first solution coming to my mind is using Gradle Initialization Scripts. They are really cool. But, the usage is a bit tedious: currently there is no way to have a default project-local Gradle init script. You have to either explicitly specify the script(s) on command line, or place them in USER_HOME/GRADLE_HOME.
So another solution (already briefliy mentioned by #lance-java) which can be used to run some initialization, like a init task/script, is "build listeners". Depending on how early/late the initialization code should run, I use one of these two:
gradle.afterProject {
println '=== initialized in afterProject'
}
or
gradle.taskGraph.whenReady {
println '=== initialized in taskGraph.whenReady'
}
Here the docs of the Gradle interface and of BuildListener.
Note that some of the events occur very early, and you probably can't use them because of that, like e.g. beforeProject and buildStarted (explanations here and there).

What is the best way to parameterize a task on Gradle?

I need to create two different .properties files from two different .properties.dist if they don't exist, so I'm using a Copy task and I'm specifying the from and the into accordingly.
At the moment I had to create two different tasks, each of which is creating a file like this:
task copyAndRenameDialling(type: Copy){
if(!file("./properties/dialling.properties").exists()){
from './dist/dialling.properties.dist'
into './properties/'
rename{ String fileName ->
fileName.replace('.dist','')
}
}
}
task copyAndRenameFiles(type: Copy){
if(!file("./properties/file.properties").exists()){
from './dist/files.properties.dist'
into './properties/'
rename{ String fileName ->
fileName.replace('.dist','')
}
}
}
task copyAndRenameProperties {
dependsOn << copyAndRenameDialling
dependsOn << copyAndRenameFiles
}
and I run the task with gradle copyAndRenameProperties.
Is it possible to make the two Copy tasks parameterized based on the name of the file, so that I have only one generic copyAndRename?
If so, how can I pass the parameter to the task?
I'd do it like this:
task copyAndRenameProperties(type: Copy) {
from 'dist'
include '*.properties.dist'
into 'properties'
rename { it - ~/\.dist$/ }
eachFile { if (file("properties/$it.name").file) it.exclude() }
}
or if you really only want those two specific files
task copyAndRenameProperties(type: Copy) {
from 'dist/dialling.properties.dist'
from 'dist/file.properties.dist'
into 'properties'
rename { it - ~/\.dist$/ }
eachFile { if (file("properties/$it.name").file) it.exclude() }
}
or
task copyAndRenameProperties(type: Copy) {
from 'dist'
include 'dialling.properties.dist', 'file.properties.dist'
into 'properties'
rename { it - ~/\.dist$/ }
eachFile { if (file("properties/$it.name").file) it.exclude() }
}

is there an anchor task that contains bundleDebug and bundleRelease in Android Gradle plugin?

In Android Gradle plugin, task "assemble" is an anchor task that contains assembleDebug and assembleRelease. Is there a similar anchor task that contains bundleDebug and bundleRelease. I currently have following build script where a task depends on bundleDebug:
android.libraryVariants.all {
variant -> variant.javaCompile.classpath += configurations.provided
}
task removeCameraApiJar(dependsOn: 'bundleDebug') << {
FileCollection outputs = tasks['bundleDebug'].getOutputs().getFiles()
outputs.each {
File file ->
println file.name
}
println 'removeCameraApiJar'
}
task assemble.dependsOn(removeCameraApiJar)
However if I replace bundleDebug with just "bundle", the script would fail with following message:
What went wrong: Could not determine the dependencies of task ':camerasupport:removeCameraApiJar'.
Task with path 'bundle' not found in project ':camerasupport'.
It doesn't seem as though the Android plugin creates such a task. You could however do something like
task removeCameraApiJar(dependsOn: tasks.matching { it.name.startsWith('bundle') })
In the current version of the gradle android plugin (1.5.0), the bundle task can be found as a property ("packageLibrary") of the variant output :
android.libraryVariants.all {
variant ->
variant.outputs.each { output ->
FileCollection outputs =
output.packageLibrary.getOutputs().getFiles()
}
}
prinln output.packageLibrary.name will yield "bundle"+buildVariant.

Resources