Gradle学习笔记・03・Gradle的Task

Gradle的整个设计围绕着Task展开,我们在gradle的脚本中也是定义各种Task。定义Task的代码如下:

task hello

我们可以使用gradle的task命令查看task.gradle中定义的task:

$ gradle task -b 03.gradle
:tasks

------------------------------------------------------------
All tasks runnable from root project
------------------------------------------------------------

Build Setup tasks
-----------------
init - Initializes a new Gradle build. [incubating]
wrapper - Generates Gradle wrapper files. [incubating]

Help tasks
----------
buildEnvironment - Displays all buildscript dependencies declared in root project '03'.
components - Displays the components produced by root project '03'. [incubating]
dependencies - Displays all dependencies declared in root project '03'.
dependencyInsight - Displays the insight into a specific dependency in root project '03'.
help - Displays a help message.
model - Displays the configuration model of root project '03'. [incubating]
projects - Displays the sub-projects of root project '03'.
properties - Displays the properties of root project '03'.
tasks - Displays the tasks runnable from root project '03'.

Other tasks
-----------
hello

To see all tasks and more detail, run gradle tasks --all

To see more detail about a task, run gradle help --task <task>

BUILD SUCCESSFUL

Total time: 1.193 secs

注意在上面的命令中,我们使用了gradle的’-b’选项指定脚本文件为”03.gradle”,否则gradle默认寻找”build.gradle”文件。此外,我们在上面的命令输出中看到”hello”任务在”Other tasks”中出现。

接下来我们可以补充这个task的内容:

task hello << {
	print "Hello, "
}

hello << {
	println "Martian!"
}

从上面的代码当中,我们可以看到task是可以在一开始被定义后,继续补充内容的,这一点非常灵活。下面是代码输出:

$ gradle -q -b 03.gradle hello
Hello, Martian!

此外,如果我们对hello任务补充内容时,不带两个小于号,仅带大括号,那么大括号中的内容将被认为是配置内容,会在task的config phase被执行。下面是代码:

task hello << {
	print "Hello, "
}

hello << {
	println "Martian!"
}

hello {
	println "Configuring hello task..."
}

代码输出如下:

$ gradle -q -b 03.gradle hello
Configuring hello task...
Hello, Martian!

可以看到虽然”Configuring…“代码是放在最后,但是它是配置代码,所以最先执行了。