Chris Lieb
Chris Lieb

Reputation: 3836

Configuring a Gradle task based on task to be executed

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.

Upvotes: 6

Views: 4142

Answers (1)

Chris Lieb
Chris Lieb

Reputation: 3836

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'
            }
        }
    }
}

Upvotes: 15

Related Questions