Running a task for every line in properties file


(eric) #1

Hi,

I am trying to automate a release process for a large composite build project. Currently I store the builds that I want to release in a properties file and I want to call a task for every line that I read.

What I have so far

task readFile {

    doLast{
        for each line in the property file
             call another task
    }
 }

Is there any way to do this? I tried to run the task from this task but it doesn’t work


(Stefan M.) #2

You can’t “execute” a Task directly.
Gradle Tasks based on the dependsOn schema.

Because of that you need multiple Tasks to archive your goal.
The first one will just read the properties file and create tasks for each of them.
The second one will just run and depends on all generated tasks (which means they will be executed).

The task which reads the properties and create the tasks can be look like this:

tasks.create("readProperties") {
    def file = file("${rootProject.rootDir.absolutePath}/gradle.properties")
    file.readLines().forEach { line ->
        tasks.create("generatedTask$line") {
            dependsOn("aTaskWhichAlreadyExist")
            doLast {
                println("Task for $line")
            }
        }
    }
}

This will create a Task for each line inside the properties and prefix them with generatedTask.
This Task can be modified like you want. Maybe you can say that this depends on some other task.

To finally run all the generated Tasks create another task:

tasks.create("runGeneratedTasks") {
    def allGeneratedTasks = tasks.findAll { it.name.startsWith("generatedTask") }
    setDependsOn(allGeneratedTasks)
}

Now you can run runGeneratedTasks and each generated task will be run (and maybe execute another task if the generated task depends on another task :wink:)

Note:
The task named aTaskWhichAlradyExist look like this:

tasks.create("aTaskWhichAlreadyExist") {
    doLast {
        println("Hey...")
    }
}

(eric) #3

Thanks that helped. Awesome!!