Write a custom Gradle Plugin (Part 2)
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.
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:
- Input file path
- Output file path
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
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
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
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.
Developing Custom Gradle Task Types
Gradle supports two types of tasks. One such type is the simple task, where you define the task with an action closure…
Developing Custom Gradle Types
There are several different kinds of "add-ons" to Gradle that you can develop, such as plugins, tasks, project…