Gradle User Guide Beginner's tutorial (iii)

Source: Internet
Author: User

Written in the previous words:
Bloggers have recently learned something about Android studio. Gradle is a whole new thing for me, the Android developer who turned from eclipse. But it is a very important part of the Android build system. In line with the person convenient, own convenient spirit, thought it is necessary to translate "Gradle User Guide" in the tutorials related section. As the level of English is quite limited, please give us a lot of advice.

Article Address: http://blog.csdn.net/mikulee/article/details/45478177
English Original address: http://gradle.org/docs/current/userguide/tutorial_using_tasks.html
Please respect the relevant knowledge copyright, thank you.

Sixth chapter. Building a Script Foundation 6.1. Projects and tasks (engineering and Task)

Everything in Gradle is based on these two concepts: projects and tasks.

Each gradle build is a combination of one or more projects. The meaning of a project rep depends on what you are dealing with with Gradle. For example, a project might represent a library (JAR) or Web page app (Web application). It may represent the release of a ZIP archive for other project libraries. A project does not need to represent what the exact thing is to be built, it may just be used to indicate that something has been done, such as releasing your application to work or production. If you are not clear about these conceptual things, please don't be nervous. Gradle's build rules support adding a concrete definition of what one or more project exactly is.

Each project is composed of one or more tasks. A task represents an indivisible build effort. It may compile some calsses, create jars, generate Javadoc, or publish some files into the repository.

From now on, we'll focus on defining some simple tasks for a project build. Later chapters learn more about the projects and tasks of working with multiple projects.

6.2. Hello World

When you run a Gradle build with the Gradle command, the Gradle command looks for a file named Build.gradle in the current directory. We call the Build.gradle file a build script, although strictly speaking, it is a build configuration script. This build script defines a project and some tasks related to it.

To verify this, create a Build.gradle file and add the following build script.

example 6.1. Your first build script
Build.gradle

task hello {    doLast {        ‘Hello world!‘    }}

In the command line shell, go to the directory containing the Build.gradle and run gradle-q Hello to execute the build script.

Example 6.2. Run a Build script
gradle-q Hello 's output

> gradle -q helloHello world!

What's going on here? This build script defines a separate task named Hello and adds an action to it. When you run gradle Hello , Gradle executes the Hello task and then executes the action you provided. This action is a closure that contains some code that executes groovy.

If you think this looks like ant target, you're right. Gradle task tasks and ant target are similar, but you will see that they (Gradle) are more powerful. We used a different terminology than ant because we thought the word task was more expressive than target. Unfortunately, this is a term that conflicts with ant, such as an ant that calls its own commands, such as Javac or Copy,tasks. So when we talk about tasks, we're talking about gradle tasks. If we're going to say ant tasks (ant command), we'll explicitly say ant task.

6.3. A shortcut Task definition (defining shortcuts to tasks)

Here's a quick way to define a task, which is very concise, for example, to define the hell task mentioned above.
example 6.3. A task definition shortcut
Build.gradle

task hell << {    ‘Hello world!‘}

Similarly, we define an executable task called Hello, which contains a separate closure. We will use this style of task definition in the entire user guide.

6.4. Build scripts is code (build script

The Gradle build script gives you a full-featured groovy. As a primer, take a look at these 2 examples:
Example 6.4: Using Groovy in a Gradle task
Build.gradle

task upper << {    ‘mY_nAmE‘    println"Original: " + someString     println"Upper case: " + someString.toUpperCase()}

gradle-q Upper output:

uppercase: MY_NAME

Or

Example 6.5: Using Groovy in a Gradle task
Build.gradle

task count << {    4.timesprint"$it " }}

gradle-q count output:

> gradle -q count
6.5. Task dependencies (tasks dependent)

You might have thought that you could declare some tasks that you can rely on for other tasks.
example 6.6. Declaring a task that relies on other tasks
Build.gradle

task hello << {    ‘Hello world!‘}task intro(dependsOn: hello) << {    "I‘m Gradle"}

gradle-q intro output:

> gradle -q introHello world!I‘m Gradle

You can add a task that does not already exist as a dependency:
example 6.7. Lazy dependency-the other task doesn't exist yet
Build.gradle

task‘taskY‘) << {    ‘taskX‘}task taskY << {    ‘taskY‘}

gradle-q taskx output:

> gradle -q taskXtaskYtaskX

The dependency of taskx corresponds to Tasky prior to the definition of Tasky. This is important for building multiple projects. More task-dependent discussions can refer to adding multiple dependencies to a task.
Note that you cannot use a shortcut tag when you want to associate a task that does not exist. (see section 6.8)

6.6. Dynamic Tasks

Groovy is far more capable than defining a single task. For example, you can use it to create a task dynamically.
Example 6.8: Creating a task dynamically
Build.gradle

4.times { counter ->    "task$counter" << {        "I‘m task number $counter"    }}

gradle-q task1 output:

> gradle -q task1I‘m task number 1
6.7. Mainipulating Existing tasks (operation adjustment already exists)

Once the task is created, the task can be accessed by the API. For example, you can use this to dynamically add dependencies to a task at run time. Ant does not allow this behavior.
Example 6.9. Access a task through the API-add a dependency
Build.gradle

4.times { counter ->    "task$counter" << {        "I‘m task number $counter"    }}task0.dependsOn task2, task3

gradle-q task0 output:

> gradle -q task0I‘m task number 2I‘m task number 3I‘m task number 0

Or you can add additional behavior for a task that currently exists.
example 6.10. Accessing a task through the API-adding behavior
Build.gradle

{    println ‘Hello Earth‘}hello.{    println ‘Hello Venus‘}hello.{    println ‘Hello Mars‘}{    println ‘Hello Jupiter‘}

gradle-q task0 output:

> gradle -q helloHello VenusHello EarthHello MarsHello Jupiter

Calls to Dofirst and Dolast can be executed multiple times. They add an action to the start or end position of the task's action list. When the task is executed, the actions in the action list are executed sequentially. The operator << is the dolast word of the same name.

6.8. Shortcut notations (shortcut marker)

In the previous example, you might have noticed a handy marker symbol to access an already existing task. This shortcut can be used in each task as a property of the build script.
example 6.11. Accessing a task in a way that constructs a script property
Build.gradle

task hello << {    println‘Hello world!‘}hello.doLast {    println"Greetings from the $hello.name task."}

gradle-q Hello output:

fromthe hello task.

This feature makes building script code more readable, especially when using a plugin-supplied task, like a compilation task.

6.9. Extra Task properties (Extended Tasks property)

You can add custom properties to a task. Add a property named MyProperty, and set ext.myproperty an initial value. From then on, this property can be read like a predefined task property.
example 6.12. Adding an extended property to a task
Build.gradle

task myTask {    "myValue"}task printTaskProperties << {    println myTask.myProperty}

gradle-q printtaskproperties output:

> gradle -q printTaskPropertiesmyValue

Extended attributes are not limited to task. You can get more information about extended properties, refer to Extended properties.

6.10. Using ant tasks (use ant Task)

Ant tasks is very good in gradle. Gradle can be very simple to use groovy to provide very good integration for ant task. Groovy encapsulates the abstract antbuilder. Using ant task in Gradle is quite handy and more powerful than using ant tasks in Build.xml. For example, you can learn how to perform ant tasks and how to access the ant properties.
example 6.13. Use Antbuilder to perform ant.loadfile target
Build.gradle

task loadfile << {    filesfile(‘../antLoadfileResources‘).listFiles().sort()    files.eachfile ->        if (file.isFile()) {            filefile.name)            " *** $file.name ***"            "${ant.properties[file.name]}"        }    }}

gradle-q loadfile output:

andoverandover comprehensive documentationCustomer collaboration  overtooverthetheandtheby Moshe Feldenkrais)

You can use ant in your build script to do more things. You can refer to using ant in Gradle.

6.11. Using methods (use method)

Gradle for how you organize your build logic hierarchy. The first level of organization-building logic is the above example, in advance of a method.
example 6.14. Use the method to organize your build logic
Build.gradle

Task Checksum << {fileList ('. /antloadfileresources '). each{Filefile-Ant.checksum (file:file, Property:"Cs_$file.name") println"$file. Name Checksum: ${ant.properties["cs_$file. Name"]}"}}task loadfile << {fileList ('. /antloadfileresources '). each{FilefileAnt.loadfile (srcfile:file, Property:file. Name) println"I ' m fond of $file. Name"}}file[] FileList (String dir) {file(dir). Listfiles ({file-file. Isfile ()} asFileFilter).Sort()}

gradle-q loadfile output:

> gradle -q loadfileI‘mof agile.manifesto.txtI‘mof gradle.manifesto.txt

Later you'll see that there are a number of shared approaches between sub-projects in the context of multiple project builds. If your build logic becomes more complex, Gradle can provide you with other very convenient ways to organize your build logic. We have prepared a whole chapter to discuss it. You can see the organization build logic.

6.12. Default Tasks

Gradle allows you to define one or more default tasks for your build.
example 6.15. Defining Default Tasks
Build.gradle

‘clean‘‘run‘task clean << {    ‘Default Cleaning!‘}task run << {    ‘Default Running!‘}task other << {    "I‘m not a default task!"}

gradle-q Output:

> gradle -qDefault Cleaning!Default Running!

This is equivalent to going to allow Gradle clean run. In a multi-project build, each subproject can have its own specified default tasks. If a subproject does not specify a default task, the default task for the parent project is used if the parent project has a default task.

6.13. Configure by DAG (configuration of a directed acyclic graph)

As we specify later (refer to the life cycle of the build), Gradle has a configuration phase and an execution phase. After the configuration phase is complete, Gradle understands that all the tasks.gradle that will be executed will provide you with a hook that allows you to use this information. One use case is to check if the release task is among these tasks that are about to be executed. Depending on this, you can assign different values to some variables.
In the following example, the 2 tasks for distribution and release will have different version values.
example 6.16. Select a different task to output a different result
Build.gradle

task distribution << {    "We build the zip with version=$version"}task‘distribution‘) << {    ‘We release now‘}gradle.taskGraph.whenReady {taskGraph ->    if (taskGraph.hasTask(release)) {        ‘1.0‘    else {        ‘1.0-SNAPSHOT‘    }}

gradle-q distribution output:

thewithversion=1.0-SNAPSHOT

gradle-q release output:

thewithversion=1.0We release now

The important thing is that Whenready affected the release task before release was executed. Even if release is not a primary task, it can take effect.

6.14. Where to next? (How to learn next?) )

In this section, we briefly introduce the task. But the task of learning is not over. If you want to learn more about tasks in more detail, learn here: more about task.

Otherwise, continue to chapter seventh Java Quick Start Tutorials and chapter eighth rely on the Management foundation.

Gradle User Guide Beginner's tutorial (iii)

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.