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 functionalities are achieved through plugins, and you can also customize Gradle plugins. Let's start with the first article in the Gradle series.
- Configuring the Gradle Environment
- Gradle Version Hello World
- Gradle Wrapper
- Gradle Logs
- Gradle Command Line
- Summary
Configuring 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:
Prepare a version of Gradle, download it, and extract it. The directory structure after extraction is as follows:
bin: Gradle batch files
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 extraction directory:
Next, add GRADLE_HOME\bin to the Path, as shown below:
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 essential. 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 automatically load the build.gradle script file in the current directory. This build script defines a task named hello, where doLast is an action within the task. After this task is completed, the code in doLast will be called. 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 Gradle versions 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 facilitates developers in building projects to some extent.
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 file directory 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 according to 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 using gradle wrapper to generate related files, 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. 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 extraction
distributionPath // The path of the extracted zip package relative to distributionBase
zipStoreBase // The storage location of the Gradle zip package relative to distributionBase
zipStorePath // The storage location of 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
Additionally, here are 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 configure the gradle-wrapper.properties file without customizing the Wrapper Task. 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 like this: 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 using Gradle to build projects, 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. The following are the log options that can be controlled via commands:
-q or --quiet // Represents QUIET and higher levels
-i or --info // Represents 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 issues, as follows:
-s or --stacktrace // Outputs critical stack information
-S or --full--stacktrace // Outputs all stack information
Generally, using -s is sufficient.
Log Information Debugging#
The simplest way to log is to print the variables you want to see at appropriate locations. You can use print series methods to output logs to the console, which belongs to the QUIET level of 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 testing
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 some extent. Compared to the convenience of using an IDE, using the command line allows you to know the reasons behind it. You can view executable commands through help, as follows:
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 grouped form, one group is about build (Build Setup tasks), and the other is about help (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 help information of the task, you can see the current task's group, type, and additional parameters.
In addition, when developing, third-party libraries are often used. So how do you force refresh third-party dependencies? You can add the parameter --refresh-dependencies when building the project. Sometimes you may need to run multiple tasks simultaneously; you can separate specific tasks with spaces, such as ./gradlew t1 t2. Gradle provides a shorthand call based on camel case naming, which can be called 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. It also serves as a foundation for future learning about building projects with Gradle. I hope to complete this series on learning Gradle.