列出任务
项目中的所有可用任务都来自 Gradle 插件和构建脚本。
您可以通过在终端中运行以下命令来列出项目中的所有可用任务:
$ ./gradlew tasks
让我们以一个非常基本的 Gradle 项目为例。该项目具有以下结构:
gradle-project
├── app
│ ├── build.gradle.kts // empty file - no build logic
│ └── ... // some java code
├── settings.gradle.kts // includes app subproject
├── gradle
│ └── ...
├── gradlew
└── gradlew.bat
gradle-project
├── app
│ ├── build.gradle // empty file - no build logic
│ └── ... // some java code
├── settings.gradle // includes app subproject
├── gradle
│ └── ...
├── gradlew
└── gradlew.bat
设置文件包含以下内容:
rootProject.name = "gradle-project"
include("app")
rootProject.name = 'gradle-project'
include('app')
目前,app
子项目的构建文件为空。
要查看子项目中可用的任务app
,请运行./gradlew :app:tasks
:
$ ./gradlew :app:tasks
> Task :app:tasks
------------------------------------------------------------
Tasks runnable from project ':app'
------------------------------------------------------------
Help tasks
----------
buildEnvironment - Displays all buildscript dependencies declared in project ':app'.
dependencies - Displays all dependencies declared in project ':app'.
dependencyInsight - Displays the insight into a specific dependency in project ':app'.
help - Displays a help message.
javaToolchains - Displays the detected java toolchains.
kotlinDslAccessorsReport - Prints the Kotlin code for accessing the currently available project extensions and conventions.
outgoingVariants - Displays the outgoing variants of project ':app'.
projects - Displays the sub-projects of project ':app'.
properties - Displays the properties of project ':app'.
resolvableConfigurations - Displays the configurations that can be resolved in project ':app'.
tasks - Displays the tasks runnable from project ':app'.
我们观察到,目前只有少量的帮助任务可用。这是因为 Gradle 的核心仅提供分析构建的任务。其他任务,例如构建项目或编译代码的任务,是通过插件添加的。
让我们通过将Gradle 核心base
插件添加到app
构建脚本来探索这一点:
plugins {
id("base")
}
plugins {
id('base')
}
该base
插件添加了中心生命周期任务。现在,当我们运行时./gradlew app:tasks
,我们可以看到assemble
和build
任务可用:
$ ./gradlew :app:tasks
> Task :app:tasks
------------------------------------------------------------
Tasks runnable from project ':app'
------------------------------------------------------------
Build tasks
-----------
assemble - Assembles the outputs of this project.
build - Assembles and tests this project.
clean - Deletes the build directory.
Help tasks
----------
buildEnvironment - Displays all buildscript dependencies declared in project ':app'.
dependencies - Displays all dependencies declared in project ':app'.
dependencyInsight - Displays the insight into a specific dependency in project ':app'.
help - Displays a help message.
javaToolchains - Displays the detected java toolchains.
outgoingVariants - Displays the outgoing variants of project ':app'.
projects - Displays the sub-projects of project ':app'.
properties - Displays the properties of project ':app'.
resolvableConfigurations - Displays the configurations that can be resolved in project ':app'.
tasks - Displays the tasks runnable from project ':app'.
Verification tasks
------------------
check - Runs all checks.
任务成果
当 Gradle 执行任务时,它会通过控制台为任务标记结果。
这些标签基于任务是否有要执行的操作以及 Gradle 是否执行了这些操作。操作包括但不限于编译代码、压缩文件和发布档案。
任务组和描述
任务组和描述用于组织和描述任务。
- 团体
-
任务组用于对任务进行分类。当您运行时
./gradlew tasks
,任务会在各自的组下列出,从而更容易理解它们的目的以及与其他任务的关系。组是使用该group
属性设置的。 - 描述
-
描述提供任务用途的简要说明。当您运行时
./gradlew tasks
,每个任务旁边都会显示说明,帮助您了解其目的以及如何使用它。描述是使用description
属性设置的。
让我们以一个基本的 Java 应用程序为例。该构建包含一个名为 的子项目app
。
app
让我们列出目前可用的任务:
$ ./gradlew :app:tasks
> Task :app:tasks
------------------------------------------------------------
Tasks runnable from project ':app'
------------------------------------------------------------
Application tasks
-----------------
run - Runs this project as a JVM application.
Build tasks
-----------
assemble - Assembles the outputs of this project.
在这里,任务是具有描述的组:run
的一部分。在代码中,它看起来像这样:Application
Runs this project as a JVM application
tasks.register("run") {
group = "Application"
description = "Runs this project as a JVM application."
}
tasks.register("run") {
group = "Application"
description = "Runs this project as a JVM application."
}
私人和隐藏任务
Gradle 不支持将任务标记为private。
:tasks
但是,只有在task.group
设置了该值或者没有其他任务依赖于它时,任务才会在运行时显示。
例如,以下任务在运行时不会出现,./gradlew :app:tasks
因为它没有组;它被称为隐藏任务:
tasks.register("helloTask") {
println("Hello")
}
tasks.register("helloTask") {
println("Hello")
}
虽然helloTask
没有列出,但仍然可以通过Gradle执行:
$ ./gradlew :app:tasks
> Task :app:tasks
------------------------------------------------------------
Tasks runnable from project ':app'
------------------------------------------------------------
Application tasks
-----------------
run - Runs this project as a JVM application
Build tasks
-----------
assemble - Assembles the outputs of this project.
让我们向同一任务添加一个组:
tasks.register("helloTask") {
group = "Other"
description = "Hello task"
println("Hello")
}
tasks.register("helloTask") {
group = "Other"
description = "Hello task"
println("Hello")
}
现在组已添加,任务可见:
$ ./gradlew :app:tasks
> Task :app:tasks
------------------------------------------------------------
Tasks runnable from project ':app'
------------------------------------------------------------
Application tasks
-----------------
run - Runs this project as a JVM application
Build tasks
-----------
assemble - Assembles the outputs of this project.
Other tasks
-----------
helloTask - Hello task
反之,./gradlew tasks --all
将显示所有任务;列出了隐藏和可见的任务。
任务分组
如果您想自定义在列出时向用户显示哪些任务,您可以对任务进行分组并设置每个组的可见性。
请记住,即使您隐藏任务,它们仍然可用,并且 Gradle 仍然可以运行它们。 |
init
让我们从 Gradle为具有多个子项目的 Java 应用程序构建的示例开始。项目结构如下:
gradle-project
├── app
│ ├── build.gradle.kts
│ └── src // some java code
│ └── ...
├── utilities
│ ├── build.gradle.kts
│ └── src // some java code
│ └── ...
├── list
│ ├── build.gradle.kts
│ └── src // some java code
│ └── ...
├── buildSrc
│ ├── build.gradle.kts
│ ├── settings.gradle.kts
│ └── src // common build logic
│ └── ...
├── settings.gradle.kts
├── gradle
├── gradlew
└── gradlew.bat
gradle-project
├── app
│ ├── build.gradle
│ └── src // some java code
│ └── ...
├── utilities
│ ├── build.gradle
│ └── src // some java code
│ └── ...
├── list
│ ├── build.gradle
│ └── src // some java code
│ └── ...
├── buildSrc
│ ├── build.gradle
│ ├── settings.gradle
│ └── src // common build logic
│ └── ...
├── settings.gradle
├── gradle
├── gradlew
└── gradlew.bat
运行app:tasks
以查看app
子项目中的可用任务:
$ ./gradlew :app:tasks
> Task :app:tasks
------------------------------------------------------------
Tasks runnable from project ':app'
------------------------------------------------------------
Application tasks
-----------------
run - Runs this project as a JVM application
Build tasks
-----------
assemble - Assembles the outputs of this project.
build - Assembles and tests this project.
buildDependents - Assembles and tests this project and all projects that depend on it.
buildNeeded - Assembles and tests this project and all projects it depends on.
classes - Assembles main classes.
clean - Deletes the build directory.
jar - Assembles a jar archive containing the classes of the 'main' feature.
testClasses - Assembles test classes.
Distribution tasks
------------------
assembleDist - Assembles the main distributions
distTar - Bundles the project as a distribution.
distZip - Bundles the project as a distribution.
installDist - Installs the project as a distribution as-is.
Documentation tasks
-------------------
javadoc - Generates Javadoc API documentation for the 'main' feature.
Help tasks
----------
buildEnvironment - Displays all buildscript dependencies declared in project ':app'.
dependencies - Displays all dependencies declared in project ':app'.
dependencyInsight - Displays the insight into a specific dependency in project ':app'.
help - Displays a help message.
javaToolchains - Displays the detected java toolchains.
kotlinDslAccessorsReport - Prints the Kotlin code for accessing the currently available project extensions and conventions.
outgoingVariants - Displays the outgoing variants of project ':app'.
projects - Displays the sub-projects of project ':app'.
properties - Displays the properties of project ':app'.
resolvableConfigurations - Displays the configurations that can be resolved in project ':app'.
tasks - Displays the tasks runnable from project ':app'.
Verification tasks
------------------
check - Runs all checks.
test - Runs the test suite.
如果我们查看可用任务列表,即使对于标准 Java 项目,也会发现它非常广泛。使用构建的开发人员很少直接需要其中许多任务。
我们可以配置:tasks
任务并将任务限制为特定组显示。
让我们创建自己的组,以便通过更新构建脚本默认隐藏所有任务app
:
val myBuildGroup = "my app build" // Create a group name
tasks.register<TaskReportTask>("tasksAll") { // Register the tasksAll task
group = myBuildGroup
description = "Show additional tasks."
setShowDetail(true)
}
tasks.named<TaskReportTask>("tasks") { // Move all existing tasks to the group
displayGroup = myBuildGroup
}
def myBuildGroup = "my app build" // Create a group name
tasks.register(TaskReportTask, "tasksAll") { // Register the tasksAll task
group = myBuildGroup
description = "Show additional tasks."
setShowDetail(true)
}
tasks.named(TaskReportTask, "tasks") { // Move all existing tasks to the group
displayGroup = myBuildGroup
}
现在,当我们列出 中可用的任务时app
,列表会更短:
$ ./gradlew :app:tasks
> Task :app:tasks
------------------------------------------------------------
Tasks runnable from project ':app'
------------------------------------------------------------
My app build tasks
------------------
tasksAll - Show additional tasks.
任务类别
Gradle 区分两类任务:
-
生命周期任务
-
可操作的任务
生命周期任务定义您可以调用的目标,例如:build
您的项目。生命周期任务不向 Gradle 提供操作。他们必须连接到可操作的任务。 Gradlebase
插件仅添加生命周期任务。
可操作任务定义 Gradle 要执行的操作,例如:compileJava
编译项目的 Java 代码。操作包括创建 JAR、压缩文件、发布档案等等。像java-library
插件这样的插件添加了可操作的任务。
让我们更新上一个示例的构建脚本,该脚本当前是一个空文件,以便我们的app
子项目是一个 Java 库:
plugins {
id("java-library")
}
plugins {
id('java-library')
}
我们再次列出可用的任务,看看有哪些新任务可用:
$ ./gradlew :app:tasks
> Task :app:tasks
------------------------------------------------------------
Tasks runnable from project ':app'
------------------------------------------------------------
Build tasks
-----------
assemble - Assembles the outputs of this project.
build - Assembles and tests this project.
buildDependents - Assembles and tests this project and all projects that depend on it.
buildNeeded - Assembles and tests this project and all projects it depends on.
classes - Assembles main classes.
clean - Deletes the build directory.
jar - Assembles a jar archive containing the classes of the 'main' feature.
testClasses - Assembles test classes.
Documentation tasks
-------------------
javadoc - Generates Javadoc API documentation for the 'main' feature.
Help tasks
----------
buildEnvironment - Displays all buildscript dependencies declared in project ':app'.
dependencies - Displays all dependencies declared in project ':app'.
dependencyInsight - Displays the insight into a specific dependency in project ':app'.
help - Displays a help message.
javaToolchains - Displays the detected java toolchains.
outgoingVariants - Displays the outgoing variants of project ':app'.
projects - Displays the sub-projects of project ':app'.
properties - Displays the properties of project ':app'.
resolvableConfigurations - Displays the configurations that can be resolved in project ':app'.
tasks - Displays the tasks runnable from project ':app'.
Verification tasks
------------------
check - Runs all checks.
test - Runs the test suite.
我们看到有许多新任务可用,例如jar
和testClasses
。
此外,该java-library
插件还将可操作的任务连接到生命周期任务。如果我们调用该:build
任务,我们可以看到包括该任务在内的多个任务已被执行:app:compileJava
。
$./gradlew :app:build
> Task :app:compileJava
> Task :app:processResources NO-SOURCE
> Task :app:classes
> Task :app:jar
> Task :app:assemble
> Task :app:compileTestJava
> Task :app:processTestResources NO-SOURCE
> Task :app:testClasses
> Task :app:test
> Task :app:check
> Task :app:build
可操作:compileJava
任务连接到生命周期:build
任务。
增量任务
Gradle 任务的一个关键特征是其增量性质。
Gradle 可以重用之前构建的结果。因此,如果我们之前已经构建了项目并且仅进行了较小的更改,则重新运行:build
将不需要 Gradle 执行大量工作。
例如,如果我们只修改项目中的测试代码,而生产代码保持不变,则执行构建只会重新编译测试代码。 Gradle 将生产代码的任务标记为UP-TO-DATE
,表示自上次成功构建以来它保持不变:
$./gradlew :app:build
lkassovic@MacBook-Pro temp1 % ./gradlew :app:build
> Task :app:compileJava UP-TO-DATE
> Task :app:processResources NO-SOURCE
> Task :app:classes UP-TO-DATE
> Task :app:jar UP-TO-DATE
> Task :app:assemble UP-TO-DATE
> Task :app:compileTestJava
> Task :app:processTestResources NO-SOURCE
> Task :app:testClasses
> Task :app:test
> Task :app:check UP-TO-DATE
> Task :app:build UP-TO-DATE
缓存任务
Gradle 可以使用构建缓存重用过go构建的结果。
--build-cache
要启用此功能,请使用命令行org.gradle.caching=true
参数或在文件中设置来激活构建缓存gradle.properties
。
此优化有可能显着加速您的构建:
$./gradlew :app:clean :app:build --build-cache
> Task :app:compileJava FROM-CACHE
> Task :app:processResources NO-SOURCE
> Task :app:classes UP-TO-DATE
> Task :app:jar
> Task :app:assemble
> Task :app:compileTestJava FROM-CACHE
> Task :app:processTestResources NO-SOURCE
> Task :app:testClasses UP-TO-DATE
> Task :app:test FROM-CACHE
> Task :app:check UP-TO-DATE
> Task :app:build
当 Gradle 可以从缓存中获取任务的输出时,它会使用 来标记该任务FROM-CACHE
。
如果您定期在分支之间切换,构建缓存会很方便。 Gradle 支持本地和远程构建缓存。
开发任务
开发 Gradle 任务时,您有两种选择:
-
使用现有的 Gradle 任务类型,例如
Zip
、Copy
或Delete
-
创建您自己的 Gradle 任务类型,例如
MyResolveTask
或CustomTaskUsingToolchains
。
任务类型只是 GradleTask
类的子类。
对于 Gradle 任务,需要考虑三种状态:
-
注册任务 - 在构建逻辑中使用任务(由您实现或由 Gradle 提供)。
-
配置任务 - 定义已注册任务的输入和输出。
-
实现任务 - 创建自定义任务类(即自定义类类型)。
注册通常是用该register()
方法完成的。
配置任务通常使用该named()
方法完成。
实现任务通常是通过扩展 Gradle 的DefaultTask
类来完成的:
tasks.register<Copy>("myCopy") (1)
tasks.named<Copy>("myCopy") { (2)
from("resources")
into("target")
include("**/*.txt", "**/*.xml", "**/*.properties")
}
abstract class MyCopyTask : DefaultTask() { (3)
@TaskAction
fun copyFiles() {
val sourceDir = File("sourceDir")
val destinationDir = File("destinationDir")
sourceDir.listFiles()?.forEach { file ->
if (file.isFile && file.extension == "txt") {
file.copyTo(File(destinationDir, file.name))
}
}
}
}
1 | Register the myCopy task of type Copy to let Gradle know we intend to use it in our build logic. |
2 | Configure the registered myCopy task with the inputs and outputs it needs according to its API. |
3 | Implement a custom task type called MyCopyTask which extends DefaultTask and defines the copyFiles task action. |
tasks.register(Copy, "myCopy") (1)
tasks.named(Copy, "myCopy") { (2)
from "resources"
into "target"
include "**/*.txt", "**/*.xml", "**/*.properties"
}
abstract class MyCopyTask extends DefaultTask { (3)
@TaskAction
void copyFiles() {
fileTree('sourceDir').matching {
include '**/*.txt'
}.forEach { file ->
file.copyTo(file.path.replace('sourceDir', 'destinationDir'))
}
}
}
1 | Register the myCopy task of type Copy to let Gradle know we intend to use it in our build logic. |
2 | Configure the registered myCopy task with the inputs and outputs it needs according to its API. |
3 | Implement a custom task type called MyCopyTask which extends DefaultTask and defines the copyFiles task action. |
1. 注册任务
您可以通过在构建脚本或插件中注册任务来定义 Gradle 要执行的操作。
任务是使用任务名称字符串定义的:
tasks.register("hello") {
doLast {
println("hello")
}
}
tasks.register('hello') {
doLast {
println 'hello'
}
}
在上面的示例中,任务被添加到TasksCollection
usingregister()
中的方法中TaskContainer
。
2. 配置任务
必须配置 Gradle 任务才能成功完成其操作。如果任务需要压缩文件,则必须配置文件名和位置。您可以参考Gradle 任务的APIZip
以了解如何正确配置它。
我们Copy
以 Gradle 提供的任务为例。我们首先在构建脚本中注册一个名为myCopy
of 类型的任务:Copy
tasks.register<Copy>("myCopy")
tasks.register('myCopy', Copy)
这会注册一个没有默认行为的复制任务。由于任务的类型是Copy
Gradle 支持的任务类型,因此可以使用其API进行配置。
以下示例展示了实现相同配置的几种方法:
1、使用named()
方法:
用于named()
配置在其他地方注册的现有任务:
tasks.named<Copy>("myCopy") {
from("resources")
into("target")
include("**/*.txt", "**/*.xml", "**/*.properties")
}
tasks.named('myCopy') {
from 'resources'
into 'target'
include('**/*.txt', '**/*.xml', '**/*.properties')
}
2. 使用配置块:
注册任务后立即使用块来配置任务:
tasks.register<Copy>("copy") {
from("resources")
into("target")
include("**/*.txt", "**/*.xml", "**/*.properties")
}
tasks.register('copy', Copy) {
from 'resources'
into 'target'
include('**/*.txt', '**/*.xml', '**/*.properties')
}
3. 将方法命名为 call:
仅 Groovy 支持的一个流行选项是速记符号:
copy {
from("resources")
into("target")
include("**/*.txt", "**/*.xml", "**/*.properties")
}
此选项会破坏任务配置避免,因此不推荐! |
无论选择哪种方法,任务都会配置要复制的文件的名称和文件的位置。
三、落实任务
Gradle 提供了许多任务类型,包括Delete
、Javadoc
、Copy
、Exec
、Tar
和Pmd
。如果 Gradle 没有提供满足您的构建逻辑需求的任务类型,您可以实现自定义任务类型。
要创建自定义任务类,您需要扩展DefaultTask
并使扩展类抽象:
abstract class MyCopyTask extends DefaultTask {
}
abstract class MyCopyTask : DefaultTask() {
}
您可以在实现任务中了解有关开发自定义任务类型的更多信息。