Configuring a project with a closure


(perrynfowler) #1

Hello

I’m a bit confused about something - probably due to my relative unfamiliarity with both gradle and groovy.

In gradle it is possible to do something like this in the root build.gradle

project(‘mysubproject’) {

apply plugin: ‘checkstyle’ }

This applies the checkstyle plugin to the ‘mysubproject’ project. What confuses me is that I would have thought the closure would be closed over the root script, so ‘apply’ would be called on that rather than on the ‘mysubproject’ project. I would have thought you would have to do something like this

project(‘mysubproject’) { it ->

it.apply plugin: ‘checkstyle’ }

sure enough, if I try to do something like this

var closure = { apply plugin: ‘checkstyle’ ) project(‘mysubproject’) closure project(‘myothersubproject’) closure

then the checkstyle plugin is NOT applied to the subprojects.

Can anyone shed any light on what is going on?

cheers P

PS I am aware there are other ways to apply the plugin to multiple sub-projects, I’m just interested in what is going on here


(René Groeschke) #2

technically spoken

project('mysubproject') {
     apply plugin: 'checkstyle'
 }

is mapped to a function “Project project(String path, Closure configureClosure)”. Before executing the closure, the delegate of the closure is set to the project identified by ‘path’. Have a look at this little example to understand closures and delegates: http://mrhaki.blogspot.com/2009/11/groovy-goodness-setting-closures.html

To reuse closures for different project configurations, you can use the following syntax:

def configClosure = { apply plugin: 'java' }
project('projb', configClosure)

regards, René


(Luke Daley) #3

This code…

var closure = { apply plugin: 'checkstyle' )
 project('mysubproject') closure
 project('myothersubproject') closure

is not valid Groovy.

Can you please post the exact code you were using.