banner
jzman

jzman

Coding、思考、自觉。
github

Introduction to Gradle Series

I have been learning Android for a while, and I often use Gradle in development, but I don't know the principles of Gradle building projects. I plan to spend some time learning about Gradle-related knowledge. Gradle is an excellent project build tool, and its DSL (Domain Specific Language) is implemented based on Groovy. Most of its functions are realized through plugins, and you can also customize Gradle plugins. Let's start with the first article in the Gradle series.

  1. Configure the Gradle environment
  2. Gradle version Hello World
  3. Gradle Wrapper
  4. Gradle logs
  5. Gradle command line
  6. Summary

Configure the Gradle environment#

First, ensure that JAVA_HOME is configured in the environment variables. Use the following command to check if it is configured:

java -version

The execution result is shown in the figure below:

image

Prepare a version of Gradle, download it, and unzip it. The directory after unzipping is described as follows:

bin: gradle batch file
docs: documentation
init.d: initialization script files
lib: related libraries
media: built-in icon resources
samples: examples
src: source files
getting-started.html: getting started guide link
LICENSE
NOTICE

Then configure GRADLE_HOME in the environment variables, which specifically refers to the Gradle unzipped directory:

image

Next, add GRADLE_HOME\bin to the Path, as shown below:

image

Then open the console and use the command gradle -v to check the Gradle version information. If the Gradle version number, Groovy version number, JVM, and other related information are displayed correctly, it indicates that the Gradle environment has been configured successfully. The successful execution result of gradle -v is as follows:

PS E:\Gradle\study> gradle -v
------------------------------------------------------------
Gradle 4.1
------------------------------------------------------------

Build time:   2017-08-07 14:38:48 UTC
Revision:     941559e020f6c357ebb08d5c67acdb858a3defc2

Groovy:       2.4.11
Ant:          Apache Ant(TM) version 1.9.6 compiled on June 29 2015
JVM:          1.8.0_91 (Oracle Corporation 25.91-b14)
OS:           Windows 10 10.0 amd64

At this point, the Gradle build environment on Windows has been set up.

Gradle version Hello World#

When learning any language, running Hello World is undoubtedly the first step. Here, we implement a Hello World Gradle script by creating a script named build.gradle with the following content:

task hello{
	doLast{
		println 'Hello world'
	}
}

Use the command gradle -q hello to execute the above script, and the result is as follows:

PS E:\Gradle\study> gradle -q hello
Hello world

build.gradle is the default build script file for Gradle. When executing commands, it will load the build.gradle script file in the current directory by default. This build script defines a task named hello, where doLast is an action within the task. When this task is completed, the code in doLast will be called back. The parameter -q used with the gradle command specifies the log level of the output. The log output levels of gradle will be introduced later.

Gradle Wrapper#

The Wrapper is a layer of packaging for Gradle, making it easier to manage the Gradle version uniformly within a team. The Wrapper method is commonly used in project development. After using the Wrapper, there is no need to configure the Gradle build environment. When enabling Gradle with the Wrapper, it will check if Gradle has been downloaded. If not, it will download it from the configured address and perform the build, which makes it easier for developers to build projects.

Generating the Wrapper#

Gradle provides a built-in Wrapper Task to generate the directory files required for the Wrapper. Execute the gradle wrapper command in the corresponding directory to generate it, as shown below:

PS E:\Gradle\study> gradle wrapper

BUILD SUCCESSFUL in 3s
1 actionable task: 1 executed
PS E:\Gradle\study> cd wrapper

The directory of the files generated by gradle wrapper is as follows:

│─gradlew
│─gradlew.bat
└─gradle
    └─wrapper
            gradle-wrapper.jar
            gradle-wrapper.properties

Among them, gradlew and gradlew.bat are executable scripts for Linux and Windows, respectively, and they are used in the same way as the native gradle command. gradle-wrapper.jar is the jar package implemented based on specific business needs, and gradlew ultimately executes related Gradle operations through this jar package. gradle-wrapper.properties is used to configure which version of Gradle to use for build operations.

Wrapper Configuration#

When generating related files using gradle wrapper, you can specify the version number that the wrapper should use and the download address for Gradle. The commands are as follows:

// Specify the Gradle version to use
gradle wrapper --gradle-version 3.3
// Specify the address to download Gradle
gradle wrapper --gradle-distribution-url ...

The default version of Gradle is the current version of Gradle, and the download address is as follows:

https\://services.gradle.org/distributions/gradle-4.1-all.zip

Now let's look at the meanings of several fields in the Gradle configuration file gradle-wrapper.properties:

distributionBase // The main directory where the downloaded Gradle zip package is stored after unzipping
distributionPath // The path of the unzipped zip package relative to distributionBase
zipStoreBase // The path to store the Gradle zip package relative to distributionBase
zipStorePath // The path to store the Gradle zip package relative to distributionPath
distributionUrl // The download address for Gradle, usually the official website address

Below is an example of a Gradle configuration file for an Android project:

#Mon Dec 28 10:00:20 PST 2015
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip

Let me briefly introduce a few property values:

// Represents the user directory, the directory under .gradle in the user directory
GRADLE_USER_HOME
// Represents the project directory, the directory where gradlew is located under the project
PROJECT

These two values can be used to set the values of distributionBase and zipStoreBase.

Custom Wrapper Task#

The Gradle configuration file gradle-wrapper.properties is generated by the Wrapper Task. You can customize the Wrapper Task to configure the gradle-wrapper.properties file. Below is an example of a custom Wrapper Task:

task wrapper(type: Wrapper){
	gradleVersion = '3.3'
	distributionBase='GRADLE_USER_HOME'
	distributionPath='wrapper/dists'
	// Note: Do not write this way: https\://services...
	distributionUrl="https://services.gradle.org/distributions/gradle-3.3-all.zip"
}

This allows you to define the Gradle version and related storage directories for generating the Wrapper.

Gradle logs#

When building a project using Gradle, you can specify the log level to display relevant log information. Gradle's log levels mainly include six types, as follows:

ERROR // Error messages
QUIET // Important messages
WARNING // Warning messages
LIFECYCLE // Progress messages
INFO // Information messages
DEBUG // Debug information

You can control the log display level through command line options. Below are the log options that can be controlled via commands:

-q or --quiet // Indicates QUIET and higher levels
-i or --info // Indicates INFO and higher levels
-d or --debug // DEBUG and higher levels (outputs all logs)

If not specified, the default output log is LIFECYCLE and higher-level logs.

Logs mainly track the build process and debug errors. Below, we introduce the output of stack information during the project build process and how to use log information for debugging.

Output Stack Information#

By default, the output of stack information is turned off. You can enable it through the command line stack information switch. When the build fails, Gradle will output the error stack information, making it easier to locate and analyze problems, as follows:

-s or --stacktrace // Outputs key stack information
-S or --full--stacktrace // Outputs all stack information

Generally, using -s is sufficient.

Log Information Debugging#

The simplest logging is to print the variables you want to see at appropriate places. You can use the print series of methods to output logs to the console, which belongs to QUIET level logs. You can also use the built-in logger to control the display of logs at different levels, with DEBUG outputting the most complete logs and ERROR outputting the least. The usage is as follows:

// Log test
task hello{
	doLast{
		println 'Hello world'
		print 'Hi'
		logger.quiet('quiet log')
		logger.lifecycle('lifecycle log')
		logger.error('error log')
		logger.info('info log')
		logger.warn('warn log')
		logger.debug('debug log')
	}
}

The basic content of Gradle logs is as above. Practicing in actual projects is the most important.

Gradle command line#

Using the command line allows you to understand the build process to a certain extent. Compared to the convenience of IDEs, using the command line allows you to know not only what is happening but also why it is happening. You can view executable commands through help for anything that can be executed via the command line, as shown below:

gradle -h
gradle -?
gradle -help

You can use the above commands to view executable commands.

View Executable Tasks#

Taking the Wrapper as an example, you can use ./gradlew tasks to view executable tasks. The execution result is output in a grouped format, one for build-related tasks (Build Setup tasks) and another for help tasks (Help tasks). The execution result is as follows:

PS E:\Gradle\study\wrapper> ./gradlew tasks
:tasks

------------------------------------------------------------
All tasks runnable from root project
------------------------------------------------------------

Build Setup tasks
-----------------
init - Initializes a new Gradle build. [incubating]
wrapper - Generates Gradle wrapper files. [incubating]

Help tasks
----------
components - Displays the components produced by root project 'wrapper'. [incubating]
dependencies - Displays all dependencies declared in root project 'wrapper'.
dependencyInsight - Displays the insight into a specific dependency in root project 'wrapper'.
help - Displays a help message.
model - Displays the configuration model of root project 'wrapper'. [incubating]
projects - Displays the sub-projects of root project 'wrapper'.
properties - Displays the properties of root project 'wrapper'.
tasks - Displays the tasks runnable from root project 'wrapper'.

To see all tasks and more detail, run gradlew tasks --all

To see more detail about a task, run gradlew help --task <task>

BUILD SUCCESSFUL

Total time: 8.4 secs

View Help for a Specific Task#

Gradle has a built-in help task that can provide information about the usage of a specific task. The specific command is as follows:

// Command format
gradle help --task TaskName
// Example
gradle help --task projects

The execution result is as follows:

PS E:\Gradle\study\wrapper> gradle help --task projects

> Task :help
Detailed task information for projects

Path
     :projects

Type
     ProjectReportTask (org.gradle.api.tasks.diagnostics.ProjectReportTask)

Description
     Displays the sub-projects of root project 'wrapper'.

Group
     help

BUILD SUCCESSFUL in 1s
1 actionable task: 1 executed

Through the task help information, you can see the current task's group, type, and additional parameters.

In addition, third-party libraries are often used in development. So how do you force a refresh of third-party dependencies? When building the project, add the parameter --refresh-dependencies. Sometimes, if you need to run multiple tasks simultaneously, you can separate the specific tasks with spaces, such as ./gradlew t1 t2. Gradle provides a camel case abbreviation call, which can be abbreviated as follows:

// Task
newTask
// Command
./gradlew nt

Summary#

This is the first article on getting to know Gradle, mainly providing a certain understanding of Gradle and related commands, which serves as a foundation for future learning about building projects with Gradle. I hope to complete this series on learning Gradle.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.