"Gradle Tutorial" The sixth chapter constructs the Script Foundation

Source: Internet
Author: User

6.1. Projects and Tasks Project and task
Everything in Gradle sits on top of both basic concepts:projects and tasks.
**< translation >** Everything in Gradle is around two basic concepts: projects and tasks.


Every Gradle build is made up by one or more projects. What's a project represents depends on what it's that's 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 to other projects. A project does not necessarily represent a thing to be built. It might represent a thing to be do, 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.
**< translation >** Each gradle build is made up of one or more projects. What a project stands for depends on what you are doing with gradle. For example, a project might represent a library or a Web application. It may represent one or more jar packages produced by other projects to package D a zip package. A project does not need to be built on behalf of a thing. It can be made to represent a thing, such as deploying your application to a staging area or product environment. Don't worry about whether this seems a bit vague now. Gradle's ability to build by convention supports adding a more specific definition to a project.


Each project was made up of one or more tasks. A task represents some atomic piece of work which a build performs. This might is compiling some classes, creating a JAR, generating Javadoc, or publishing some archives to a repository.
**< translation >** Each project is composed of one or more tasks. A task represents some small fragment work. This might compile some classes, create a jar package, generate Javadoc, or publish some files to the repository.


For now, we'll look at the defining some simple tasks in a build with one project. Later chapters would look at working with multiple projects and more about working with projects and tasks.
**< translation >** Now, let's look at some simple tasks to define when building a project. The following chapters will focus on the work under multiple projects and more on the work of 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 the Build.gradle file a build script, although strictly speaking it is a build configuration script, as We WI ll see later. The build script defines a project and its tasks.
**< translation >** You can use the Gradle command to run a Gradle build. The Gradle command will find the Build.gradle file in the current directory. [2] We call the Build.gradle file a build script, strictly speaking it is a build configuration script, as we will see. This build script defines a project and some of its tasks.


To try this out, create the following build script named Build.gradle.
**< Translate >** To try this, create the following build script Build.gradle.


Example 6.1. Your First Build Script
**< Translation >** Example 6.1. Your first build script


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:
**< translation >** in a command-line shell, move to the directory containing the script and execute gradle-q Hello:


What does-q? What is the function of-Q?


Most of the examples in this user guide is run with the-q command-line option. This suppresses Gradle's log messages, so that's only the output of the tasks is shown. This keeps the example output in this user guide a little clearer. You don ' t need the use of this option if you don't want to. See Chapter, Logging for more details about the command-line options which affect Gradle ' s output.
**< translation >** Most of the examples in the User Wizard run the-q command-line option. These suppress Gradle log messages so that only the output of the task is displayed. This also guarantees the simplicity of the sample output. You can also not use this option. See the 18th Chapter to learn more about the effect of gradle output D command line options.


Example 6.2. Execution of a build script
**< Translation >** Example 6.2. Execute a Build script


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.
**< translation >** what happened? This build script defines a hello task with an action. When you run Gradle Hello, Gradle performs the action of the Hello task.


If you think the looks similar to Ant's targets, you are would be right. Gradle tasks is the equivalent to Ant targets, but as you'll see, they is much more powerful. We have used a different terminology than Ant as we think the word task was 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. We always mean Gradle tasks, which is the equivalent to Ant ' s targets. If We talk about ant tasks (ant commands), we explicitly say ant task.
**< translation >** If you think this looks similar to Ant's Goal, you're right. Gradle tasks are equivalent to ant targets, but not just what you will see, they are more powerful. It seems to us that the task is more meaningful than the goal. However, these terms will conflict with some ant commands, such as Javac,copy,tasks. So the task we're talking about is the Gradle task. If we talk about the ant task (Ant command) it will say ant task.


6.3. A shortcut task definition
There is a shorthand-a-define a task like our Hello task above, which are more concise.
**< translation >** There is a shorthand way to define a task


Example 6.3. A Task Definition Shortcut
**< translation >** a task shortcut definition


Build.gradle
Task Hello << {
println ' Hello world! '
}
Again, this defines a task called Hello with a single closure to execute. We'll use this task definition style throughout the user guide.
**< translation >** Similarly, this defines a task called Hello, which is executed with a closure. We will use this task to define the style throughout the User Wizard.


6.4. Build scripts are code build scripts


Gradle ' s build scripts give you the full power of Groovy. As an appetizer, with a look at this:
**< translation >** gradle build script gives you all the groovy features. As an appetizer, look here:


Example 6.4. Using Groovy in Gradle ' s tasks
**< Translation >** example 6.4. Use Groovy in Gradle tasks


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 OR


Example 6.5. Using Groovy in Gradle ' s tasks
**< Translation >** example 6.5. Use Groovy in Gradle tasks


Build.gradle
Task Count << {
4.times {print "$it"}
}
Output of Gradle-q Count
> Gradle-q Count
0 1 2 3


6.5. task dependencies Tasks Dependencies


As you probably has guessed, you can declare tasks, which depend on other tasks.
**< translation >** As you may have guessed, you can declare tasks that depend on other tasks


Example 6.6. Declaration of task depends on other task
**< Translation >** Example 6.6. Declaring tasks that depend on other tasks


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.
**< translation >** If you want to add a dependency, the corresponding task does not need to exist.


Example 6.7. Lazy dependson-the Other task does not exist (yet)
**< Translation >** example 6.7. Lazy dependencies-Other tasks do not exist


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 are declared before Tasky is defined. This is the very important for multi-project builds. task dependencies is discussed in + detail in the section 15.4, "Adding dependencies to a task".
The dependence of **< translation >** taskx to Tasky was defined before Tasky. This is very important when building multiple projects. task dependencies will be discussed in more detail in 15.4, "adding dependencies to a task".


Please notice this can ' t use shortcut notation (see Section 6.8, "shortcut notations") while referring to a task that I s not yet defined.
**< translation >** Note that when referencing a task that is not defined, you cannot use the shortcut symbol (see 6.8).


6.6. Dynamic Tasks


The power of Groovy can be used to more than defining what a task does. For example, you can also use the it to dynamically create tasks.
**< translation >**


Example 6.8. Dynamic creation of a task
**< translation >**


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 is created they can is accessed via an API. For instance, you could use the this to dynamically add dependencies to a task, at runtime. Ant doesn ' t allow anything like this.
**< translation >**


Example 6.9. Accessing a task via api-adding a dependency
**< translation >**


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.
**< translation >**


Example 6.10. Accessing a task via api-adding behaviour
**< translation >**


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 is executes, the actions in the action list is executed in order. The << operator is simply a alias for Dolast.
**< translation >**


6.8. Shortcut Notations Shortcut symbols


As you might has noticed in the previous examples, there are a convenient notation for accessing a existing task. Each task was available as a property of the build script:
**< translation >**


Example 6.11. Accessing task as a property of the build script
**< translation >**


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 if using the tasks provided by the plugins, like the compile task.
**< translation >**


6.9. Extra task properties Extra Tasks Property


You can add your own properties to a task. To add a property named MyProperty, set Ext.myproperty to an initial value. The property can is read and set like a predefined task property.
**< translation >**


Example 6.12. Adding Extra properties to a task
**< translation >**


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".
**< translation >**


6.10. Using Ant Tasks


Ant tasks is 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 are as convenient and more powerful than using ant tasks from a build.xml file. From the example below, what can learn how to execute Ant tasks and what to access Ant properties:
**< translation >**


Example 6.13. Using Antbuilder to execute ant.loadfile target
**< translation >**


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 to make the "possible easy" and make the "easy elegant."
(Inspired by Moshe Feldenkrais)
**< translation >**
There is lots more you can do with Ant in your build scripts. You can find the more in Chapter, Using the Ant from Gradle.
**< translation >**


6.11. Using methods


Gradle scales in how can organize your build logic. The first level of organizing your build logic for the example above, is extracting a method.
**< translation >**


Example 6.14. Using methods to organize your build logic
**< translation >**


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'll see this such methods can be gkfx among subprojects in multi-project builds. If Your build logic becomes more complex, Gradle offers your other very convenient ways to organize it. We have devoted a whole chapter to this. See Chapter, organizing Build Logic.
**< translation >**


6.12. Default Tasks


Gradle allows-define one or more default tasks for your build.
**< translation >**


Example 6.15. Defining a default Tasks
**< translation >**


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 was equivalent to running Gradle clean run. In a multi-project build every subproject can has its own specific default tasks. If a subproject does not specify default tasks, the default tasks of the parent project is used (if defined).
**< translation >**


6.13. Configure by DAG


As we later describe in full detail (see Chapter, the Build Lifecycle), Gradle have a configuration phase and an Executi On phase. After the configuration phase, Gradle knows all tasks, this should be executed. Gradle offers you a hook-to-make use of the this information. A Use-case for this would are to check if the release task was among the tasks to be executed. Depending on this, you can assign different values to some variables.
**< translation >**


In the following example, execution of the distribution and release tasks results in different value of the version Variab Le.
**< translation >**


Example 6.16. Different outcomes of build depending on chosen tasks
**< translation >**


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 this whenready affects the release task before the release task is executed. This works even when the release task was not the primary task (i.e., the task passed to the Gradle command).
**< translation >**


6.14. Where to next? Where will it be next?


In this chapter, we had had a first look at tasks. It's not the end of the stories for tasks. If you want-to-jump-to-more of the details, there is a look at Chapter and more about Tasks.
**< translation >**


Otherwise, continue on to the tutorials in Chapter 7, Java Quickstart and Chapter 8, Dependency Management Basics.
**< translation >**




[2] There is command line switches to change this behavior. See Appendix D, Gradle Command line)
**< translation >**


Original address: [Http://www.gradle.org/docs/current/userguide/tutorial_using_tasks.html] (http://www.gradle.org/docs/ current/userguide/tutorial_using_tasks.html)
Translated by: [Wellchang] (Http://ask.android-studio.org/?/people/wellchang)
email: [[email protected]] (Mailto:[email protected])


* * If you have any objection to the translation, please submit it in the comment area or [contact the author] (Http://ask.android-studio.org/?/people/wellchang) * *

"Gradle Tutorial" The sixth chapter constructs the Script Foundation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.