Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom conditional configuration for Gradle project

Tags:

gradle

Having an extract from https://github.com/gradle/gradle/blob/master/build.gradle:

ext {
  isDevBuild = {
    gradle.taskGraph.hasTask(developerBuild)
  }
}

task developerBuild {
  description = 'Builds distributions and runs pre-checkin checks'
  group = 'build'
  dependsOn testedDists
}

When I used this approach to create custom configuration in my project I discovered that:

isDevBuild === true

i.e. it's always true because task 'developerBuild' is inside my build.gradle project, and hence in graph. They have a couple of "different" configs (isCIBuild, isCommitBuild, isFinalReleaseBuild, ...) so I suppose I got something wrong here.

Can someone explain how to make this configs conditional based on some external parameter?

like image 599
Artem Oboturov Avatar asked May 11 '12 16:05

Artem Oboturov


Video Answer


1 Answers

taskGraph.hasTask() tells if a task is in the task execution graph, that is whether it will get executed. Because the task execution graph is only created after the configuration phase, this method has to be called from a whenReady callback (or in the execution phase):

gradle.taskGraph.whenReady { graph ->
    if (graph.hasTask(developerBuild)) { 
        // do conditional configuration
    }
} 

To make this more readable, we can introduce a new method:

def onlyFor(task, config) {
    gradle.taskGraph.whenReady { graph ->
        if (graph.hasTask(task)) { 
            project.configure(project, config)
        }
    }
}

Now we can write:

onlyFor(developerBuild) { ... }
onlyFor(ciBuild) { ... } 

Another, simpler way to solve this problem is to check whether a particular task name is contained in gradle.startParameter.taskNames. However, this has two limitations: First, it compares task names, which can make a difference in multi-project builds. Second, it will only find tasks that have been specified directly (e.g. on the command line), but not dependencies thereof.

PS.: In your code, isDevBuild always holds because a (non-null) closure is true according to Groovy truth. (In contrast to isDevBuild(), isDevBuild won't call the closure.)

like image 123
Peter Niederwieser Avatar answered Oct 07 '22 02:10

Peter Niederwieser