Image Credit: https://gradle.org/

Write a Custom Gradle Plugin (Part 2)

Custom Gradle task with configuration

Rupesh Urmaliya
Geek Culture
Published in
3 min readJan 11, 2021

--

In the previous blog, I have explained how to create a simple Gradle plugin. Here I’ll be discussing in more depth about Gradle task and how to configure parameters to the plugin during apply.

Let’s start writing a custom Gradle task:

Let’s take an example where I’ll be creating a resource(XML) file from JSON for an android app.

First, we’ll create a custom Gradle task and add it to the plugin.

Now we’ll have to add this task to the plugin.

Now trigger the uploadArchive task or execute from the terminal by using the below command:

Now run the SimpleTask from the app, we will get the below output.

Now let’s go one step further and read the JSON file and create the resource file from this task.

Generate resource:

First, let's create a resource.json file and place it inside the app directory (This is just for demo. You can specify any path).

Now we’ll be parsing this JSON and converting it to a color resource file. In order to achieve this, we’ll need to make changes in our SimpleTask. Here we need two main things:

  1. Input file path (resource.json)
  2. Output file path (resource.xml)

Now our SimpleTask will look like this:

Now we’ll have to pass both the file's path to SimpleTask.

Again export the plugin with new code changes and run the SimpleTask from the app. Now resource.xml will be added to app/src/main/res/values directory.

Pass the config from app to plugin:

To pass the file’s path to the plugin we’ll have to add an extension for the plugin. I have created a class PluginConfig for that and add as an extension to the plugin.

Add as an extension to the plugin

Now let's pass the plugin config from the app. For this add below lines of code in app’s build.gradle (module-level):

To retrieve this config in the plugin, our final SamplePlugin & SimpleTask class will look like this:

The below lines of code is to retrieve the value of inputFile in the plugin which being pass from our app’s build.gradle (module-level).

SimpleTask:

Task grouping:

We can group all the tasks in place by using the below code.

Now if we check the app project the tasks will be grouped like below:

Now if we run this task we’ll see the new files which will be added to the below path directory:

Thanks for reading this. In the next part, I’ll be talking about Unit & Functional testing of the plugin.

--

--