【Gradle教程】第六章:构建脚本基础

6.1. Projects and tasks 项目和任务
Everything in Gradle sits on top of two basic concepts: projects and tasks.
<翻译> Gradle中的所有东西都是围绕两个基本概念:项目和任务。

Every Gradle build is made up of one or more projects. What a project represents depends on what it is that you are doing with Gradle. For example, a project might represent a library JAR or a web application. It might represent a distribution ZIP assembled from the JARs produced by other projects. A project does not necessarily represent a thing to be built. It might represent a thing to be done, such as deploying your application to staging or production environments. Don't worry if this seems a little vague for now. Gradle's build-by-convention support adds a more concrete definition for what a project is.
<翻译> 每个Gradle构建都是由一个或多个项目组成。一个项目代表什么,取决于你用Gradle正在做的。比如,一个项目可能代表一个库或一个网络应用。它可能代表一个由其他项目产生的一个或多个jar包打包d一个zip包。一个项目不需要代表一个事物而被构建。它可以代表一个事物而被做出来,比如部署你的应用到暂存区或产品环境。不要担心这个现在是否好像有一点含糊。Gradle的通过约定来构建的功能支持为一个项目添加一个更加具体的定义。

Each project is made up of one or more tasks. A task represents some atomic piece of work which a build performs. This might be compiling some classes, creating a JAR, generating Javadoc, or publishing some archives to a repository.
<翻译> 每一个项目都是有一个或多个任务组成。一个任务代表一些小片段工作。这个可能会时编译一些类,创建一个jar包,生成Javadoc,或者发布一些档案到仓库。

For now, we will look at defining some simple tasks in a build with one project. Later chapters will look at working with multiple projects and more about working with projects and tasks.
<翻译> 现在,我们将来看看在构建一个项目时要定义的一些简单任务。后面的章节将关注多项目下的工作,更多的关注项目和任务的工作。

6.2. Hello world 哈喽 世界
You run a Gradle build using the gradle command. The gradle command looks for a file called build.gradle in the current directory. [2] We call this build.gradle file a build script, although strictly speaking it is a build configuration script, as we will see later. The build script defines a project and its tasks.
<翻译> 你可以使用gradle命令来运行一个Gradle构建。gradle命令会在当前目录下找到build.gradle文件。[2]我们称build.gradle文件为一个构建脚本,严格地来说它是一个构建配置脚本,就像我们将要看到的那样。这个构建脚本定义了一个项目和它的一些任务。

To try this out, create the following build script named build.gradle.
<翻译> 来试试这个,创建下面的构建脚本build.gradle。

Example 6.1. Your first build script
<翻译> 例 6.1.你的第一个构建脚本

build.gradle
task hello {
doLast {
    println 'Hello world!'
}
}


In a command-line shell, move to the containing directory and execute the build script with gradle -q hello:
<翻译> 在一个命令行shell里,移动到包含该脚本的目录下并执行gradle -q hello:

What does -q do? -q有什么作用?

Most of the examples in this user guide are run with the -q command-line option. This suppresses Gradle's log messages, so that only the output of the tasks is shown. This keeps the example output in this user guide a little clearer. You don't need to use this option if you don't want to. See Chapter 18, Logging for more details about the command-line options which affect Gradle's output.
<翻译> 在用户向导中的大部分示例都运行-q命令行选项。这些抑制Gradle的日志消息,以便只有任务的输出被显示。这也保证了示例输出的简洁性。你也可以不使用这个选项。看第18章了解更多影响Gradle输出d命令行选项。

Example 6.2. Execution of a build script
<翻译> 例 6.2.执行一个构建脚本

Output of gradle -q hello
> gradle -q hello
Hello world!


What's going on here? This build script defines a single task, called hello, and adds an action to it. When you run gradle hello, Gradle executes the hello task, which in turn executes the action you've provided. The action is simply a closure containing some Groovy code to execute.
<翻译> 发生什么了?这个构建脚本定义了一个带有动作的hello任务。当你运行gradle hello时,Gradle执行hello任务的动作。

If you think this looks similar to Ant's targets, you would be right. Gradle tasks are the equivalent to Ant targets, but as you will see, they are much more powerful. We have used a different terminology than Ant as we think the word task is more expressive than the word target. Unfortunately this introduces a terminology clash with Ant, as Ant calls its commands, such as javac or copy, tasks. So when we talk about tasks, we always mean Gradle tasks, which are the equivalent to Ant's targets. If we talk about Ant tasks (Ant commands), we explicitly say Ant task.
<翻译> 如果你认为这个看起来类似于Ant的目标,你是对的。Gradle任务相当于Ant目标,但不仅是你将看到的,他们更加强大。在我们看来任务比目标更有意义。不过这些术语将和Ant的一些命令冲突,如javac,copy,tasks。所以我们谈论的任务是gradle任务。如果我们谈论Ant任务(Ant命令)会说Ant任务。

6.3. A shortcut task definition 一个快捷的任务定义
There is a shorthand way to define a task like our hello task above, which is more concise.
<翻译> 有一个速记的方法来定义一个任务

Example 6.3. A task definition shortcut
<翻译> 一个任务快捷定义

build.gradle
task hello << {
println 'Hello world!'
}


Again, this defines a task called hello with a single closure to execute. We will use this task definition style throughout the user guide.
<翻译> 同样,这里定义了一个叫hello的任务,执行的时候会有一个闭包。我们将使用这个任务定义风格贯穿整个用户向导。

6.4. Build scripts are code 构建脚本都是代码

Gradle's build scripts give you the full power of Groovy. As an appetizer, have a look at this:
<翻译> Gradle构建脚本给你所有的Groovy功能。作为一道开胃菜,看看这里:

Example 6.4. Using Groovy in Gradle's tasks
<翻译> 例 6.4.在Gradle任务中使用Groovy

build.gradle
task upper << {
String someString = 'mY_nAmE'
println "Original: " + someString 
println "Upper case: " + someString.toUpperCase()
}
Output of gradle -q upper
> gradle -q upper
Original: mY_nAmE
Upper case: MY_NAME


or 或

Example 6.5. Using Groovy in Gradle's tasks
<翻译> 例 6.5.在Gradle任务中使用Groovy

build.gradle
task count << {
4.times { print "$it " }
}
Output of gradle -q count
> gradle -q count
0 1 2 3


6.5. Task dependencies 任务依赖

As you probably have guessed, you can declare tasks that depend on other tasks.
<翻译> 你可能已经猜到了,你可以声明依赖其他任务的任务

Example 6.6. Declaration of task that depends on other task
<翻译> 例 6.6.声明依赖其他任务的任务

build.gradle
task hello << {
println 'Hello world!'
}
task intro(dependsOn: hello) << {
println "I'm Gradle"
}
Output of gradle -q intro
> gradle -q intro
Hello world!
I'm Gradle


To add a dependency, the corresponding task does not need to exist.
<翻译> 如果想要添加一个依赖,相应的任务不需要存在。

Example 6.7. Lazy dependsOn - the other task does not exist (yet)
<翻译> 例 6.7.懒惰依赖项 - 其他任务不存在

build.gradle
task taskX(dependsOn: 'taskY') << {
println 'taskX'
}
task taskY << {
println 'taskY'
}
Output of gradle -q taskX
> gradle -q taskX
taskY
taskX


The dependency of taskX to taskY is declared before taskY is defined. This is very important for multi-project builds. Task dependencies are discussed in more detail in Section 15.4, “Adding dependencies to a task”.
<翻译> taskX到taskY的依赖在taskY之前就被定义了。这个在多项目构建时非常重要。任务依赖在15.4会有更详细的讨论,“增加依赖到一个任务中”。

Please notice that you can't use shortcut notation (see Section 6.8, “Shortcut notations”) when referring to a task that is not yet defined.
<翻译> 请注意,当引用一个没有被定义的任务时,你不能使用快捷符号(看6.8)。

6.6. Dynamic tasks 动态任务

The power of Groovy can be used for more than defining what a task does. For example, you can also use it to dynamically create tasks.
<翻译> Groovy不仅仅能够用来定义一个任务该做什么。比方说,你也可以用它来动态创建任务。

Example 6.8. Dynamic creation of a task
<翻译> 例 6.8.动态创建任务

build.gradle
4.times { counter ->
task "task$counter" << {
    println "I'm task number $counter"
}
}
Output of gradle -q task1
> gradle -q task1
I'm task number 1


6.7. Manipulating existing tasks 操作已存在的任务

Once tasks are created they can be accessed via an API. For instance, you could use this to dynamically add dependencies to a task, at runtime. Ant doesn't allow anything like this.
<翻译> 一旦任务被创建,他们就能够通过API来被访问。例如,你可以在运行时使用这个动态添加依赖到一个任务。Ant没有这样的功能。

Example 6.9. Accessing a task via API - adding a dependency
<翻译> 例 6.9.通过API访问任务 - 添加依赖

build.gradle
4.times { counter ->
task "task$counter" << {
    println "I'm task number $counter"
}
}
task0.dependsOn task2, task3
Output of gradle -q task0
> gradle -q task0
I'm task number 2
I'm task number 3
I'm task number 0


Or you can add behavior to an existing task.
<翻译> 或者你可以添加一个行为到一个已存在的任务

Example 6.10. Accessing a task via API - adding behaviour
<翻译> 例 6.10.通过API访问任务 - 添加行为

build.gradle
task hello << {
println 'Hello Earth'
}
hello.doFirst {
println 'Hello Venus'
}
hello.doLast {
println 'Hello Mars'
}
hello << {
println 'Hello Jupiter'
}
Output of gradle -q hello
> gradle -q hello
Hello Venus
Hello Earth
Hello Mars
Hello Jupiter


The calls doFirst and doLast can be executed multiple times. They add an action to the beginning or the end of the task's actions list. When the task executes, the actions in the action list are executed in order. The << operator is simply an alias for doLast.
<翻译> doFirst和doLast能够被多次执行。他们在任务动作列表的开始或结尾添加一个动作。当任务执行时,动作列表中的动作将会按顺序执行。“<<”操作符只是doLast的一个别名而已。

6.8. Shortcut notations 快捷符号

As you might have noticed in the previous examples, there is a convenient notation for accessing an existing task. Each task is available as a property of the build script:
<翻译> 你可能已经注意到上一个示例中有一个约定符号来访问已存在的任务。每一个任务都会作为构建脚本中的一个属性。

Example 6.11. Accessing task as a property of the build script
<翻译> 作为构建脚本中的一个属性的任务的访问

build.gradle
task hello << {
println 'Hello world!'
}
hello.doLast {
println "Greetings from the $hello.name task."
}
Output of gradle -q hello
> gradle -q hello
Hello world!
Greetings from the hello task.


This enables very readable code, especially when using the tasks provided by the plugins, like the compile task.
<翻译> 这使得代码的可读性很高,尤其是当使用插件提供的任务,如编译任务。

6.9. Extra task properties 额外的任务属性

You can add your own properties to a task. To add a property named myProperty, set ext.myProperty to an initial value. From that point on, the property can be read and set like a predefined task property.
<翻译> 你可以添加你自己的属性到一个任务中。添加一个属性设置为myProperty,ext.myProperty为初始值。从这一点上,该属性可以像一个预定义的任务属性一样读取和设置。

Example 6.12. Adding extra properties to a task
<翻译> 例 6.12.添加额外属性到一个任务中

build.gradle
task myTask {
ext.myProperty = "myValue"
}


task printTaskProperties << {
println myTask.myProperty
}
Output of gradle -q printTaskProperties
> gradle -q printTaskProperties
myValue


Extra properties aren't limited to tasks. You can read more about them in Section 13.4.2, “Extra properties”.
<翻译> 额外属性不局限于任务。你可以在13.4.2“额外属性”中了解更多。

6.10. Using Ant Tasks 使用Ant任务

Ant tasks are first-class citizens in Gradle. Gradle provides excellent integration for Ant tasks by simply relying on Groovy. Groovy is shipped with the fantastic AntBuilder. Using Ant tasks from Gradle is as convenient and more powerful than using Ant tasks from a build.xml file. From the example below, you can learn how to execute Ant tasks and how to access Ant properties:
<翻译> Ant任务在Gradle中得到了很好地支持。Gradle通过简单依赖Groovy为Ant任务提供了优化整合。Groovy拥有一个棒极了的AntBuilder。使用来自Gradle的Ant任务作为约定,同时比通过使用来自build.xml的Ant任务更高效。通过下面的示例,你可以学习怎么执行Ant任务和访问Ant属性:

Example 6.13. Using AntBuilder to execute ant.loadfile target
<翻译> 例 6.13.使用AntBuilder执行ant.loadfile目标

build.gradle
task loadfile << {
def files = file('../antLoadfileResources').listFiles().sort()
files.each { File file ->
    if (file.isFile()) {
        ant.loadfile(srcFile: file, property: file.name)
        println " *** $file.name ***"
        println "${ant.properties[file.name]}"
    }
}
}
Output of gradle -q loadfile
> gradle -q loadfile


*** agile.manifesto.txt ***
Individuals and interactions over processes and tools
Working software over comprehensive documentation
Customer collaboration over contract negotiation
Responding to change over following a plan

*** gradle.manifesto.txt ***
Make the impossible possible, make the possible easy and make the easy elegant.
(inspired by Moshe Feldenkrais)
<翻译> 让不可能成为可能,让可能变得容易,让容易变得轻松优雅。(灵感来自Moshe Feldenkrais)

There is lots more you can do with Ant in your build scripts. You can find out more in Chapter 17, Using Ant from Gradle.
<翻译> 在你的构建脚本中你可以用Ant做得更多。你可以在第17章“使用来自Gradle的Ant”中发现更多。

6.11. Using methods 使用方法

Gradle scales in how you can organize your build logic. The first level of organizing your build logic for the example above, is extracting a method.
<翻译> 你可以怎样组织你的构建逻辑在Gradle是有等级限制的。上面的示例“提取一个方法”只是第一级。

Example 6.14. Using methods to organize your build logic
<翻译> 使用方法来组织你的构建逻辑

build.gradle
task checksum << {
fileList('../antLoadfileResources').each {File file ->
    ant.checksum(file: file, property: "cs_$file.name")
    println "$file.name Checksum: ${ant.properties["cs_$file.name"]}"
}
}


task loadfile << {
fileList('../antLoadfileResources').each {File file ->
    ant.loadfile(srcFile: file, property: file.name)
    println "I'm fond of $file.name"
}
}


File[] fileList(String dir) {
file(dir).listFiles({file -> file.isFile() } as FileFilter).sort()
}
Output of gradle -q loadfile
> gradle -q loadfile
I'm fond of agile.manifesto.txt
I'm fond of gradle.manifesto.txt


Later you will see that such methods can be shared among subprojects in multi-project builds. If your build logic becomes more complex, Gradle offers you other very convenient ways to organize it. We have devoted a whole chapter to this. See Chapter 60, Organizing Build Logic.
<翻译> 之后你将看到在多项目构建中很多子项目中的方法能够被共享。如果你的构建逻辑变得很复杂,Gradle提供了一个其他约定的方法来组织它。我们已经用一整章来研究它。(看第六十章“组织构建逻辑”)

6.12. Default tasks 默认任务

Gradle allows you to define one or more default tasks for your build.
<翻译> Gradle允许你为你的构建定义一个或多个默认任务。

Example 6.15. Defining a default tasks
<翻译> 例 6.15. 定义一个默认任务

build.gradle
defaultTasks 'clean', 'run'


task clean << {
println 'Default Cleaning!'
}


task run << {
println 'Default Running!'
}


task other << {
println "I'm not a default task!"
}
Output of gradle -q
> gradle -q
Default Cleaning!
Default Running!


This is equivalent to running gradle clean run. In a multi-project build every subproject can have its own specific default tasks. If a subproject does not specify default tasks, the default tasks of the parent project are used (if defined).
<翻译> 这相当于运行gradle clean run。在一个多项目构建中,每个子项目能够有它自己指定的默认任务。如果一个子任务不指定默认任务,将会使用父项目中已定义的默认任务。

6.13. Configure by DAG 使用DAG配置

As we later describe in full detail (see Chapter 56, The Build Lifecycle), Gradle has a configuration phase and an execution phase. After the configuration phase, Gradle knows all tasks that should be executed. Gradle offers you a hook to make use of this information. A use-case for this would be to check if the release task is among the tasks to be executed. Depending on this, you can assign different values to some variables.
<翻译> 就想我们之后详细描述那样(看第五十六章“构建生命周期”),Gradle有一个配置阶段和一个执行阶段。在配置阶段后,Gradle知道所有应该被执行的任务。Gradle提供了一个钩子来使用这个信息。一个使用案例将检查发布的任务是否被执行。依此,你可以给一些变量赋不同的值。

In the following example, execution of the distribution and release tasks results in different value of the version variable.
<翻译> 在接下来的示例中,版本变量不同的值时分配和发布任务执行的结果

Example 6.16. Different outcomes of build depending on chosen tasks
<翻译> 例 6.16. 不同的结果取决于选择的构建任务

build.gradle
task distribution << {
println "We build the zip with version=$version"
}


task release(dependsOn: 'distribution') << {
println 'We release now'
}


gradle.taskGraph.whenReady {taskGraph ->
if (taskGraph.hasTask(release)) {
    version = '1.0'
} else {
    version = '1.0-SNAPSHOT'
}
}
Output of gradle -q distribution
> gradle -q distribution
We build the zip with version=1.0-SNAPSHOT
Output of gradle -q release
> gradle -q release
We build the zip with version=1.0
We release now


The important thing is that whenReady affects the release task before the release task is executed. This works even when the release task is not the primary task (i.e., the task passed to the gradle command).
<翻译> 重要的是whenReady的影响在发布任务执行之前。当发布任务不是首要任务时也会奏效。(比如,任务传递给gradle命令)

6.14. Where to next? 接下来会时哪里呢?

In this chapter, we have had a first look at tasks. But this is not the end of the story for tasks. If you want to jump into more of the details, have a look at Chapter 15, More about Tasks.
<翻译> 在这一章,我们已经初步了解了任务。任务还有更多的故事在等着你来发现。欲知后事,请看第十五章。

Otherwise, continue on to the tutorials in Chapter 7, Java Quickstart and Chapter 8, Dependency Management Basics.
<翻译> 另外,第七章“Java快速入门”,第八章“依赖管理基础”中会继续说明。

[2] There are command line switches to change this behavior. See Appendix D, Gradle Command Line
<翻译> 改变行为的命令行开关请看Appendix D, Gradle Command Line

原文地址:http://www.gradle.org/docs/cur ... .html
翻译者:wellchang
邮箱:2483808264@qq.com

如对翻译内容有异议,请在评论区提出或联系作者
7 分享
ask chendeshen studio 胖女 gaojs 逆向人生 夜空sky
studio

studio

楼主辛苦了!
0 赞 2014-12-16 15:47
胖女

胖女

好强大啊 楼主辛苦了
0 赞 2015-06-07 14:54
DovSnier

DovSnier

非常感谢
0 赞 2015-06-09 11:51
youhu868

youhu868

6.10有个地方错了,““<<”操作符只是doLast的一个别人而已。”应修改为““<<”操作符只是doLast的一个别名而已。”
0 赞 2015-11-17 10:51
wellchang

wellchang 回复 youhu868

谢谢,已修改
0 赞 2015-11-25 17:05
逆向人生

逆向人生

task toDex(type: Exec, dependsOn: 'copyJar') {
executable "dx"
int code = android.defaultConfig.versionCode
args "--dex", "--output=$buildDir/libs/plugin_" + code + ".dex", "$buildDir/libs/plugin_" + code + ".jar"
}

您好,我这个task是想用dx命令将jar包转为dex,但是执行这个task后,
报错:* What went wrong:
Execution failed for task ':plugin:toDex'.
> A problem occurred starting process 'command 'dx''*
我觉得应该是我写的命令有问题,但是不知道该怎么修改。
该task在Linux和Mac下可以正常运行 。
0 赞 2016-04-06 10:57
aijiao

aijiao

怎么没有看到第五章
0 赞 2017-03-07 09:50

要回复文章请先登录注册