8

I don't understand why we don't need to add quotes to the name of gradle task when we declare it like:

task hello (type : DefaultTask) {
}

I've tried in a groovy project and found that it's illegal, how gradle makes it works. And I don't understand the expression above neither, why we can add (type : DefaultTask), how can we analyze it with groovy grammar?

tkruse
  • 10,222
  • 7
  • 53
  • 80
Zijian
  • 207
  • 1
  • 9
  • 4
    Possible duplicate of [Understanding the groovy syntax in a gradle task definition](https://stackoverflow.com/questions/27584463/understanding-the-groovy-syntax-in-a-gradle-task-definition) – tkruse Jan 29 '18 at 05:29

3 Answers3

3

As an example in a GroovyConsole runnable form, you can define a bit of code thusly:

// Set the base class for our DSL

@BaseScript(MyDSL)
import groovy.transform.BaseScript

// Something to deal with people
class Person { 
    String name
    Closure method
    String toString() { "$name" }
    Person(String name, Closure cl) {
        this.name = name
        this.method = cl
        this.method.delegate = this
    }
    def greet(String greeting) {
        println "$greeting $name"
    }
}

//  and our base DSL class

abstract class MyDSL extends Script {
    def methodMissing(String name, args) {
        return new Person(name, args[0])
    }

    def person(Person p) {
        p.method(p)
    }
}

// Then our actual script

person tim {
    greet 'Hello'
}

So when the script at the bottom is executed, it prints Hello tim to stdout

But David's answer is the correct one, this is just for example

See also here in the documentation for Groovy

tim_yates
  • 167,322
  • 27
  • 342
  • 338
1

A Gradle build script is a Groovy DSL application. By careful use of "methodMissing" and "propertyMissing" methods, all magic is possible.

I don't remember the exact mechanism around "task ". I think this was asked in the Gradle forum (probably more than once).

David M. Karr
  • 14,317
  • 20
  • 94
  • 199
0

Here is the code that make the magic possible and legal.

// DSL class - Gradle Task
class Task {

    def name;
}

// DSL class - Gradle Project
class Project {

    List<Task> tasks = [];


    def methodMissing(String name, def args) {
        if(name == "task"){
            Task t = new Task(name:args[0])
            tasks << t
        }
    }

    def propertyMissing(String name) {
        name
    }
}

// gradle build script
def buildScript = {

    task myTask

    println tasks[0].name

}

buildScript.delegate = new Project()

// calling the script will print out "myTask"

buildScript()
John
  • 2,633
  • 4
  • 19
  • 34