Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Configuring a Gradle task based on task to be executed

Tags:

gradle

I'm seemingly in a bit of a chicken/egg problem. I have the test task that Gradle defines with the Java plugin. I set the JUnit categories to run using a property. My team has expressed interest in a task that will run tasks in a specific category instead of having to use -P to set a property on the command line.

I can't come up with a way to pull this off since the new task would need to configure the test task only if it's executed. Since the categories to run need to be a input parameter for the test task to make sure the UP-TO-DATE check functions correctly, they need to be set during the configuration phase and can't wait for the execution phase.

Does anyone know how to make a setup like this work? Maybe I'm approaching it from the wrong angle entirely.

Edit 1

Current build.gradle

apply plugin: 'java'

def defaultCategory = 'checkin'

test {
    def category = (project.hasProperty('category') ? project['category'] : defaultCategory)
    inputs.property('category', category)

    useJUnit()
    options {
        includeCategories category
    }
}

What I'd like, but doesn't work:

apply plugin: 'java'

def defaultCategory = 'checkin'

test {
    def category = (project.hasProperty('category') ? project['category'] : defaultCategory)
    inputs.property('category', category)

    useJUnit()
    options {
        includeCategories category
    }
}

task nightly(dependsOn: 'build') {
    defaultCategory = 'nightly'
}

task weekly(dependsOn: 'build') {
    defaultCategory = 'weekly'
}

Since both tasks are configured regardless of whether they will be run, they become useless. I can't defer setting the defaultCategory value until the execution phase because it's value is needed to configure the task inputs of the test task and because the value is required to be able to run the test task, which runs before the build task.

like image 879
Chris Lieb Avatar asked Dec 19 '22 03:12

Chris Lieb


1 Answers

I don't know if I'd call this solution elegant, but it has proven to be effective:

task nightly(dependsOn: 'build')

test {
    useJUnit()

    gradle.taskGraph.whenReady {
        if (gradle.taskGraph.hasTask(":${project.name}:nightly")) {
            options {
                includeCategories 'nightly'
            }
        }
    }
}
like image 162
Chris Lieb Avatar answered May 11 '23 10:05

Chris Lieb