Gradle Effective Implementation Guide - Hubert Klein Ikkink - E-Book

Gradle Effective Implementation Guide E-Book

Hubert Klein Ikkink

0,0
34,79 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Gradle is the next generation in build automation. It uses convention-over-configuration to provide good defaults, but is also flexible enough to be usable 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."Gradle Effective Implementation Guide" is a great introduction and reference for using Gradle. The Gradle build language is explained with hands on code and practical applications. You learn how to apply Gradle in your Java, Scala or Groovy projects, integrate with your favorite IDE and how to integrate with well-known continuous integration servers.Start with the foundations and work your way through hands on examples to build your knowledge of Gradle to skyscraper heights. You will quickly learn the basics of Gradle, how to write tasks, work with files and how to use write build scripts using the Groovy DSL. Then as you develop you will be shown how to use Gradle for Java projects. Compile, package, test and deploy your applications with ease. When you've mastered the simple, move on to the sublime and integrate your code with continuous integration servers and IDEs. By the end of the "Gradle Effective Implementation Guide" you will be able to use Gradle in your daily development. Writing tasks, applying plugins and creating build logic will be second nature.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 347

Veröffentlichungsjahr: 2012

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Gradle Effective Implementation Guide
Credits
About the Author
Acknowledgement
About the Reviewers
www.PacktPub.com
Support files, eBooks, discount offers and more
Why Subscribe?
Free Access for Packt account holders
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. Starting with Gradle
Introducing Gradle
Declarative builds and convention over configuration
Support for Ant tasks and Maven repositories
Incremental builds
Multi-project builds
Gradle wrapper
Free and open source
Getting started
Installing Gradle
Writing our first build script
Default Gradle tasks
Task name abbreviation
Executing multiple tasks
Command-line options
Logging options
Changing the build file and directory
Running tasks without execution
Gradle daemon
Profiling
Understanding the Gradle user interface
Task Tree
Favorites
Command Line
Setup
Summary
2. Creating Gradle Build Scripts
Writing a build script
Defining tasks
Defining actions with the Action interface
Build scripts are Groovy code
Defining dependencies between tasks
Defining dependencies via tasks
Defining dependencies via closures
Setting default tasks
Organizing tasks
Adding a description to tasks
Grouping tasks together
Adding tasks in other ways
Using task rules
Accessing tasks as project properties
Adding additional properties to tasks
Avoiding common pitfalls
Skipping tasks
Using onlyIf predicates
Skipping tasks by throwing StopExecutionException
Enabling and disabling tasks
Skipping from the command line
Skipping tasks that are up-to-date
Summary
3. Working with Gradle Build Scripts
Working with files
Locating files
Using file collections
Working with file trees
Copying files
Renaming files
Filtering files
Archiving files
Project properties
Defining custom properties in script
Passing properties via the command line
Defining properties via system properties
Adding properties via environment variables
Defining properties using an external file
Using logging
Controlling output
Using the Gradle wrapper
Creating wrapper scripts
Customizing the Gradle wrapper
Summary
4. Using Gradle for Java Projects
Using plugins
Getting started
Using the Java plugin
Working with source sets
Creating a new source set
Custom configuration
Working with properties
Creating documentation
Assembling archives
Summary
5. Dependency Management
Dependency configuration
Repositories
Adding Maven repositories
Adding Ivy repositories
Adding a local directory repository
Defining dependencies
Using external module dependencies
Using project dependencies
Using file dependencies
Using client module dependencies
Using Gradle and Groovy dependencies
Accessing configuration dependencies
Setting dynamic versions
Resolving version conflicts
Adding optional ANT tasks
Using dependency configurations as files
Summary
6. Testing, Building, and Publishing Artifacts
Testing
Using TestNG for testing
Configuring the test process
Determining tests
Logging test output
Generating test reports
Running Java applications
Running an application from a project
Running an application as task
Running an application with the application plugin
Creating a distributable application archive
Publishing artifacts
Uploading to a Maven repository
Multiple artifacts
Signing artifacts
Publishing signature files
Configuring conditional signing
Packaging Java Enterprise Edition applications
Creating a WAR file
Using the War plugin
Creating an EAR file
Using the Ear plugin
Summary
7. Multi-project Builds
Working with multi-project builds
Executing tasks by project path
Using a flat layout
Defining projects
Filtering projects
Defining task dependencies between projects
Defining configuration dependencies
Working with Java multi-project builds
Using partial builds
Using the Jetty plugin
Summary
8. Mixed Languages
Using the Groovy plugin
Creating documentation with the Groovy plugin
Using the Scala plugin
Creating documentation with the Scala plugin
Summary
9. Maintaining Code Quality
Using the Checkstyle plugin
Using the PMD plugin
Using the FindBugs plugin
Using the JDepend plugin
Using the CodeNarc plugin
Using the Sonar plugin
Summary
10. Writing Custom Tasks and Plugins
Creating a custom task
Creating a custom task in the build file
Using incremental build support
Creating a task in the project source directory
Writing tests
Creating a task in a standalone project
Creating a custom plugin
Creating a plugin in the build file
Creating a plugin in the project source directory
Testing a plugin
Creating a plugin in a standalone project
Summary
11. Using Gradle with Continuous Integration
Creating a sample project
Using Jenkins
Adding the Gradle plugin
Configuring Jenkins job
Running the job
Configuring artifacts and test results
Adding Gradle versions
Using JetBrains TeamCity
Creating a project
Running the project
Using Atlassian Bamboo
Defining a build plan
Running the build plan
Summary
12. IDE Support
Using the Eclipse plugin
Customizing generated files
Customizing using DSL
Customizing with merge hooks
Customizing with XML manipulation
Merging configuration
Configuring WTP
Customizing file generation
Using the IntelliJ IDEA plugin
Customizing file generation
Customizing using DSL
Customizing with merged hooks
Customizing with XML manipulation
Running Gradle in Eclipse
Installing Gradle plugin
Importing Gradle project
Running tasks
Editing build files
Running Gradle in IntelliJ IDEA
Installing the plugin
Importing a project
Running tasks
Summary
Index

Gradle Effective Implementation Guide

Gradle Effective Implementation Guide

Copyright © 2012 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

Production Reference: 1181012

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-84951-810-9

www.packtpub.com

Cover Image by Syarafuddin (<[email protected]>)

Credits

Author

Hubert Klein Ikkink

Reviewers

René Gröschke

Rajmahendra Hegde

Michał Huniewicz

James L. Williams

Acquisition Editor

Martin Bell

Lead Technical Editor

Sweny M. Sukumaran

Technical Editors

Dipesh Panchal

Unnati Shah

Dominic Pereira

Copy Editors

Brandt D’Mello

Insiya Morbiwala

Aditya Nair

Project Coordinator

Sai Gamare

Proofreader

Maria Gould

Clyde Jenkins

Mario Cecere

Indexer

Rekha Nair

Production Coordinator

Nitesh Thakur

Cover Work

Nitesh Thakur

About the Author

Hubert Klein Ikkink was born in 1973 and lives in Tilburg, the Netherlands, with his beautiful wife and gorgeous children. He is also known as mrhaki, which is simply the initials of his name prepended by mr. He studied Information Systems and Management at the Tilburg University. After finishing his studies he started to work at a company which specialized in knowledge-based software. There he started writing his first Java software (yes, an applet!) in 1996. Over the years his focus switched from applets, to servlets, to Java Enterprise Edition applications, to Spring-based software.

In 2008 he wanted to have fun again when writing software. The larger projects he was working on were more about writing configuration XML files, tuning performance and less about real development in his eyes. So he started to look around and noticed Groovy as a good language to learn about. He could still use existing Java code, libraries, and his Groovy classes in Java. The learning curve isn’t steep and to support his learning phase he wrote down interesting Groovy facts in 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); DZone also posts his blog items on their site.

In 2010, 2011, and 2012 Hubert was invited to speak at Gr8Conf in Copenhagen, Denmark. This is a very good conference with all the project leaders of Groovy and Groovy-related projects. In November 2010 he presented a Gradle talk at the J-Fall conference of the Dutch Java User Group. In November 2011 he presented about the new features in Groovy 1.8 at the same conference. The conference is visited by 1000 Java developers and he got the chance to educate some of them about the greatness of Gradle and Groovy.

Hubert works for a company called JDriven in the 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.

Acknowledgement

It was a great honor to be asked by Packt Publishing to write this book. I knew beforehand 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 would like to thank them.

First of all I would like to thank my family for supporting me while writing this book. They gave me space and time to write the book. Thank you for your patience and a big kiss for Kim, Britt, and Liam; I love you. I also like to thank my colleagues at JDriven. They reviewed the pages I wrote and helped me by asking questions and showing interest in the progress of the book. Of course I like to thank all the people at Gradleware for making Gradle such a great build tool and René Gröschke for reviewing the chapters in the book.

Finally I’d like to thank the great staff at Packt Publishing. Sai Gamare kept me on schedule and made sure everything was submitted on time. I’d also like to thank all the editors for reviewing the book. They really helped me to keep focus and be concise with the text.

About the Reviewers

René Gröschke has been working as a Software Engineer for more than eight years now. He has worked on several international projects and regularly shares his passion and experience of agile methodologies and software craftsmanship with other developers at different national and international conferences or with bachelor students of the Baden-Wuerttemberg Cooperative State University (DHBW) in Germany.

Supporting Gradle and the Gradle community by providing plugins, patches, screencasts, and talks since the early days, René has turned his hobby into his occupation and is now part of the core developer team of Gradle working for Gradleware. From time to time, he’s contributing to other open source projects, such as Macports or Griffon.

Rajmahendra Hegde has been a Java Developer since 2000. He is currently working for Logica as Project Lead/Architect. He is a User Group lead for Java User Group – Chennai. He has contributed to JSRs and Scalaxia.com. He is the committer for Visage. His primary areas of interest are JEE, JavaFX, JVM Languages (Groovy, Scala, and Visage), NetBeans, and Gradle. You can follow him at @rajonjava.

Michał Huniewicz is a Software Developer, with several years of experience in the JVM technologies. He has been involved in projects for a variety of industries, including banking, press, finance, telecoms, and the government. He was also the head developer of an award-winning community portal. Apart from being an active blogger (http://blog.m1key.me/), he is a passionate photographer and traveller. He holds an M.Sc. degree in Computer Science from Adam Mickiewicz University. Currently, he lives in London.

I would like to thank my parents, Rita and Andrzej, for their continued support and for having faith in me.

James L. Williams is a developer based in Silicon Valley and a frequent international conference speaker. He is the author of the book Learning HTML5 Game Programming for Addison-Wesley. He blogs at http://jameswilliams.be/blog and tweets as @ecspike.

www.PacktPub.com

Support files, eBooks, discount offers and more

You might want to visit www.PacktPub.com for support files and downloads related to your book.

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.

http://PacktLib.PacktPub.com

Do you need instant solutions to your IT questions? PacktLib is Packt’s online digital book library. Here, you can access, read and search across Packt’s entire library of books. 

Why Subscribe?

Fully searchable across every book published by PacktCopy and paste, print and bookmark contentOn demand and accessible via web browser

Free Access for Packt account holders

If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view nine entirely free books. Simply use your login credentials for immediate access.

Preface

Gradle is the next-generation build automation. Not only does Gradle use convention over configuration to provide good defaults, it is also adaptable for use 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 learn about Gradle's features with code samples throughout the book. We will learn how to write tasks, work with files, and write build scripts using the Groovy DSL. Next, we will learn how to use Gradle in projects to compile, package, test, check code quality and deploy applications. And finally, we will see how to integrate Gradle with continuous integration servers and development environments (IDEs).

After reading this book, we will know how to use Gradle in our daily development. We can write tasks, apply plugins, and write build logic using the Gradle build language.

What this book covers

Chapter 1, Starting with Gradle, introduces Gradle and explains how to install Gradle. We will write our first Gradle script and learn about the 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 we can define tasks and use task dependencies to describe build logic.

Chapter 3, Working with Gradle Build Scripts, covers more functionality that we can apply in Gradle scripts. We will learn 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, is all about using the Java plugin for Gradle projects. Gradle offers several tasks and configuration conventions that make working with Java projects very easy. We will see how we can customize the configuration for projects that cannot follow the conventions.

Chapter 5, Dependency Management, covers the support for dependencies by Gradle. We will learn how to use configurations to organize dependencies. We will also see how we can use repositories with dependencies in our build scripts.

Chapter 6, Testing, Building, and Publishing Artifacts, is an introduction to Gradle support for running tests from the build script. We will learn how we can build several artifacts for a project and publish the artifacts to a repository so other developers can reuse our code.

Chapter 7, Multi-project Builds, covers Gradle's support for multi-project builds. With Gradle, we can easily configure multiple projects that are related to each other. We will also see how Gradle can automatically build related or dependent projects if necessary.

Chapter 8, Mixed Languages, is about the Scala and Groovy plugins that are included with Gradle, to work with projects that have Scala or Groovy code.

Chapter 9, Maintaining Code Quality, introduces Gradle's code quality plugins. We will see how we can use and configure the plugins to include code analysis in our build process.

Chapter 10, Writing Custom Tasks and Plugins, covers what we need to do to write our own custom tasks and plugins. We will see how we can decouple the definition and usage of a custom task and plugin into separate source files. We will also learn how we can reuse our custom tasks and plugins in other projects

Chapter 11, Using Gradle withContinuous Integration, is an introduction to the support of several continuous integration tools for Gradle. We will learn how we can 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 to run (for example) tasks, and keep track of dependencies defined in Gradle scripts.

What you need for this book

In order to work with Gradle and the code samples in the book, we need at least a Java Development Kit (JDK 1.5 or higher), Gradle, and a good text editor. In Chapter 1, Starting with Gradle, we will see how we can install Gradle on our computer.

Who this book is for

This book is for you if you work on Java (Scala or Groovy) applications and want to use build automation to compile, package, and deploy your application automatically. 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.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.

To send us general feedback, simply send an e-mail to <[email protected]>, and mention the book title via the subject of your message.

If there is a book that you need and would like to see us publish, please send us a note in the SUGGEST A TITLE form on www.packtpub.com or e-mail <[email protected]>.

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 on www.packtpub.com/authors.

Customer support

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.

Downloading the example code

You can download the example code files for all Packt books you have purchased 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.

Errata

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 would 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/support, 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 on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.

Piracy

Piracy of copyright 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.

Questions

You can contact us at <[email protected]> if you are having a problem with any aspect of the book, and we will do our best to address it.

Chapter 1. Starting with Gradle

When we develop software, we write code, compile code, test our code, package our code, 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. Each time, the build system will follow the steps we have defined, so we can concentrate on writing the actual code and not worry about the other steps.

Gradle is such a build system. In this chapter, we will explain what Gradle is and how to use it in our development projects.

Introducing Gradle

Gradle is a tool for build automation. With Gradle, we can automate the compiling, testing, packaging, and deployment of our software or other types of projects. Gradle is flexible but has sensible defaults for most projects. This means we can rely on the defaults, if we don't want something special, but can still use the flexibility to adapt a build to certain custom needs.

Gradle is already used by big open source projects, such as Spring, Hibernate, and Grails. Enterprise companies such as LinkedIn also use Gradle.

Let's take a look at some of Gradle's features.

Declarative builds and convention over configuration

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. Because 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 has 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 would compile. But, 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 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. But we have the flexibility to change these configuration settings, if needed, in our projects.

Support for Ant tasks and Maven repositories

Gradle supports Ant tasks and projects. We can import an Ant build and re-use all the tasks. But we can also write Gradle tasks dependent on Ant tasks. The integration also applies to 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 we already have.

Incremental builds

With Gradle we have incremental builds. This means tasks in a build are only executed if necessary. For example, a task to compile source code will first check whether the sources since the last execution of the task have changed. 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 the provided tasks. But we can also use this for tasks we write ourselves.

Multi-project builds

Gradle has great support for multi-project builds. A project can simply be dependent on other projects or be a dependency for other projects. We can define a graph of dependencies between projects, and Gradle can resolve those dependencies for us. We have the flexibility to define our project layout as we want.

Gradle has support for partial builds. This means Gradle will figure out if a project that our project depends on needs to be rebuilt or not. And if the project needs rebuilding, Gradle will do this before building our own project.

Gradle wrapper

The Gradle wrapper allows us to execute Gradle builds, even though 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 the whole team is using the same version.

Free and open source

Gradle is an open source project and it is licensed under the Apache Software License(ASL).

Getting started

In this section, we will download and install Gradle before writing our first Gradle build script.

Before we get and install Gradle, we must make sure we have a Java Development Kit(JDK) installed on our computer. Gradle requires JDK 5 or higher. Gradle will use the JDK found at the path set on our computer. We can check this by running the following command on the command line:

java -version

Although 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 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. Or, we can download a previous version if we want to. We can choose among three different distributions to download. We can download either the complete Gradle distribution, with binaries, sources, and documentation, or only the binaries, or only the sources.

To get started with Gradle, we download the standard distribution with the binaries, sources, and documentation. At the time of writing this book, the current release is 1.1. On computers with a Debian Linux operation sytem, we can install Gradle as a Debian package. On computers with Mac OS X, we can use MacPorts or Homebrow to install Gradle.

Installing Gradle

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 the following:

Binaries in the bin directoryDocumentation with the user guide, Groovy DSL, and the API documentation in the docs directoryA lot of samples in the samples directorySource code for Gradle in the src directorySupporting libraries for Gradle in the lib directoryA directory named init.d where we can store Gradle scripts that need to be executed each time we run Gradle

Once we have unpacked the Gradle distribution to a directory, we can open a command prompt. We change the directory to bin, which we extracted from the ZIP file. To check our installation, we run gradle -v and we get output, listing the JDK used and the library versions of Gradle:

$ gradle -v------------------------------------------------------------Gradle 1.1------------------------------------------------------------Gradle build time: Tuesday, July 31, 2012 1:24:32 PM UTCGroovy: 1.8.6Ant: Apache Ant(TM) version 1.8.4 compiled on May 22 2012Ivy: 2.2.0JVM: 1.6.0_33 (Apple Inc. 20.8-b03-424)OS: Mac OS X 10.7.4 x86_64

Here we can check whether the displayed version is the same as the distribution version we have downloaded from the Gradle website.

To run Gradle on our computer we only have to 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 environment variables JAVA_OPTS and GRADLE_OPTS. The former is a commonly used environment variable name to pass extra parameters to a Java application. Similarly, Gradle uses the GRADLE_OPTS environment variable to pass extra arguments to Gradle. Both environment variables are used so we can set them both with different values. This is mostly used to set, for example, an HTTP proxy or extra memory options.

Writing our first build script

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 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, or deploying the application.

We now know that a task is 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 those of our tasks that need to be executed in this build script file.

We create a new file, build.gradle, and open it in a text editor. We type the following code to define our first Gradle task:

task helloWorld << { println 'Hello world.' }

With this code we define a helloWorld task. The task will print the words "Hello world." to the console. println is a Groovy method to print text to the console and is basically a shorthand version of the Java method System.out.println.

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. And because Gradle uses Groovy to define the build scripts, we can use closures in our build scripts.

The << syntax is, technically speaking, operator shorthand for the method leftShift(), which actually means "add to". So, we are defining here that we want to add the closure (with the statement println 'Hello world.') to our task with the name helloWorld.

First we save build.gradle, and then with the command gradle helloWorld, we execute our build:

hello-world $ gradle helloWorld:helloWorldHello world.BUILD SUCCESSFULTotal time: 2.047 secs

The 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. Because Gradle runs in the JVM, it must be started each time we run a Gradle build.

We can run the same build again, but with only the output of our task, by using the Gradle command-line option --quiet (or -q). Gradle will suppress all messages except error messages. When we use --quiet (or -q), we get the following output:

hello-world $ gradle --quiet helloWorldHello world.

Default Gradle tasks

We created 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 we can execute. We type gradle -q tasks to see the tasks for our project:

hello-world $gradle -q tasks-----------------------------------------------------All tasks runnable from root project-----------------------------------------------------Help tasks----------dependencies - Displays the dependencies of root project 'hello-world'.help - Displays a help messageprojects - 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' (some of the displayed tasks may belong to subprojects).Other tasks-----------helloWorldTo see all tasks and more detail, run with --all.

Here, we see our task helloWorld in the Other tasks section. The Gradle built-in tasks are displayed in the Help tasks section. For example, to see some general help information, we execute the help task:

hello-world $ gradle -q helpWelcome to Gradle 1.1.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 --help

The properties task is very useful to see the properties available to 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:

hello-world $ gradle -q properties-----------------------------------------------------Root project-----------------------------------------------------additionalProperties: {}allprojects: [root project 'hello-world']ant: org.gradle.api.internal.project.DefaultAntBuilder@6af37a62antBuilderFactory: org.gradle.api.internal.project.DefaultAntBuilderFactory@16e7eec9artifacts: org.gradle.api.internal.artifacts.dsl.DefaultArtifactHandler@54edd9deasDynamicObject: org.gradle.api.internal.DynamicObjectHelper@4b7aa961buildDir: /Users/mrhaki/Projects/gradle-book/samples/chapter1/hello-world/buildbuildDirName: buildbuildFile: /Users/mrhaki/Projects/gradle-book/samples/chapter1/hello-world/build.gradle...

The dependencies task will show dependencies (if any) for our project. Our first project doesn't have any dependencies when we run the task, as the output shows:

hello-world $ gradle -q dependencies-----------------------------------------------------Root project-----------------------------------------------------No configurations

The projects task will display sub-projects (if any) for a root project. Our project doesn't have any sub-projects. So when we run the task projects, the output shows us that our project has no sub-projects.

hello-world $ 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 :tasks

Task name abbreviation

Before we look at more Gradle command-line options, it is good to learn about a real timesaving 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 command gradle h should work just fine. But then, we didn't take into account the built-in task help. So, to uniquely identify our helloWorld task, we use the abbreviation hello:

hello-world $ gradle -q helloHello world.

We can also abbreviate each word in a camel case task name. For example, our task name helloWorld can be abbreviated to hW:

hello-world $gradle -q hWHelloWorld

This feature saves us the time spent in typing the complete task name and can speed up the execution of our tasks.

Executing multiple tasks

With just a simple build script, we already learned 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 custom task helloWorld and the built-in task tasks, as follows:

hello-world $ gradle helloWorld tasks:helloWorldHello world.:tasks-----------------------------------------------------All tasks runnable from root project-----------------------------------------------------Help tasks----------dependencies - Displays the dependencies of root project 'hello-world'.help - Displays a help messageprojects - 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' (some of the displayed tasks may belong to subprojects).Other tasks-----------helloWorldTo see all tasks and more detail, run with --all.BUILD SUCCESSFULTotal time: 1.718 secs

We see the output of both the tasks. First, helloWorld is executed, followed by tasks. When executed, we see the task names prepended with a colon (:) and the output on the following lines.

Gradle executes the tasks in the same order as they are defined on the command line. Gradle will execute a task only once during the build. So even if we define the same task multiple times, it will be executed only 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.

Command-line options

The gradle command is used to execute a build. This command accepts several command-line options. We know the option --quiet (or -q) to reduce the output of a build. If we use the option --help (or -h or -?), we see the complete list of options:

hello-world $ 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, --cache Specifies how compiled build scripts should be cached. Possible values are: 'rebuild' and 'on'. Default value is 'on' [deprecated - Use '--rerun-tasks' or '--recompile-scripts' instead]-c, --settings-file Specifies the settings file.--continue Continues task execution after a task failure. [experimental]-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. [experimental]-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.--no-color Do not use color in the console output.--no-daemon Do not use the Gradle daemon to run the build.--no-opt Ignore any task optimization. [deprecated - Use '--rerun-tasks' instead]--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.--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 Refresh the state of resources of the type(s) specified. Currently only 'dependencies' is supported. [deprecated - Use '--refresh-dependencies' instead.]--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.-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.

Logging options

Let's look at some of the options in more detail. The options --quiet (or -q), --debug (or -d), --info (or -i), --stacktrace (or -s), and --full-stacktrace (or -S) control the amount of output we see when we execute tasks. To get the most detailed output we use the option --debug (or -d). This option provides a lot of output with information about the steps and classes used to run the build. The output is very verbose, therefore we will not use it much.

To get a better insight into the steps that are executed for our task, we can use the --info (or -i) option. The output is not as verbose as with --debug, but it can give a better understanding of the build steps:

hello-world $ gradle --info helloWorldStarting BuildSettings evaluated using empty settings file.Projects loaded. Root project using build file '/Users/gradle/hello-world/build.gradle'.Included projects: [root project 'hello-world']Evaluating root project 'hello-world' using build file '/Users/gradle/hello-world/build.gradle'.All projects evaluated.Selected primary task 'helloWorld'Tasks to be executed: [task ':helloWorld']:helloWorldTask ':helloWorld' has not declared any outputs, assuming that it is out-of-date.Hello world.BUILD SUCCESSFULTotal time: 1.535 secs

If our build throws exceptions, we can see the stack trace information with the options --stacktrace (or -s) and --full-stacktrace (or -S). The latter option will output the most information and is the most verbose. The options --stacktrace and --full-stracktrace can be combined with the other logging options.

Changing the build file and directory

We created our build file with the name build.gradle. This is the default name for a build file. Gradle will look for a file with this name in the current directory, to execute the build. But we can change this with the command-line options --build-file (or -b) and --project-dir (or -p).

Let's run the Gradle command from the parent directory of our current directory:

hello-world $ cd ..$ gradle --project-dir hello-world -q helloWorldHello world.

And we can also rename build.gradle to, for example, hello.build and still execute our build:

hello-world $ mv build.gradle hello.buildhello-world $ gradle --build-file -q helloWorldHello world.