34,79 €
Gradle is a project automation tool that has a wide range of applications. The basic aim of Gradle is to automate a wide variety of tasks performed by software developers, including compiling computer source code to binary code, packaging binary codes, running tests, deploying applications to production systems, and creating documentation.
The book will start with the fundamentals of Gradle and introduce you to the tools that will be used in further chapters. You will learn to create and work with Gradle scripts and then see how to use Gradle to build your Java Projects. While building Java application, you will find out about other important topics such as dependency management, publishing artifacts, and integrating the application with other JVM languages such as Scala and Groovy.
By the end of this book, you will be able to use Gradle in your daily development. Writing tasks, applying plugins, and creating build logic will be your second nature.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 350
Veröffentlichungsjahr: 2016
Copyright © 2016 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: October 2012
Second edition: May 2016
Production reference: 1250516
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.
ISBN 978-1-78439-497-4
www.packtpub.com
Author
Hubert Klein Ikkink
Copy Editor
Vibha Shukla
Reviewer
Izzet Mustafaiev
Project Coordinator
Shweta H Birwatkar
Commissioning Editor
Amarabha Banerjee
Proofreader
Safis Editing
Acquisition Editor
Manish Nainani
Indexer
Mariammal Chettiyar
Content Development Editor
Shweta Pant
Graphics
Disha Haria
Technical Editor
Suwarna Patil
Production Coordinator
Nilesh Mohite
Hubert Klein Ikkink was born in 1973 and currently lives in Tilburg, Netherlands, with his beautiful wife and gorgeous children. He is also known as mrhaki, which is simply the first letters of his name prepended with mr. He studied information systems and management at Tilburg University. After finishing his studies, he started working at a company specialized in knowledge-based software. There he started writing his first Java software (yes, an applet!) in 1996. During these years, his focus switched from applets to servlets to Java Enterprise Edition applications to Spring-based software.
In 2008, he wanted to have fun when writing software. The larger projects he was working on were more about writing configuration XML files and tuning performance and less about real development in his eyes, so he started to look around and noticed that Groovy was a very good language to learn. He could still use the existing Java code and libraries and use his Groovy classes in Java. The learning curve isn't steep and to support his learning phase, he wrote interesting Groovy facts on his blog with the title Groovy Goodness. He posts small articles with a lot of code samples to understand how to use Groovy. Since November 2011, he is also a DZone Most Valuable Blogger (MVB), where DZone post his blog items on their site. During these years, he also wrote about other subjects such as Grails, Gradle, Spock, Asciidoctor, and Ratpack.
Hubert was invited to speak at conferences such as Gr8Conf in Copenhagen, Minneapolis, and Greach, Madrid. Also, he gave presentations at Java conferences such as JFall in Netherlands and Javaland in Germany.
Hubert works for a company called JDriven in Netherlands. JDriven focuses on technologies that simplify and improve development of enterprise applications. Employees of JDriven have years of experience with Java and related technologies and are all eager to learn about new technologies. Hubert works on projects using Grails and Java combined with Groovy and Gradle.
It was a great honor to be asked by Packt Publishing to write this book. I knew it beforehand that it would be a lot of work and somehow needed to be combined with my daytime job. I couldn't have written the book without the help of a lot of people and I want to thank all these people.
First of all, I would like to thank my family for supporting me while writing the book. They gave me space and time to write the book. Thank you for your patience and a big kiss to Kim, Britt, Liam, and Chloë, I love you. Of course, I would also like to thank all the people at Gradle Inc. for making Gradle such a great build tool.
Finally, I would like to thank the great staff at Packt Publishing. Shweta Pant kept me on schedule and made sure everything was submitted on time. I would also like to thank all the editors for reviewing the book. They really helped me to keep focus and be concise with the text.
Izzet Mustafaiev is a family guy with a tendency of having BBQ parties and traveling.
Professionally, he's a software engineer, working with EPAM Systems with primary language—Java, hands on Groovy/Ruby, and exploring FP with Erlang/Elixir. Izzet has participated in different projects as a developer and architect. He advocates XP, clean code, and DevOps habits and practices, speaking at engineering conferences.
For support files and downloads related to your book, please visit www.PacktPub.com.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
https://www2.packtpub.com/books/subscription/packtlib
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.
If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view 9 entirely free books. Simply use your login credentials for immediate access.
Gradle is the next generation in build automation. Gradle uses convention-over-configuration to provide good defaults, but it is also flexible to be used in every situation you encounter in daily development. Build logic is described with a powerful DSL and empowers developers to create reusable and maintainable build logic.
We will see more about Gradle in this book. We will discuss Gradle's features with code samples throughout the book. We will also discuss how to write tasks, work with files, and write build scripts using the Groovy DSL. Next, we will discuss how to use Gradle in projects to compile, package, test, check code quality, and deploy applications. Finally we will see how to integrate Gradle with continuous integration servers and development environments (IDEs).
After reading this book, you will know how to use Gradle in your daily development. We can write tasks, apply plugins, and write build logic using the Gradle build language.
Chapter 1, Starting with Gradle, introduces Gradle and how to install it. We will write our first Gradle script and discuss command-line and GUI features of Gradle.
Chapter 2, Creating Gradle Build Scripts, looks at tasks as part of the Gradle build scripts. We will see how to define tasks and how to use task dependencies to describe the build logic.
Chapter 3, Working with Gradle Build Scripts, covers more functionalities that we can apply in Gradle scripts. We will discuss how to work with files and directories, apply logging to our build scripts, and use properties to parameterize our build scripts.
Chapter 4, Using Gradle for Java Projects, discusses all about using the Java plugin for Gradle projects. Gradle offers several tasks and configuration convention that makes working with Java project very easy. We see how to customize the configuration for project that cannot follow the conventions.
Chapter 5, Dependency Management, covers the support for dependencies by Gradle. We will discuss how to use configurations to organize dependencies. We will also see how to use repositories with dependencies in our build scripts.
Chapter 6, Testing, Building, and Publishing Artifacts, introduces the support of Gradle to run tests from the build script. We will discuss how to build several artifacts for a project and how to publish the artifacts to a repository so that other developers can reuse our code.
Chapter 7, Multi-project Builds, covers Gradle's support for multi-project builds. With Gradle, we can configure multiple projects that can be related to each other easily. We will also see how Gradle can automatically build related or dependent projects if necessary.
Chapter 8, Mixed Languages, explains the Scala and Groovy plugin that is included with Gradle to work with projects that have Scala or Groovy code.
Chapter 9, Maintaining Code Quality, introduces the code quality plugins of Gradle. We will see how to use and configure the plugins to include code analysis in our build process.
Chapter 10, Writing Custom Tasks and Plugins, introduces what we need to do to write our own custom task and plugins. We will see how to decouple the definition and usage of a custom task and plugin in separate source files. We will also discuss how to reuse our custom task and plugin in other projects.
Chapter 11, Gradle in the Enterprise, introduces the support of several continuous integration tools for Gradle. We will discuss how to configure a continuous integration server to automatically invoke our Gradle build scripts.
Chapter 12, IDE Support, looks at how Gradle can generate project files for Eclipse and IntelliJ IDEA. We will also see how the IDEs support Gradle from within the IDE in order to run, for example, tasks and keep track of dependencies defined in Gradle scripts.
In order to work with Gradle and the code samples in the book, we need at least a Java Development Toolkit (JDK, 1.6 or higher version), Gradle, and a good text editor. In the first chapter, we will see how to install Gradle on our computer.
You are working on Java (Scala and Groovy) applications and want to use build automation to automatically compile, package, and deploy your application. You might have worked with other build automation tools, such as Maven or ANT, but this is not necessary to understand the topics in this book.
In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.
Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "We can include other contexts through the use of the include directive."
A block of code is set as follows:
task helloWorld << { println 'Hello world.' }Any command-line input or output is written as follows:
$ gradle -v------------------------------------------------------------ Gradle 2.12------------------------------------------------------------ Build time: 2016-03-14 08:32:03 UTCChapter 1[ 5 ] Build number: none Revision: b29fbb64ad6b068cb3f05f7e40dc670472129bc0 Groovy: 2.4.4 Ant: Apache Ant(TM) version 1.9.3 compiled on December23 2013 JVM: 1.8.0_66 (Oracle Corporation 25.66-b17) OS: Mac OS X 10.11.3 x86_64New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "With the Gradle GUI, we have a graphical overview of the tasks in a project and we can execute them by simply clicking on the mouse."
Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.
To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
You can download the code files by following these steps:
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Gradle-Effective-Implementations-Guide-Second-Edition. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at [email protected] with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.
When we develop a software, we write, compile, test, package, and finally, distribute the code. We can automate these steps by using a build system. The big advantage is that we have a repeatable sequence of steps. The build system will always follow the steps that we have defined, so we can concentrate on writing the actual code and don't have to worry about the other steps.
Gradle is one such build system.
In this chapter, we will cover the following topics:
Gradle is a tool for build automation. With Gradle, we can automate compiling, testing, packaging, and deployment of our software or any other types of projects. Gradle is flexible, but has sensible defaults for most projects. This means that we can rely on the defaults if we don't want something special, but we can still can use the flexibility to adapt a build to certain custom needs.
Gradle is already used by large open source projects such as Spring, Hibernate, and Grails. Enterprise companies such as LinkedIn and Netflix also use Gradle.
In this chapter, we will explain what Gradle is and how to use it in our development projects.
Let's take a look at some of Gradle's features.
Gradle uses a Domain Specific Language (DSL) based on Groovy to declare builds. The DSL provides a flexible language that can be extended by us. As the DSL is based on Groovy, we can write Groovy code to describe a build and use the power and expressiveness of the Groovy language. Groovy is a language for the Java Virtual Machine (JVM), such as Java and Scala. Groovy makes it easy to work with collections, has closures, and a lot of useful features. The syntax is closely related to the Java syntax. In fact, we could write a Groovy class file with Java syntax and it will compile. However, using the Groovy syntax makes it easier to express the code intent and we need less boilerplate code than with Java. To get the most out of Gradle, it is best to also learn the basics of the Groovy language, but it is not necessary to start writing Gradle scripts.
Gradle is designed to be a build language and not a rigid framework. The Gradle core itself is written in Java and Groovy. To extend Gradle, we can use Java and Groovy to write our custom code. We can even write our custom code in Scala if we want to.
Gradle provides support for Java, Groovy, Scala, web, and OSGi projects out of the box. These projects have sensible convention-over-configuration settings that we probably already use ourselves. However, we have the flexibility to change these configuration settings if required for our projects.
Gradle supports Ant Tasks and projects. We can import an Ant build and reuse all the tasks. However, we can also write Gradle tasks dependent on Ant Tasks. The integration also applies for properties, paths, and so on.
Maven and Ivy repositories are supported to publish or fetch dependencies. So, we can continue to use any repository infrastructure that we already have.
With Gradle, we have incremental builds. This means the tasks in a build are only executed if necessary. For example, a task to compile source code will first check whether the sources have changed since the last execution of the task. If the sources have changed, the task is executed; but if the sources haven't changed, the execution of the task is skipped and the task is marked as being up to date.
Gradle supports this mechanism for a lot of provided tasks. However, we can also use this for tasks that we write ourselves.
Gradle has great support for multi-project builds. A project can simply be dependent on other projects or be a dependency of other projects. We can define a graph of dependencies among projects, and Gradle can resolve these dependencies for us. We have the flexibility to define our project layout as we want.
Gradle has support for partial builds. This means that Gradle will figure out whether a project, which our project depends on, needs to be rebuild or not. If the project needs rebuilding, Gradle will do this before building our own project.
The Gradle Wrapper allows us to execute Gradle builds even if Gradle is not installed on a computer. This is a great way to distribute source code and provide the build system with it so that the source code can be built.
Also in an enterprise environment, we can have a zero-administration way for client computers to build the software. We can use the wrapper to enforce a certain Gradle version to be used so that the whole team is using the same version. We can also update the Gradle version for the wrapper, and the whole team will use the newer version as the wrapper code is checked in to version control.
Gradle is an open source project and it is licensed under the Apache License (ASL).
In this section, we will download and install Gradle before writing our first Gradle build script.
Before we install Gradle, we must make sure that we have a Java Development SE Kit (JDK) installed on our computer. Gradle requires JDK 6 or higher. Gradle will use the JDK found on the path of our computer. We can check this by running the following command on the command line:
$ java -versionAlthough Gradle uses Groovy, we don't have to install Groovy ourselves. Gradle bundles the Groovy libraries with the distribution and will ignore a Groovy installation that is already available on our computer.
Gradle is available on the Gradle website at http://www.gradle.org/downloads. From this page, we can download the latest release of Gradle. We can also download an older version if we want. We can choose among three different distributions to download. We can download the complete Gradle distribution with binaries, sources, and documentation; or we can only download the binaries; or we can only download the sources.
To get started with Gradle, we will download the standard distribution with the binaries, sources, and documentation. At the time of writing this book, the current release is 2.12.
Gradle is packaged as a ZIP file for one of the three distributions. So when we have downloaded the Gradle full-distribution ZIP file, we must unzip the file. After unpacking the ZIP file we have:
Once we have unpacked the Gradle distribution to a directory, we can open a command prompt. We go to the directory where we have installed Gradle. To check our installation, we run gradle -v and get an output with the used JDK and library versions of Gradle, as follows:
$ gradle -v------------------------------------------------------------Gradle 2.12------------------------------------------------------------Build time: 2016-03-14 08:32:03 UTCBuild number: noneRevision: b29fbb64ad6b068cb3f05f7e40dc670472129bc0Groovy: 2.4.4Ant: Apache Ant(TM) version 1.9.3 compiled on December23 2013JVM: 1.8.0_66 (Oracle Corporation 25.66-b17)OS: Mac OS X 10.11.3 x86_64Here, we can check whether the displayed version is the same as the distribution version that we have downloaded from the Gradle website.
To run Gradle on our computer, we have to only add $GRADLE_HOME/bin to our PATH environment variable. Once we have done that, we can run the gradle command from every directory on our computer.
If we want to add JVM options to Gradle, we can use the JAVA_OPTS and GRADLE_OPTS environment variables. JAVA_OPTS is a commonly used environment variable name to pass extra parameters to a Java application. Gradle also uses the GRADLE_OPTS environment variable to pass extra arguments to Gradle. Both environment variables are used, so we can even set them both with different values. This is mostly used to set, for example, an HTTP proxy or extra memory options.
Software Development Kit Manager (SDKMAN!) is a tool to manage versions of software development kits such as Gradle. Once we have installed SKDMAN!, we can simply use the install command and SDKMAN! downloads Gradle and makes sure that it is added to our $PATH variable. SDKMAN! is available for Unix-like systems, such as Linux, Mac OSX, and Cygwin (on Windows).
First, we need to install SDKMAN! with the following command in our shell:
$ curl -s get.sdkman.io | bashNext, we can install Gradle with the install command:
$ sdk install gradleDownloading: gradle 2.12% Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0 0 354 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0100 42.6M 100 42.6M 0 0 1982k 0 0:00:22 0:00:22 --:--:-- 3872kInstalling: gradle 2.12Done installing!Do you want gradle 2.12 to be set as default? (Y/n): YSetting gradle 2.12 as default.If we have multiple versions of Gradle, it is very easy to switch between versions with the use command:
$ sdk use gradle 2.12Using gradle version 2.12 in this shell.We now have a running Gradle installation. It is time to create our first Gradle build script. Gradle uses the concept of projects to define a related set of tasks. A Gradle build can have one or more projects. A project is a very broad concept in Gradle, but it is mostly a set of components that we want to build for our application.
A project has one or more tasks. Tasks are a unit of work that need to be executed by the build. Examples of tasks are compiling source code, packaging class files into a JAR file, running tests, and deploying the application.
We now know a task is a part of a project, so to create our first task, we also create our first Gradle project. We use the gradle command to run a build. Gradle will look for a file named build.gradle in the current directory. This file is the build script for our project. We define our tasks that need to be executed in this build script file.
We create a new build.gradle file and open this in a text editor. We type the following code to define our first Gradle task:
task helloWorld << { println 'Hello world.' }With this code, we will define a helloWorld task. The task will print the words Hello world. to the console. The println is a Groovy method to print text to the console and is basically a shorthand version of the System.out.println Java method.
The code between the brackets is a closure. A closure is a code block that can be assigned to a variable or passed to a method. Java doesn't support closures, but Groovy does. As Gradle uses Groovy to define the build scripts, we can use closures in our build scripts.
The << syntax is, technically speaking, an operator shorthand for the leftShift()method, which actually means add to. Therefore, here we are defining that we want to add the closure (with the println 'Hello world' statement) to our task with the helloWorld name.
First, we save build.gradle, and with the gradle helloWorld command, we execute our build:
$ gradle helloWorld:helloWorldHello world.BUILD SUCCESSFULTotal time: 2.384 secsThis build could be faster, please consider using the Gradle Daemon: https://docs.gradle.org/2.12/userguide/gradle_daemon.htmlThe first line of output shows our line Hello world. Gradle adds some more output such as the fact that the build was successful and the total time of the build. As Gradle runs in the JVM, every time we run a Gradle build, the JVM must be also started. The last line of the output shows a tip that we can use the Gradle daemon to run our builds. We will discuss more about the Gradle daemon later, but it essentially keeps Gradle running in memory so that we don't get the penalty of starting the JVM each time we run Gradle. This drastically speeds up the execution of tasks.
We can run the same build again, but only with the output of our task using the Gradle --quiet or -q command-line option. Gradle will suppress all messages except error messages. When we use the --quiet (or -q) option, we get the following output:
$ gradle --quiet helloWorldHello world.We can create our simple build script with one task. We can ask Gradle to show us the available tasks for our project. Gradle has several built-in tasks that we can execute. We type gradle -q tasks to see the tasks for our project:
$ gradle -q 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 'hello-world'. [incubating]dependencies - Displays all dependencies declared in root project 'hello-world'.dependencyInsight - Displays the insight into a specific n dependency in root project 'hello-world'.help - Displays a help message.model - Displays the configuration model of root project 'hello-world'. [incubating]projects - Displays the sub-projects of root project 'hello-world'.properties - Displays the properties of root project 'hello-world'.tasks - Displays the tasks runnable from root project 'hello-world'.Other tasks-----------helloWorldTo see all tasks and more detail, run gradle tasks --allTo see more detail about a task, run gradle help --task <task>Here, we see our helloWorld task in the Other tasks section. The Gradle built-in tasks are displayed in the Help tasks section. For example, to get some general help information, we execute the help task:
$ gradle -q helpWelcome to Gradle 2.12.To run a build, run gradle <task> ...To see a list of available tasks, run gradle tasksTo see a list of command-line options, run gradle --helpTo see more detail about a task, run gradle help --task <task>The properties task is very useful to see the properties available for our project. We haven't defined any property ourselves in the build script, but Gradle provides a lot of built-in properties. The following output shows some of the properties:
$ gradle -q properties------------------------------------------------------------Root project------------------------------------------------------------allprojects: [root project 'hello-world']ant: org.gradle.api.internal.project.DefaultAntBuilder@3bd3d05eantBuilderFactory: org.gradle.api.internal.project.DefaultAntBuilderFactory@6aba5d30artifacts: org.gradle.api.internal.artifacts.dsl.DefaultArtifactHandler_Decorated@61d34b4asDynamicObject: org.gradle.api.internal.ExtensibleDynamicObject@588307f7baseClassLoaderScope: org.gradle.api.internal.initialization.DefaultClassLoaderScope@7df76d99 buildDir: /Users/mrhaki/Projects/gradle-effective-implementation-guide-2/gradle-impl-guide-2/src/docs/asciidoc/Chapter1/Code_Files/hello-world/buildbuildFile: /Users/mrhaki/Projects/gradle-effective-implementation-guide-2/gradle-impl-guide-2/src/docs/asciidoc/Chapter1/Code_Files/hello-world/build.gradlebuildScriptSource: org.gradle.groovy.scripts.UriScriptSource@459cfccabuildscript: org.gradle.api.internal.initialization.DefaultScriptHandler@2acbc859childProjects: {}class: class org.gradle.api.internal.project.DefaultProject_DecoratedclassLoaderScope: org.gradle.api.internal.initialization.DefaultClassLoaderScope@6ab7ce48components: []configurationActions: org.gradle.configuration.project.DefaultProjectConfigurationActionContainer@2c6aed22...The dependencies task will show dependencies (if any) for our project. Our first project doesn't have any dependencies, as the output shows when we run the task:
$ gradle -q dependencies------------------------------------------------------------Root project------------------------------------------------------------No configurationsThe projects tasks will display subprojects (if any) for a root project. Our project doesn't have any subprojects. Therefore, when we run the projects task, the output shows us our project has no subprojects:
$ gradle -q projects------------------------------------------------------------Root project------------------------------------------------------------Root project 'hello-world'No sub-projectsTo see a list of the tasks of a project, run gradle <project-path>:tasksFor example, try running gradle :tasksThe model tasks displays information about the model that Gradle builds internally from our project build file. This feature is incubating, which means that the functionality can change in future versions of Gradle:
$ gradle -q model------------------------------------------------------------Root project------------------------------------------------------------+ model+ tasks | Type: org.gradle.model.ModelMap<org.gradle.api.Task> | Creator: Project.<init>.tasks() + components | Type: org.gradle.api.reporting.components.ComponentReport | Value: task ':components' | Creator: tasks.addPlaceholderAction(components) | Rules: ⤷ copyToTaskContainer + dependencies | Type: org.gradle.api.tasks.diagnostics.DependencyReportTask | Value: task ':dependencies' | Creator: tasks.addPlaceholderAction(dependencies) | Rules:...We will discuss more about these and the other tasks in this book.
Before we look at more Gradle command-line options, it is good to discuss a real-time save feature of Gradle: task name abbreviation. With task name abbreviation, we don't have to type the complete task name on the command line. We only have to type enough of the name to make it unique within the build.
In our first build, we only have one task, so the gradle h command should work just fine. However, we didn't take the built-in help task into account. So, to uniquely identify our helloWorld task, we use the hello abbreviation:
$ gradle -q helloHello world.We can also abbreviate each word in a CamelCase task name. For example, our helloWorld task name can be abbreviated to hW:
$ gradle -q hWHello world.This feature saves us the time spent in typing the complete task name and can speed up the execution of our tasks.
With just a simple build script, we already discussed that we have a couple of default tasks besides our own task that we can execute. To execute multiple tasks, we only have to add each task name to the command line. Let's execute our helloWorld custom task and built-in tasks task:
$ gradle helloWorld tasks:helloWorldHello world.: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 'hello-world'. [incubating] dependencies - Displays all dependencies declared in root project 'hello-world'.dependencyInsight - Displays the insight into a specific dependency in root project 'hello-world'.help - Displays a help message.model - Displays the configuration model of root project 'hello-world'. [incubating]projects - Displays the sub-projects of root project 'hello-world'.properties - Displays the properties of root project 'hello-world'.tasks - Displays the tasks runnable from root project 'hello-world'.Other tasks-----------helloWorldTo see all tasks and more detail, run gradle tasks --allTo see more detail about a task, run gradle help --task <task>BUILD SUCCESSFULTotal time: 2.028 secsThis build could be faster, please consider using the Gradle Daemon: https://docs.gradle.org/2.12/userguide/gradle_daemon.htmlWe see the output of both tasks. First, helloWorld is executed, followed by tasks. In the output, we see the task names prepended with a colon (:) and the output is in the next lines.
Gradle executes the tasks in the same order as they are defined in the command line. Gradle will only execute a task once during the build. So even if we define the same task multiple times, it will only be executed once. This rule also applies when tasks have dependencies on other tasks. Gradle will optimize the task execution for us and we don't have to worry about that.
The gradle command is used to execute a build. This command accepts several command-line options. We know the --quiet (or -q) option to reduce the output of a build. If we use the --help (or -h or -?) option, we see the complete list of options, as follows:
$ gradle --helpUSAGE: gradle [option...] [task...]-?, -h, --help Shows this help message.-a, --no-rebuild Do not rebuild project dependencies.-b, --build-file Specifies the build file.-c, --settings-file Specifies the settings file.--configure-on-demand Only relevant projects are configured in this build run. This means faster build for large multi-project builds. [incubating]--console Specifies which type of console output to generate. Values are 'plain', 'auto' (default) or 'rich'.--continue Continues task execution after a task failure.-D, --system-prop Set system property of the JVM (e.g. -Dmyprop=myvalue).-d, --debug Log in debug mode (includes normal stacktrace).--daemon Uses the Gradle daemon to run the build. Starts the daemon if not running.--foreground Starts the Gradle daemon in the foreground. [incubating]-g, --gradle-user-home Specifies the gradle user home directory.--gui Launches the Gradle GUI.-I, --init-script Specifies an initialization script.-i, --info Set log level to info.-m, --dry-run Runs the builds with all task actions disabled.--max-workers Configure the number of concurrent workers Gradle is allowed to use. [incubating]--no-color Do not use color in the console output. [deprecated - use --console=plain instead]--no-daemon Do not use the Gradle daemon to run the build.--offline The build should operate without accessing network resources.-P, --project-prop Set project property for the build script (e.g. -Pmyprop=myvalue).-p, --project-dir Specifies the start directory for Gradle. Defaults to current directory.--parallel Build projects in parallel. Gradle will attempt to determine the optimal number of executor threads to use. [incubating]--parallel-threads Build projects in parallel, using the specified number of executor threads. [deprecated - Please use --parallel, optionally in conjunction with --max-workers.] [incubating]--profile Profiles build execution time and generates a report in the <build_dir>/reports/profile directory.--project-cache-dir Specifies the project-specific cache directory. Defaults to .gradle in the root project directory.-q, --quiet Log errors only.--recompile-scripts Force build script recompiling.--refresh-dependencies Refresh the state of dependencies.--rerun-tasks Ignore previously cached task results.-S, --full-stacktrace Print out the full (very verbose) stacktrace for all exceptions.-s, --stacktrace Print out the stacktrace for all exceptions.--stop Stops the Gradle daemon if it is running.-t, --continuous Enables continuous build. Gradle does not exit and will re-execute tasks when task file inputs change. [incubating]-u, --no-search-upward Don't search in parent folders for a settings.gradle file.-v, --version Print version info.-x, --exclude-task Specify a task to be excluded from execution.Let's look at some of the options in more detail. The --quiet (or -q), --debug (or -d), --info (or -i), --stacktrace (or-s), and --full-stacktrace (or-S
