第四章. 使用 Gradle 命令行

Chapter 4. Using the Gradle Command-Line

目录
Table of Contents

4.1. 执行多个任务 - Executing multiple tasks
4.2. 排除任务 - Excluding tasks
4.3. 失败后继续构建 - Continuing the build when a failure occurs
4.4. 任务名称缩写 - Task name abbreviation
4.5. 选择要执行的构建 - Selecting which build to execute
4.6. 强制执行任务 - Forcing tasks to execute
4.7. 获取构建的相关信息 - Obtaining information about your build
4.8. 空运行 - Dry Run
4.9. 总结 - Summary

本章介绍了 Gradle 命令行的基础知识。正如你在前面章节所看到的,可以使用 gradle 命令来运行构建。
This chapter introduces the basics of the Gradle command-line. You run a build using the gradle command, which you have already seen in action in previous chapters.

4.1. 执行多个任务

4.1. Executing multiple tasks

通过在命令行中列出每个任务,你可以在单个构建中执行多个任务。例如,gradle compile test 命令将执行 compiletest 任务。Gradle 将按照命令行中的顺序依次执行这些任务以及每一个任务所依赖的其他任务。每个任务只会被执行一次,无论它们是如何被包含在构建中的:即无论是在命令行中指定的,还是另一个任务的依赖,抑或两者都有。来看下面的例子。
You can execute multiple tasks in a single build by listing each of the tasks on the command-line. For example, the command gradle compile test will execute the compile and test tasks. Gradle will execute the tasks in the order that they are listed on the command-line, and will also execute the dependencies for each task. Each task is executed once only, regardless of how it came to be included in the build: whether it was specified on the command-line, or as a dependency of another task, or both. Let's look at an example.

下面定义了四个任务,其中 disttest 都依赖于 compile 任务。对于这个构建脚本,运行gradle dist test只会使 compile 任务被执行一次。
Below four tasks are defined. Both dist and test depend on the compile task. Running gradle dist test for this build script results in the compile task being executed only once.

图4.1. 任务依赖 - Figure 4.1. Task dependencies

任务依赖

示例 4.1. 执行多个任务 - Example 4.1. Executing multiple tasks

build.gradle

task compile << {
    println 'compiling source'
}

task compileTest(dependsOn: compile) << {
    println 'compiling unit tests'
}

task test(dependsOn: [compile, compileTest]) << {
    println 'running unit tests'
}

task dist(dependsOn: [compile, test]) << {
    println 'building the distribution'
}

gradle dist test的输出结果
Output of gradle dist test

> gradle dist test
:compile
compiling source
:compileTest
compiling unit tests
:test
running unit tests
:dist
building the distribution

BUILD SUCCESSFUL

Total time: 1 secs

每个任务只执行一次,所以执行 gradle test test 与执行 gradle test 是完全一样的。
Each task is executed only once, so gradle test test is exactly the same as gradle test.

4.2. 排除任务

4.2. Excluding tasks

你可以使用 -x 命令行选项加上任务名称来排除某些会被执行的任务。让我们用上面的例子来演示一下。
You can exclude a task from being executed using the -x command-line option and providing the name of the task to exclude. Let's try this with the sample build file above.

示例 4.2. 排除任务 - Example 4.2. Excluding tasks

gradle dist -x test的输出结果
Output of gradle dist -x test

> gradle dist -x test
:compile
compiling source
:dist
building the distribution

BUILD SUCCESSFUL

Total time: 1 secs

你可以从本例的输出中看出,test 任务并不执行,即使它是 dist 任务的依赖。你也可能同时注意到 test 任务所依赖的任务,如compileTest也一样没有执行。而test所依赖的同时也是其他任务所需要的任务,如compile,则仍然被执行。
You can see from the output of this example, that the test task is not executed, even though it is a dependency of the dist task. You will also notice that the test task's dependencies, such as compileTest are not executed either. Those dependencies of test that are required by another task, such as compile, are still executed.

4.3. 失败后继续构建

4.3. Continuing the build when a failure occurs

默认情况下,只要有任务失败,Gradle 就将中断执行让构建失败。这样做会使构建更快地结束,但也会让其他可能发生的失败不被发现。为了在单个构建执行中发现尽可能多的失败,你可以使用 --continue 选项。
By default, Gradle will abort execution and fail the build as soon as any task fails. This allows the build to complete sooner, but hides other failures that would have occurred. In order to discover as many failures as possible in a single build execution, you can use the --continue option.

当使用 --continue 参数执行时,Gradle 将执行所有要执行的、并且它们的所有依赖任务都能完成且未失败的任务,而不是一出现错误就停止。所有失败的信息将在构建结束时报告出来。
When executed with --continue, Gradle will execute every task to be executed where all of the dependencies for that task completed without failure, instead of stopping as soon as the first failure is encountered. Each of the encountered failures will be reported at the end of the build.

如果任务失败了,则依赖于它的所有后续任务都不会被执行,因为那样做是不安全的。例如,如果在测试代码中存在编译失败,测试就不会运行;因为测试任务会(直接或间接地)依赖于编译任务。
If a task fails, any subsequent tasks that were depending on it will not be executed, as it is not safe to do so. For example, tests will not run if there is a compilation failure in the code under test; because the test task will depend on the compilation task (either directly or indirectly).

4.4. 任务名缩写

4.4. Task name abbreviation

在命令行中指定任务时,可以不输入任务的全名,只需要提供可以足够唯一标识任务的任务名。例如,在上面的示例构建中,你可以通过运行 gradle d 来执行 dist 任务:
When you specify tasks on the command-line, you don't have to provide the full name of the task. You only need to provide enough of the task name to uniquely identify the task. For example, in the sample build above, you can execute task dist by running gradle d:

示例4.3. 缩写任务名称 - Example 4.3. Abbreviated task name

gradle di的输出结果
Output of gradle di

> gradle di
:compile
compiling source
:compileTest
compiling unit tests
:test
running unit tests
:dist
building the distribution

BUILD SUCCESSFUL

Total time: 1 secs

你也可以对驼峰命名的任务名称的每一个单词进行缩写。例如,你可以通过运行 gradle compTestgradle cT 执行 compileTest 任务
You can also abbreviate each word in a camel case task name. For example, you can execute task compileTest by running gradle compTest or even gradle cT

示例4.4. 缩写驼峰任务名称 - Example 4.4. Abbreviated camel case task name

gradle cT的输出结果
Output of gradle cT

> gradle cT
:compile
compiling source
:compileTest
compiling unit tests

BUILD SUCCESSFUL

Total time: 1 secs

在使用 -x 命令行选项时,这些缩写依然可以使用。
You can also use these abbreviations with the -x command-line option.

4.5. 选择要执行的构建

4.5. Selecting which build to execute

当你运行 gradle 命令时,它会在当前目录中查找一个构建文件。你也可以使用 -b 选项来选择另一个构建文件。如果你使用 -b 选项,则 Gradle 就不会去用到 settings.gradle 文件。例如:
When you run the gradle command, it looks for a build file in the current directory. You can use the -b option to select another build file. If you use -b option then settings.gradle file is not used. Example:

示例4.5. 使用构建文件选择项目 - Example 4.5. Selecting the project using a build file

subdir/myproject.gradle

task hello << {
    println "using build file '$buildFile.name' in '$buildFile.parentFile.name'."
}

gradle -q -b subdir/myproject.gradle hello的输出结果
Output of gradle -q -b subdir/myproject.gradle hello

> gradle -q -b subdir/myproject.gradle hello
using build file 'myproject.gradle' in 'subdir'.

或者,你也可以使用 -p 选项来指定使用哪一个项目目录。对于多项目构建,你应该使用 -p选项 而不是 -b 选项。
Alternatively, you can use the -p option to specify the project directory to use. For multi-project builds you should use -p option instead of -b option.

示例4.6. 使用项目目录选择项目 - Example 4.6. Selecting the project using project directory

gradle -q -p subdir hello的输出结果
Output of gradle -q -p subdir hello

> gradle -q -p subdir hello
using build file 'build.gradle' in 'subdir'.

4.6. 强制执行任务

4.6. Forcing tasks to execute

许多任务,尤其是 Gradle 本身提供的任务,支持增量构建。此类任务可以根据自上次运行以来其输入或输出是否发生变化来确定它们是否需要运行。在执行一个构建时,当 Gradle 在任务的名字旁边显示 UP-TO-DATE 文本时,你可以轻松识别到这些增量任务。
Many tasks, particularly those provided by Gradle itself, support incremental builds. Such tasks can determine whether they need to run or not based on whether their inputs or outputs have changed since the last time they ran. You can easily identify incremental tasks when Gradle displays the text UP-TO-DATE next to their name when executing a build.

你有时可能希望强制 Gradle 运行所有任务,而忽略任何最新检查。如果是这种情况,只需使用--rerun-tasks选项。这是在没有和有 --rerun-tasks 的情况下运行任务时的输出:
You may on occasion want to force Gradle to run all the tasks, ignoring any up-to-date checks. If that's the case, simply use the --rerun-tasks option. Here's the output when running a task both without and with --rerun-tasks:

示例 4.7. 强制运行任务 - Example 4.7. Forcing tasks to run

gradle doIt 的输出结果
Output of gradle doIt

> gradle doIt
:doIt UP-TO-DATE

gradle --rerun-tasks doIt 的输出结果
Output of gradle --rerun-tasks doIt

> gradle --rerun-tasks doIt
:doIt

请注意,这将强制执行所有必需的任务,而不仅仅是你在命令行上指定的任务。这有点像运行一个 clean,但不删除构建生成的输出。
Note that this will force all required tasks to execute, not just the ones you specify on the command line. It's a little like running a clean, but without the build's generated output being deleted.

4.7. 获取构建的相关信息

4.7. Obtaining information about your build

Gradle 提供了一些内置任务来展示构建的相关特定信息。这对于理解构建的结构和依赖,以及问题的调试来说很有用。
Gradle provides several built-in tasks which show particular details of your build. This can be useful for understanding the structure and dependencies of your build, and for debugging problems.

除了下面所示的内置任务之外,还可以使用项目报告插件将一些任务添加到项目中,以生成这些报告。
In addition to the built-in tasks shown below, you can also use the project report plugin to add tasks to your project which will generate these reports.

4.7.1. 列出项目

4.7.1. Listing projects

运行 gradle projects 会为你按子项目的层次结构显示出项目列表,如下所示:
Running gradle projects gives you a list of the sub-projects of the selected project, displayed in a hierarchy. Here is an example:

示例4.8. 获取项目的相关信息 - Example 4.8. Obtaining information about projects

gradle -q projects的输出结果
Output of gradle -q projects

> gradle -q projects

------------------------------------------------------------
Root project
------------------------------------------------------------

Root project 'projectReports'
+--- Project ':api' - The shared API for the application
\--- Project ':webapp' - The Web application implementation

To see a list of the tasks of a project, run gradle <project-path>:tasks
For example, try running gradle :api:tasks

这个报告会显示每一个项目的描述信息,如果你有配置的话。你可以通过设置 description 属性来提供项目的描述信息:
The report shows the description of each project, if specified. You can provide a description for a project by setting the description property:

示例4.9. 提供项目描述信息 - Example 4.9. Providing a description for a project

build.gradle

description = 'The shared API for the application'

4.7.2. 列出任务

4.7.2. Listing tasks

运行 gradle tasks 会为你列出所选项目的主要任务。报告会显示项目的默认任务(如果有配置默认任务的话),以及每个任务的说明。以下是关于该报告的示例:
Running gradle tasks gives you a list of the main tasks of the selected project. This report shows the default tasks for the project, if any, and a description for each task. Below is an example of this report:

示例4.10. 获取任务的相关信息 - Example 4.10. Obtaining information about tasks

gradle -q tasks的输出结果
Output of gradle -q tasks

> gradle -q tasks

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

Default tasks: dists

Build tasks
-----------
clean - Deletes the build directory (build)
dists - Builds the distribution
libs - Builds the JAR

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 'projectReports'.
components - Displays the components produced by root project 'projectReports'. [incubating]
dependencies - Displays all dependencies declared in root project 'projectReports'.
dependencyInsight - Displays the insight into a specific dependency in root project 'projectReports'.
help - Displays a help message.
model - Displays the configuration model of root project 'projectReports'. [incubating]
projects - Displays the sub-projects of root project 'projectReports'.
properties - Displays the properties of root project 'projectReports'.
tasks - Displays the tasks runnable from root project 'projectReports' (some of the displayed tasks may belong to subprojects).

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

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

默认情况下,此报告仅显示已分配给任务组的任务。你可以通过为任务设置group属性来实现它。你也可以通过设置description属性,来提供要包含在报告中的描述。
By default, this report shows only those tasks which have been assigned to a task group. You can do this by setting the group property for the task. You can also set the description property, to provide a description to be included in the report.

示例 4.11. 更改任务报告的内容 - Example 4.11. Changing the content of the task report

build.gradle

dists {
    description = 'Builds the distribution'
    group = 'build'
}

你可以使用 --all 选项,来获取更多的任务信息。使用此选项时,任务报告将列出项目中的所有任务,按主要任务以及每一个任务的依赖进行分组。示例如下:
You can obtain more information in the task listing using the --all option. With this option, the task report lists all tasks in the project, grouped by main task, and the dependencies for each task. Here is an example:

示例 4.12. 获取任务的更多相关信息 - Example 4.12. Obtaining more information about tasks

gradle -q tasks --all的输出结果
Output of gradle -q tasks --all

> gradle -q tasks --all

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

Default tasks: dists

Build tasks
-----------
clean - Deletes the build directory (build)
api:clean - Deletes the build directory (build)
webapp:clean - Deletes the build directory (build)
dists - Builds the distribution [api:libs, webapp:libs]
    docs - Builds the documentation
api:libs - Builds the JAR
    api:compile - Compiles the source files
webapp:libs - Builds the JAR [api:libs]
    webapp:compile - Compiles the source files

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 'projectReports'.
api:buildEnvironment - Displays all buildscript dependencies declared in project ':api'.
webapp:buildEnvironment - Displays all buildscript dependencies declared in project ':webapp'.
components - Displays the components produced by root project 'projectReports'. [incubating]
api:components - Displays the components produced by project ':api'. [incubating]
webapp:components - Displays the components produced by project ':webapp'. [incubating]
dependencies - Displays all dependencies declared in root project 'projectReports'.
api:dependencies - Displays all dependencies declared in project ':api'.
webapp:dependencies - Displays all dependencies declared in project ':webapp'.
dependencyInsight - Displays the insight into a specific dependency in root project 'projectReports'.
api:dependencyInsight - Displays the insight into a specific dependency in project ':api'.
webapp:dependencyInsight - Displays the insight into a specific dependency in project ':webapp'.
help - Displays a help message.
api:help - Displays a help message.
webapp:help - Displays a help message.
model - Displays the configuration model of root project 'projectReports'. [incubating]
api:model - Displays the configuration model of project ':api'. [incubating]
webapp:model - Displays the configuration model of project ':webapp'. [incubating]
projects - Displays the sub-projects of root project 'projectReports'.
api:projects - Displays the sub-projects of project ':api'.
webapp:projects - Displays the sub-projects of project ':webapp'.
properties - Displays the properties of root project 'projectReports'.
api:properties - Displays the properties of project ':api'.
webapp:properties - Displays the properties of project ':webapp'.
tasks - Displays the tasks runnable from root project 'projectReports' (some of the displayed tasks may belong to subprojects).
api:tasks - Displays the tasks runnable from project ':api'.
webapp:tasks - Displays the tasks runnable from project ':webapp'.

4.7.3. 显示任务帮助信息

4.7.3. Show task usage details

运行 gradle help --task someTask 可以向你提供有关指定任务或是在多项目构建中与所指定的任务名称相匹配的所有任务的详细信息。如下所示:
Running gradle help --task someTask gives you detailed information about a specific task or multiple tasks matching the given task name in your multiproject build. Below is an example of this detailed information:

示例4.13. 获取任务的帮助信息 - Example 4.13. Obtaining detailed help for tasks

gradle -q help --task libs的输出结果
Output of gradle -q help --task libs

> gradle -q help --task libs
Detailed task information for libs

Paths
     :api:libs
     :webapp:libs

Type
     Task (org.gradle.api.Task)

Description
     Builds the JAR

Group
     build

该信息包括完整的任务路径,任务类型,可用的命令行选项以及给定任务的描述。
This information includes the full task path, the task type, possible commandline options and the description of the given task.

4.7.4. 列出项目依赖

4.7.4. Listing project dependencies

运行 gradle dependencies 会为你列出所选项目的依赖,并按配置细分。对于每个配置,它的直接和传递依赖会按树型结构展示出来。以下是此报告的示例:
Running gradle dependencies gives you a list of the dependencies of the selected project, broken down by configuration. For each configuration, the direct and transitive dependencies of that configuration are shown in a tree. Below is an example of this report:

示例 4.14. 获取依赖的相关信息 - Example 4.14. Obtaining information about dependencies

gradle -q dependencies api:dependencies webapp:dependencies 的输出结果
Output of gradle -q dependencies api:dependencies webapp:dependencies

> gradle -q dependencies api:dependencies webapp:dependencies

------------------------------------------------------------
Root project
------------------------------------------------------------

No configurations

------------------------------------------------------------
Project :api - The shared API for the application
------------------------------------------------------------

compile
\--- org.codehaus.groovy:groovy-all:2.4.4

testCompile
\--- junit:junit:4.12
     \--- org.hamcrest:hamcrest-core:1.3

------------------------------------------------------------
Project :webapp - The Web application implementation
------------------------------------------------------------

compile
+--- project :api
|    \--- org.codehaus.groovy:groovy-all:2.4.4
\--- commons-io:commons-io:1.2

testCompile
No dependencies

由于一份依赖报告可能会很大,因此将报告限定为特定配置会很有用,它通过可选的 --configuration 参数来实现:
Since a dependency report can get large, it can be useful to restrict the report to a particular configuration. This is achieved with the optional --configuration parameter:

示例 4.15. 按配置过滤依赖报告 - Example 4.15. Filtering dependency report by configuration

gradle -q api:dependencies --configuration testCompile 的输出结果
Output of gradle -q api:dependencies --configuration testCompile

> gradle -q api:dependencies --configuration testCompile

------------------------------------------------------------
Project :api - The shared API for the application
------------------------------------------------------------

testCompile
\--- junit:junit:4.12
     \--- org.hamcrest:hamcrest-core:1.3

4.7.5. 列出项目 buildscript 的依赖

4.7.5. Listing project buildscript dependencies

运行 gradle buildEnvironment 会可视化所选项目的 buildscript 依赖,类似于 gradle dependencies 可视化正在构建的软件的依赖。
Running gradle buildEnvironment visualises the buildscript dependencies of the selected project, similarly to how gradle dependencies visualises the dependencies of the software being built.

4.7.6. 深入了解一个特定的依赖

4.7.6. Getting the insight into a particular dependency

运行 gradle dependencyInsight 会让你深入了解与指定的输入内容相匹配的特定依赖(或多个依赖)。如下是此报告的示例:
Running gradle dependencyInsight gives you an insight into a particular dependency (or dependencies) that match specified input. Below is an example of this report:

示例4.16. 深入了解特定的依赖 - Example 4.16. Getting the insight into a particular dependency

gradle -q webapp:dependencyInsight --dependency groovy --configuration compile 的输出结果
Output of gradle -q webapp:dependencyInsight --dependency groovy --configuration compile

> gradle -q webapp:dependencyInsight --dependency groovy --configuration compile
org.codehaus.groovy:groovy-all:2.4.4
\--- project :api
     \--- compile

这一任务对于调查依赖解析、找出某些依赖的来源,以及选择某些版本的原因来说非常有用。有关更多信息,请参阅DependencyInsightReportTask
This task is extremely useful for investigating the dependency resolution, finding out where certain dependencies are coming from and why certain versions are selected. For more information please see the DependencyInsightReportTask class in the API documentation.

内置的 dependencyInsight 任务是“Help”任务组的一部分。该任务需要配置依赖和配置信息。报告将在指定的配置中查找与指定依赖相匹配的依赖。如果应用了 java 相关的插件,那么 dependencyInsight 任务是通过“compile”配置进行预配置的,因为通常来说,我们感兴趣的是编译的依赖。你应该通过命令行“--dependency”选项指定你感举的依赖。如果您不想要默认的配置,也可以通过“--configuration”选项来选择配置。更多信息请参阅 API 文档里的 DependencyInsightReportTask 类。
The built-in dependencyInsight task is a part of the 'Help' tasks group. The task needs to configured with the dependency and the configuration. The report looks for the dependencies that match the specified dependency spec in the specified configuration. If Java related plugin is applied, the dependencyInsight task is pre-configured with 'compile' configuration because typically it's the compile dependencies we are interested in. You should specify the dependency you are interested in via the command line '--dependency' option. If you don't like the defaults you may select the configuration via '--configuration' option. For more information see the DependencyInsightReportTask class in the API documentation.

4.7.7. 列出项目属性

4.7.7. Listing project properties

运行 gradle properties 会向你列出所选项目的属性。以下是输出结果中的一个片段:
Running gradle properties gives you a list of the properties of the selected project. This is a snippet from the output:

示例 4.17. 有关属性的信息 - Example 4.17. Information about properties

gradle -q api:properties 的输出结果
Output of gradle -q api:properties

> gradle -q api:properties

------------------------------------------------------------
Project :api - The shared API for the application
------------------------------------------------------------

allprojects: [project ':api']
ant: org.gradle.api.internal.project.DefaultAntBuilder@12345
antBuilderFactory: org.gradle.api.internal.project.DefaultAntBuilderFactory@12345
artifacts: org.gradle.api.internal.artifacts.dsl.DefaultArtifactHandler_Decorated@12345
asDynamicObject: DynamicObject for project ':api'
baseClassLoaderScope: org.gradle.api.internal.initialization.DefaultClassLoaderScope@12345
buildDir: /home/user/gradle/samples/userguide/tutorial/projectReports/api/build
buildFile: /home/user/gradle/samples/userguide/tutorial/projectReports/api/build.gradle

4.7.8. 分析构建

4.7.8. Profiling a build

使用 --profile 命令行选项会在运行构建时记录一些有用的时间信息,并把报告写入 build/reports/profile 目录。报告将使用构建运行的时间命名。
The --profile command line option will record some useful timing information while your build is running and write a report to the build/reports/profile directory. The report will be named using the time when the build was run.

该报告列出了配置阶段和任务执行的总体时间和详细信息。配置和任务执行的时间会按从慢到快排序。任务执行的结果还指示了是否有任务被跳过(及跳过原因),或者是否有未跳过的任务不起作用。
This report lists summary times and details for both the configuration phase and task execution. The times for configuration and task execution are sorted with the most expensive operations first. The task execution results also indicate if any tasks were skipped (and the reason) or if tasks that were not skipped did no work.

使用 buildSrc 目录的构建将在 buildSrc/build 目录里为 buildSrc 生成第二个分析报告。
Builds which utilize a buildSrc directory will generate a second profile report for buildSrc in the buildSrc/build directory.

4.8. 空运行

4.8. Dry Run

有时候你可能想知道,以命令行指定的给定一组任务会以怎样的顺序去执行哪些任务,但你不希望任务被真的执行,就可以使用 -m 这个选项。例如,如果你运行“gradle -m clean compile”,你会看到将作为 cleancompile 任务的一部分来执行的所有任务。这是对 tasks 任务的补充,用于显示可以执行的任务。
Sometimes you are interested in which tasks are executed in which order for a given set of tasks specified on the command line, but you don't want the tasks to be executed. You can use the -m option for this. For example, if you run “gradle -m clean compile”, you'll see all the tasks that would be executed as part of the clean and compile tasks. This is complementary to the tasks task, which shows you the tasks which are available for execution.

4.9. 总结

4.9. Summary

在本章中,你已经学到了许多可以从命令行使用的操作。关于 gradle 命令的更多信息,可以参考《附录D,Gradle 命令行》。
In this chapter, you have seen some of the things you can do with Gradle from the command-line. You can find out more about the gradle command in Appendix D, Gradle Command Line.