Table of contents
Open Table of contents
- Explore about Build Tool
- Purposes of Build Tools
- What is Groovy
- What is Maven
- Lighten the word - Gradle
- Gradle - Features
- Advantages of Gradle over Maven
- Gradle Configuration Files
- Gradle Plugins
- Types of Plugin
- Jenkins - all you want to know
- Workflow of Jenkins
- Jenkins Installation
- Jenkins Configuration
- Gradle - Linking with Android Studio
- Explanation of gradle file in Android studio
- Summary
Explore about Build Tool
- It is a software tool used in software development to automate various tasks related to building, compiling, testing, and packaging software projects.
- It plays a crucial role in managing the entire software development lifecycle, from source code to the final executable or distributable product.
- Build tools help developers streamline and standardize the build process, making it more efficient, repeatable, and less error-prone.
- Build tools ensure consistency, reliability, and efficiency in the software build and deployment processes.
Examples of Build Tools : Ant, Maven, Gradle, and NAnt, Make, CMake, npm etc
Purposes of Build Tools
-
Compilation: Build tools compile source code into executable code or machine-readable instructions (e.g., bytecode).
-
Dependency Management: Build tools manage project dependencies, including libraries, frameworks, and external modules.
-
Automated Testing: Run automated tests (e.g., unit tests, integration tests, and acceptance tests) to verify the correctness and quality of the software.
-
Packaging: They package the compiled code and resources into deployable artifacts, such as executable files, JAR files, WAR files, or APK files, depending on the platform and technology stack.
-
Versioning: Build tools can automatically generate version numbers or timestamps for the built artifacts for proper versioning and tracking of software releases.
-
Optimization: To improve performance and reducing final distribution size, some build tools perform code optimization and resource compression.
-
Documentation Generation: Build tools can generate documentation from code comments or documentation files, helping developers maintain up-to-date documentation for their projects.
-
Continuous Integration (CI) and Continuous Deployment (CD): Build tools are often integrated with CI/CD pipelines to automate the build and deployment processes whenever changes are pushed to version control repositories.
What is Groovy
- Provides greater transparency for Java people.
- The base syntax, type system, and package structure of Groovy are the same as Java.
- Overcomes all Java limitations
- Reduces the size of a build script
- Groovy is far more readable
- The reduced line of code implies a reduction in time.
What is Maven
- Maven is an open-source build automation and project management tool making it easier for developers to collaborate on projects and manage dependencies, while ensuring consistency and reproducibility in software builds.
- It is a widely adopted tool in the Java ecosystem and plays a crucial role in simplifying the build, dependency management, and project organization processes.
- Maven uses an XML-based configuration file called pom.xml (Project Object Model) to define project settings, dependencies, and plugins.
- The pom.xml file serves as the project’s blueprint, specifying how the project should be built, tested, and packaged.
Lighten the word - Gradle
- Gradle is an open-source build automation tool that is widely used in the software development industry, including Android app development.
- It is primarily used for building, configuring, and managing projects.
- Gradle uses a domain-specific language (DSL) based on Groovy or Kotlin for writing build scripts, which are typically named build.gradle.
Gradle - Features
Gradle is an open-source project, and it is licensed under the Apache Software License (ASL).
Following are some of the features:
- Utilizes a Domain Specific Language (DSL) based on Groovy or kotlin to declare builds.
- Gradle allows to monitor and configure the build script’s execution behavior.
- Manages dependencies and Structures the build.
- Supports Ant tasks and projects.
- Uses Maven and Ivy repositories to publish or fetch dependencies.
- Supports incremental builds by executing only the necessary tasks in a build.
- Increases productivity.
- Supports multi-project builds.
- Extends easy migration of builds.
- Gradle’s build scripts are written in Groovy, not XML.
The Gradle Wrapper allows to execute Gradle builds on machines where Gradle is not installed.
Advantages of Gradle over Maven
Gradle and Maven are both popular build automation tools used in software development, especially in the Java ecosystem.
-
Groovy and Kotlin DSL Support: Gradle allows build scripts to be written in either Groovy or Kotlin, providing more flexibility and expressiveness compared to Maven’s XML-based POM files.
-
Performance: Gradle is known for its highly optimized, improved performance, handling large multi-module projects. It only rebuilds if a changes has happened since the last build and significantly speed up the build process.
-
Dynamic Dependency Resolution: Gradle can resolve and download dependencies at runtime based on specific configurations and which is useful for managing different build variants or flavours.
-
Gradle Wrapper: Gradle includes a “wrapper” feature, which allows to specify the Gradle version for the project ensuring that all team members are using the same Gradle version, reducing compatibility issues.
-
Integrated Testing Framework: Gradle provides an integrated testing framework (Gradle TestKit) for writing and running tests against build logic.
Gradle Configuration Files
The Gradle build has the following three configuration files:
-
The Gradle build script (build.gradle) specifies a project and its tasks.
-
The Gradle properties file (gradle.properties) is used to configure the properties of the build.
-
The Gradle Settings file (settings.gradle) is optional in a build which has only one project. If Gradle build has more than one project, it is necessary as it explains which projects engage to the build. Each multi-project build should include a settings file in the project hierarchy’s root project.
build.gradle :
- build.gradle is the file located in the root folder of the project.
- This file is the build script for the project.
- It defines a project and its tasks.
- This can be written in Groovy or Kotlin.
Gradle Plugins
A Gradle plugin works as an extension to Gradle. It extends the project’s capabilities when applied to a project. Gradle comes with several plug-ins, and one can create custom plug-ins.
Example: Java plug-in adds tasks to a project that permits to create a JAR file, run unit tests and compile Java source code.
- A plug-in is included in a build.gradle file with the apply plugin:‘pluginname’ statement.
Example: The entry apply plugin:‘com.android.application’ makes the Android plug-in available for a Gradle build.
Gradle also provides a registry for plug-ins via https://plugins.gradle.org/
- Plugins are applied using the Project.apply() method. The same plugin can be applied multiple times.
Types of Plugin
Script Plugins :
Script plugins are an effective way to modularize and share common build logic and configurations across multiple projects or modules. They help keep build scripts clean, promote consistency, and reduce the need to duplicate code in multiple build.gradle files.
- They are additional build scripts.
- They follow a declarative approach to manipulate the build.
- They are applied from a script on the local filesystem or at a remote location.
Example: Applying a script plugin
apply from: 'other.gradle'
Binary Plugins :
In Gradle, a “binary plugin” typically refers to a plugin that provides binary artifacts for use in other projects, such as libraries, frameworks, or executables. Binary plugins are distributed as JAR files or other binary artifacts, and they can be applied to Gradle projects to extend their functionality.
- They are classes that implement the plugin interface.
- They follow a programmatic approach to manipulate the build.
- They occupy within a build script/project hierarchy/externally in a plugin jar.
Example: Applying a binary plugin
apply plugin: 'java'
Applied using a unique plugin id (in the above case - ‘java’)
Java Plugins :
In Gradle, the Java Plugin is one of the core plugins that provides a set of tasks and configurations for building and managing Java projects. This plugin simplifies the process of compiling Java source code, managing project dependencies, and creating JAR files for distribution.
- It acts as the basis for many of the other Gradle plugins.
To work with the Java plugin:
- Create a Java source file
- Use the tasks of the plugin to build the source file.
Example: Using the Java plugin
apply plugin: 'java'
The above code is included in the build script to use Java plugin. By default, the plugin searches for Java source file in the directory src/main/java, relative to the project directory.
Jenkins - all you want to know
- Jenkins is an open-source automation server that is widely used for building, deploying, and automating projects, particularly in the field of software development.
- Performs software build using build tools such as Maven, Gradle, and Ant.
- Offers a variety of plugins supporting build, deployment, and automation of projects.
- Supports different repositories like SVN and Git.
- Jenkins is a popular choice for organizations looking to implement CI/CD pipelines and automate various aspects of the software development and deployment lifecycle.
- It helps teams deliver software faster, with higher quality, and with fewer manual interventions, ultimately improving productivity and reducing the risk of errors.
Features of Jenkins
-
Automation: Jenkins allows developers to automate repetitive tasks, such as building code, running tests, and deploying applications, reducing the human error and saves time.
-
Integration: Jenkins integrates with a wide range of version control systems, build tools, testing frameworks, and deployment platforms, making it adaptable to various software development environments.
-
Plugins: Jenkins offers a rich ecosystem of plugins, covering various use cases, including source code management, build tools, notifications, and reporting.
-
Continuous Integration (CI): Jenkins supports CI by automatically building and testing code changes as they are committed to version control repositories.
-
Continuous Delivery (CD): Jenkins can automate the deployment process, enabling continuous delivery of applications to various environments, such as development, staging, and production.
-
Pipeline as Code: Jenkins provides a feature called “Pipeline as Code” (Jenkinsfile) that allows to define the build and deployment pipelines using code. This approach promotes consistency and reproducibility in your CI/CD processes.
-
Security: Jenkins offers security features, including user authentication, role-based access control (RBAC), and integration with authentication providers like LDAP and Active Directory.
Workflow of Jenkins
This workflow represents a typical CI/CD pipeline in Jenkins, but the exact steps and configurations can vary depending on the project’s requirements and complexity. Jenkins offers flexibility in defining and customizing these workflows to meet specific needs. Pipeline scripts (Jenkinsfiles) provide a powerful way to describe more complex and customizable workflows in code.
Step 1 : Version Control Integration -> Developers commit code changes to a version control system (e.g., Git, SVN) hosted on a remote repository server.
Step 2 : Webhook or Polling -> Jenkins can be configured to either poll the version control system at regular intervals or use webhooks to detect changes automatically.
Step 3 : Triggering a build -> When Jenkins detects a code change or is triggered manually, it initiates the build process. This is often the first step in a CI/CD pipeline.
Step 4 : Workspace preparation -> Jenkins creates a workspace for the build, which is a directory where it will perform all build-related operations. This workspace is isolated for each build to prevent interference between different builds.
Step 5 : Build Environment Setup -> Depending on the project’s requirements, Jenkins may set up a build environment that includes the necessary build tools, dependencies, and configurations. This can be achieved using build agents, Docker containers, or virtual machines.
Step 6 : Build Process -> Jenkins executes the build process, which can involve compiling source code, running unit tests, performing code analysis, generating artifacts, and more. The specific tasks depend on the project’s build script or configuration.
Step 7 : Artifact Generation -> If the build is successful, Jenkins generates artifacts such as JAR files, WAR files, or other binaries that are ready for deployment.
Step 8 : Testing -> Jenkins can run automated tests on the built artifacts, including unit tests, integration tests, and end-to-end tests. It records test results and generates reports.
Step 9 : Quality Assurance -> Code quality checks and static code analysis tools can be integrated into the workflow to ensure code quality and compliance with coding standards.
Step 10 : Artifact Archiving and Storage -> Successful build artifacts and test results are archived and stored for future reference and deployments. Jenkins can also publish these artifacts to a repository manager (e.g., Nexus, Artifactory).
Step 11 : Deployment -> Depending on the project’s deployment strategy, Jenkins can automate the deployment of artifacts to different environments, such as development, staging, and production.
Step 12 : Notification and Reporting -> Jenkins can send notifications via email, slack messages and integration with collaboration tools to relevant stakeholders about the build status, test results, and deployment outcomes.
Step 13 : Monitoring Logging and Reporting -> Jenkins provides monitoring capabilities to track build and deployment progress. It also generates logs for debugging and auditing purposes.
Step 14 : Post Build Action -> After the build and deployment are complete, Jenkins can perform additional actions, such as triggering downstream builds, archiving build artifacts, and cleaning up resources.
Step 15 : Pipeline Visualization -> Jenkins provides visualization tools to monitor the progress of the pipeline and see the status of each stage and task.
Jenkins Installation
- Download jenkins.war from http://jenkins-ci.org/.
- After the download, it can be deployed in a container such as Tomcat, or via the command line with java -jar jenkins*.war.
- If it is started locally, open a browser and type the following URL: http://localhost:8080/ and Jenkins welcome page will be displayed.
Jenkins Configuration
Configure the following plugins for Jenkins:
- Gradle Plugin
- Git Plugin (required if Git is used as a repository)
The Jenkins welcome page is shown above.
- Click Manage Jenkins on the left-hand side vertical menu.
- A list of different categories will be displayed.
- Click Manage Plugins. Four tabs will be displayed.
- Go to the Available tab and filter (top right) for Gradle Plugin.
- Select the plugin and click Download now and install it.
This adds Gradle build execution capability to the Jenkins server.
- Next, configure JDK, Gradle, and Git with Jenkins.
To configure these settings:
- Open Jenkins URL.
- Click Manage Jenkins and click Configure System.
- Enter the path to JDK and save the settings.
Create the First Gradle Build Job ~
Jobs are the unit of execution in Jenkins. A build job can perform compilation, run automated tests, package and deployment related tasks.
Steps:
- Go to Jenkins home page and click Create new jobs.
- Choose a category of jobs (Freestyle project) that can be created in Jenkins.
- Type a name for the project and then click OK.
In the next page, the following details have to be configured:
- Source code management location to download the project.
- Build step for the project.
- Schedule the Build task (daily, hourly, after every commit, etc.).
- Put in any post build action to perform.
After saving the configurations, the project will be displayed on the dashboard.
Execute Job ~
- Click the <name_of_project> job on the Jenkins home page. It gets navigated to the job console at http://localhost:8080/job/name_of_project/.
- On the job console, click the Build Now option (left-hand side) to execute the job manually.
Gradle - Linking with Android Studio
- Gradle is regarded as the build tool for Android Studio.
- Android Studio assigns the entire process of building android apps to Gradle.
- Gradle doesn’t know anything about Android. Thus Android Gradle plugin is leveraged to bridge the gap.
- Gradle offers to create variants of apps easily like, debug and release builds
Android Studio creates :
- build.gradle for the parent project
- individual build.gradle files for the subprojects.
- creates settings.gradle file that includes all the subprojects.
Android Studio also adds Gradle Wrapper. So, Android project can be built on a machine where Gradle is not installed.
The build.gradle file of the app folder is used to build the Android application. The below configurations helps to get build with Gradle.
apply plugin: 'com.android.application'
android {
compileSdkVersion 34
buildToolsVersion "22.0.1"
defaultConfig {
applicationId "ch10.androidsampleapp"
minSdkVersion 30
targetSdkVersion 22
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:22.1.1'
}
Explanation of gradle file in Android studio
- Project-level Gradle File (build.gradle in the project root directory): This Gradle file, located in the root directory of your Android project, configures settings that apply to the entire project. It mainly deals with the Gradle plugin version and repositories.
buildscript
Block: is used to define the build script dependencies and the classpath for the Gradle plugins. It specifies which Gradle plugin versions to use for the entire project.
buildscript {
repositories {
google() // Google's Maven repository
jcenter() // JCenter repository
}
dependencies {
classpath 'com.android.tools.build:gradle:7.0.0' // Android Gradle Plugin version
}
}
allprojects
Block: can be used to configure repositories and dependencies that apply to all modules in the project. It’s often used to specify common repositories for all modules.
allprojects {
repositories {
google()
jcenter()
}
}
- task Definitions: One can define custom tasks and configurations at the project level, although this is less common. These customizations can affect the entire project.
- Module-level Gradle File (build.gradle in the “app” module directory): This Gradle file, located in the “app” module directory (e.g., app/build.gradle), configures settings that apply specifically to the Android app module, including dependencies, build types, flavours, and more.
apply plugin
Statement: is used to apply the Android Gradle Plugin and other plugins to the module. The most common plugin applied is the com.android.application plugin for Android app modules.
apply plugin: 'com.android.application'
android
Block: contains configurations related to the Android app, such as compileSdkVersion, buildToolsVersion, defaultConfig, buildTypes, and productFlavors.
android {
compileSdkVersion 30
buildToolsVersion "30.0.3"
defaultConfig {
applicationId "com.example.myapp"
minSdkVersion 16
targetSdkVersion 30
// ...
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
// ...
}
dependencies
Block: specifies the project’s dependencies, including libraries and external dependencies fetched from repositories like Maven or JCenter.
dependencies {
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
// ...
}
buildTypes
andproductFlavors
block: The buildTypes configuration is used to define types or environments of build, such as debug, release, QA. By default, both the debug and release versions of the Android project are in the build/outputs/apk directory. Product flavors to create variations of your app, each with its own configurations and resources.
One can customize both build and release build types and also extend the build types by adding your own build types, as follows:
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
staging.initWith(buildTypes.release)
staging {
debuggable true
}
productFlavors {
free {
// Flavor-specific configurations
}
paid {
// Flavor-specific configurations
}
}
}
In this above example, one more build type staging is added and configured it to be a copy of the release build type and added debuggable true.
proGuard
file: This section specifies ProGuard configuration files for code shrinking and obfuscation.
buildTypes {
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
Summary
Gradle has become the standard build tool for Android app development, and many Android projects use Gradle for managing dependencies, building APKs, and customizing build processes. Gradle’s flexibility and extensibility make it a powerful choice for a wide range of software projects beyond Android development as well.