// Copyright 2017 the original author or authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

[[tutorial_using_tasks]]
= Build Script Basics


[[sec:projects_and_tasks]]
== Projects and tasks

Everything in Gradle sits on top of two basic concepts: _projects_ and _tasks_.

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.

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.

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.

[[sec:hello_world]]
== 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.footnote:[There are command line switches to change this behavior. See <<command_line_interface.adoc#command_line_interface,Command-Line Interface>>)] 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.

To try this out, create the following build script named `build.gradle`.

=== Example: Your first build script

[source.multi-language-sample,groovy]
.build.gradle
----
include::{samplesPath}/userguide/tutorial/hello/build.gradle[]
----

In a command-line shell, move to the containing directory and execute the build script with `gradle -q hello`:

[TIP]
.What does `-q` do?
====

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 <<logging.adoc#logging,Logging>> for more details about the command-line options which affect Gradle's output.

====

=== Example: Execution of a build script

.Output of **`gradle -q hello`**
----
> gradle -q hello
include::{samplesPath}/userguide/tutorial/hello/hello.out[]
----

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.

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_.

[[sec:a_shortcut_task_definition]]
== A shortcut task definition


[NOTE]
====

This functionality is deprecated and will be removed in Gradle 5.0 without replacement. Use the methods link:{groovyDslPath}/org.gradle.api.Task.html#org.gradle.api.Task:doFirst(org.gradle.api.Action)[Task.doFirst(org.gradle.api.Action)] and link:{groovyDslPath}/org.gradle.api.Task.html#org.gradle.api.Task:doLast(org.gradle.api.Action)[Task.doLast(org.gradle.api.Action)] to define an action instead, as demonstrated by the rest of the examples in this chapter.

====

There is a shorthand way to define a task like our `hello` task above, which is more concise.

=== Example: A task definition shortcut

[source.multi-language-sample,groovy]
.build.gradle
----
include::{samplesPath}/userguide/tutorial/helloShortcut/build.gradle[]
----

Again, this defines a task called `hello` with a single closure to execute. The `&lt;&lt;` operator is simply an alias for `doLast`.

[[sec:build_scripts_are_code]]
== Build scripts are code

Gradle's build scripts give you the full power of Groovy. As an appetizer, have a look at this:

=== Example: Using Groovy in Gradle's tasks

[source.multi-language-sample,groovy]
.build.gradle
----
include::{samplesPath}/userguide/tutorial/upper/build.gradle[]
----

.Output of **`gradle -q upper`**
----
> gradle -q upper
include::{samplesPath}/userguide/tutorial/upper/upper.out[]
----

or

=== Example: Using Groovy in Gradle's tasks

[source.multi-language-sample,groovy]
.build.gradle
----
include::{samplesPath}/userguide/tutorial/count/build.gradle[]
----

.Output of **`gradle -q count`**
----
> gradle -q count
include::{samplesPath}/userguide/tutorial/count/count.out[]
----


[[sec:task_dependencies]]
== Task dependencies

As you probably have guessed, you can declare tasks that depend on other tasks.

=== Example: Declaration of task that depends on other task

[source.multi-language-sample,groovy]
.build.gradle
----
include::{samplesPath}/userguide/tutorial/intro/build.gradle[]
----

.Output of **`gradle -q intro`**
----
> gradle -q intro
include::{samplesPath}/userguide/tutorial/intro/intro.out[]
----

To add a dependency, the corresponding task does not need to exist.

=== Example: Lazy dependsOn - the other task does not exist (yet)

[source.multi-language-sample,groovy]
.build.gradle
----
include::{samplesPath}/userguide/tutorial/lazyDependsOn/build.gradle[]
----

.Output of **`gradle -q taskX`**
----
> gradle -q taskX
include::{samplesPath}/userguide/tutorial/lazyDependsOn/lazyDependsOn.out[]
----

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 <<more_about_tasks.adoc#sec:adding_dependencies_to_tasks,Adding dependencies to a task>>.

Please notice that you can't use <<#sec:shortcut_notations, shortcut notation>> when referring to a task that is not yet defined.

[[sec:dynamic_tasks]]
== 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: Dynamic creation of a task

[source.multi-language-sample,groovy]
.build.gradle
----
include::{samplesPath}/userguide/tutorial/dynamic/build.gradle[]
----

.Output of **`gradle -q task1`**
----
> gradle -q task1
include::{samplesPath}/userguide/tutorial/dynamic/dynamic.out[]
----


[[sec:manipulating_existing_tasks]]
== 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: Accessing a task via API - adding a dependency

[source.multi-language-sample,groovy]
.build.gradle
----
include::{samplesPath}/userguide/tutorial/dynamicDepends/build.gradle[]
----

.Output of **`gradle -q task0`**
----
> gradle -q task0
include::{samplesPath}/userguide/tutorial/dynamicDepends/dynamicDepends.out[]
----

Or you can add behavior to an existing task.

=== Example: Accessing a task via API - adding behaviour

[source.multi-language-sample,groovy]
.build.gradle
----
include::{samplesPath}/userguide/tutorial/helloEnhanced/build.gradle[]
----

.Output of **`gradle -q hello`**
----
> gradle -q hello
include::{samplesPath}/userguide/tutorial/helloEnhanced/helloEnhanced.out[]
----

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.

[[sec:shortcut_notations]]
== Shortcut notations

There is a convenient notation for accessing an _existing_ task. Each task is available as a property of the build script:

=== Example: Accessing task as a property of the build script

[source.multi-language-sample,groovy]
.build.gradle
----
include::{samplesPath}/userguide/tutorial/helloWithShortCut/build.gradle[]
----

.Output of **`gradle -q hello`**
----
> gradle -q hello
include::{samplesPath}/userguide/tutorial/helloWithShortCut/helloWithShortCut.out[]
----

This enables very readable code, especially when using the tasks provided by the plugins, like the `compile` task.

[[sec:extra_task_properties]]
== 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: Adding extra properties to a task

[source.multi-language-sample,groovy]
.build.gradle
----
include::{samplesPath}/userguide/tutorial/extraProperties/build.gradle[tag=taskProperties]
----

.Output of **`gradle -q printTaskProperties`**
----
> gradle -q printTaskProperties
include::{samplesPath}/userguide/tutorial/extraProperties/extraTaskProperties.out[]
----

Extra properties aren't limited to tasks. You can read more about them in <<writing_build_scripts.adoc#sec:extra_properties,Extra properties>>.

[[sec:using_ant_tasks_tutorial]]
== 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: Using AntBuilder to execute ant.loadfile target

[source.multi-language-sample,groovy]
.build.gradle
----
include::{samplesPath}/userguide/tutorial/antLoadfile/build.gradle[]
----

.Output of **`gradle -q loadfile`**
----
> gradle -q loadfile
include::{samplesPath}/userguide/tutorial/antLoadfile/antLoadfile.out[]
----

There is lots more you can do with Ant in your build scripts. You can find out more in <<ant.adoc#ant,Ant>>.

[[sec:using_methods]]
== 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: Using methods to organize your build logic

[source.multi-language-sample,groovy]
.build.gradle
----
include::{samplesPath}/userguide/tutorial/antLoadfileWithMethod/build.gradle[]
----

.Output of **`gradle -q loadfile`**
----
> gradle -q loadfile
include::{samplesPath}/userguide/tutorial/antLoadfileWithMethod/antLoadfileWithMethod.out[]
----

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 <<organizing_gradle_projects.adoc#organizing_gradle_projects,Organizing Gradle Projects>>.

[[sec:default_tasks]]
== Default tasks

Gradle allows you to define one or more default tasks that are executed if no other tasks are specified.

=== Example: Defining a default task

[source.multi-language-sample,groovy]
.build.gradle
----
include::{samplesPath}/userguide/tutorial/defaultTasks/build.gradle[]
----

.Output of **`gradle -q`**
----
> gradle -q
include::{samplesPath}/userguide/tutorial/defaultTasks/defaultTasks.out[]
----

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).

[[configure-by-dag]]
== Configure by DAG

As we later describe in full detail (see <<build_lifecycle.adoc#build_lifecycle,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: Different outcomes of build depending on chosen tasks

[source.multi-language-sample,groovy]
.build.gradle
----
include::{samplesPath}/userguide/tutorial/configByDag/build.gradle[]
----

.Output of `gradle -q distribution`
----
> gradle -q distribution
include::{samplesPath}/userguide/tutorial/configByDag/configByDagNoRelease.out[]
----

.Output of `gradle -q release`
----
> gradle -q release
include::{samplesPath}/userguide/tutorial/configByDag/configByDag.out[]
----

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).

[[sec:build_script_external_dependencies]]
== External dependencies for the build script

If your build script needs to use external libraries, you can add them to the script's classpath in the build script itself. You do this using the `buildscript()` method, passing in a closure which declares the build script classpath.

=== Example: Declaring external dependencies for the build script

[source.multi-language-sample,groovy]
.build.gradle
----
include::{samplesPath}/userguide/tutorial/externalDependency/build.gradle[tag=declare-classpath]
----

The closure passed to the `buildscript()` method configures a link:{javadocPath}/org/gradle/api/initialization/dsl/ScriptHandler.html[ScriptHandler] instance. You declare the build script classpath by adding dependencies to the `classpath` configuration. This is the same way you declare, for example, the Java compilation classpath. You can use any of the <<dependency_types.adoc#dependency_types,dependency types>> except project dependencies.

Having declared the build script classpath, you can use the classes in your build script as you would any other classes on the classpath. The following example adds to the previous example, and uses classes from the build script classpath.

=== Example: A build script with external dependencies

[source.multi-language-sample,groovy]
.build.gradle
----
include::{samplesPath}/userguide/tutorial/externalDependency/build.gradle[tag=all]
----

.Output of **`gradle -q encode`**
----
> gradle -q encode
include::{samplesPath}/userguide/tutorial/externalDependency/externalBuildDependency.out[]
----

For multi-project builds, the dependencies declared with a project's `buildscript()` method are available to the build scripts of all its sub-projects.

Build script dependencies may be Gradle plugins. Please consult <<plugins.adoc#plugins,Using Gradle Plugins>> for more information on Gradle plugins.

Every project automatically has a `buildEnvironment` task of type link:{groovyDslPath}/org.gradle.api.tasks.diagnostics.BuildEnvironmentReportTask.html[BuildEnvironmentReportTask] that can be invoked to report on the resolution of the build script dependencies.

[[sec:tasks_tutorial_where_to_next]]
== 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 <<more_about_tasks.adoc#more_about_tasks,More About Tasks>>.

Otherwise, continue on to <<tutorial_java_projects.adoc#tutorial_java_projects,the tutorials>> and <<dependency_management_for_java_projects.adoc#dependency_management_for_java_projects,Dependency Management for Java Projects>>.
