首页 > 代码库 > 【Gradle教程】第六章 构建脚本基础

【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.
**<翻译>** 


Example 6.8. Dynamic creation of a task
**<翻译>** 


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.
**<翻译>** 


Example 6.9. Accessing a task via API - adding a dependency
**<翻译>** 


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
**<翻译>** 


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.
**<翻译>** 


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.
**<翻译>** 


Example 6.12. Adding extra properties to a task
**<翻译>** 


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”.
**<翻译>** 


6.10. Using Ant Tasks


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:
**<翻译>** 


Example 6.13. Using AntBuilder to execute ant.loadfile target
**<翻译>** 


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)
**<翻译>** 
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.
**<翻译>** 


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.
**<翻译>** 


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.
**<翻译>** 


6.12. Default tasks 默认任务


Gradle allows you to define one or more default tasks for your build.
**<翻译>** 


Example 6.15. Defining a default tasks
**<翻译>** 


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).
**<翻译>** 


6.13. Configure by 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.
**<翻译>** 


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
**<翻译>** 


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).
**<翻译>** 


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.
**<翻译>** 




[2] There are command line switches to change this behavior. See Appendix D, Gradle Command Line)
**<翻译>** 


原文地址:[http://www.gradle.org/docs/current/userguide/tutorial_using_tasks.html](http://www.gradle.org/docs/current/userguide/tutorial_using_tasks.html)
翻译者:[wellchang](http://ask.android-studio.org/?/people/wellchang)
邮箱:[2483808264@qq.com](mailto:2483808264@qq.com)


**如对翻译内容有异议,请在评论区提出或[联系作者](http://ask.android-studio.org/?/people/wellchang)**

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