Reputation: 376
I am new in groovy-gradle field, and right now I am taking multiple online courses, but I am missing something here.
I'll give you and example. This creates a Jar file:
apply plugin: 'java' // 1. Apply the Java plugin to the project
sourceSets {
main {
java {
srcDir 'java' // 3. Add 'java' directory as a source directory
}
}
}
jar {
manifest {
attributes 'Implementation-Version': '1.0' // 2. Add manifest attribute
}
}
You can find this solution everywhere, but not clear explanation.
Now, can apply plugin by: Plugin.apply(T)
I assume that the Plugin is object instance and apply is its method and T is an an argument.
So what is what is apply plugin "java"
?
There is also thing called sourceSets. It may be method that takes an argument of a Closure, or it may be a property that takes a Closure as argument because of default getter generated by groovy. I canot tell because in groovy equal sign is optional, parenthesis are optional.--- VERY INOVATIVE!!!!!!!!
And finally there is thing called main. I cannot find what it is, and I've been looking for it everywhere, even here :https://docs.gradle.org/current/dsl/org.gradle.api.tasks.SourceSet.html
And this 'main'-ting contains thing called java (looks like instance of SourceDirectorySet), which contains method srcDir, that takes a string as an agument.
Does it makes sense to you?. How to extract information from here: https://docs.gradle.org/current/dsl/, and use it in a build?
What am I missing here?
Upvotes: 2
Views: 158
Reputation: 27994
I'm on my mobile so it's difficult to explain all of the Gradle magic but this should help you on your way.
There is an implicit Project instance in scope and much of what you see in a gradle script will delegate to this.
Eg
apply plugin: 'java'
Is equivalent to
getProject().apply([plugin: 'java'])
You can read more in the writing a custom plugin section but there's a property file that maps "java" to JavaPlugin
When you applied the "java" plugin, this will "mixin" the JavaPluginConvention to the project (so you can now call getSourceSets() in java which can be shortened to "sourceSets" in groovy)
One feature that gets a lot of use in Gradle's DSL is Groovy's methodMissing(...). So
sourceSets.main { ... }
will actually get dynamically delegated to
sourceSets.getByName('main').configure { ... }
Another feature which is a source of "magic" is that in groovy you can write
def a = new A()
a.foo = 'bar'
a.baz('x')
As
def a = new A()
a.with {
foo = 'bar'
baz('x')
}
Hopefully you can see that all property/method references in the closure are delegated to the "a" instance. This style of configuration helps gradle scripts remain succinct.
See the with method
Upvotes: 1