Series of articles look here

Gradle gets started and builds the environment

Gradle is an introduction to meta-programming

Gradle: Groovy syntax for getting started

Gradle introduction and lifecycle

Gradle core project

How to create a Gradle plugin by yourself

What is a Transform in Gradle?

preface

We have put in front of the gradle some groovy syntax, and commonly used in the project and task is introduced again, so we through their lu a plug-in. Just to reinforce what we’ve already done.

What plug-ins do

First of all, we need to understand the functions of plug-ins, mainly as follows:

  • Add tasks to a project to test, compile, and package the project.

  • Add dependencies to a project, which can be used to configure dependencies needed during the project build process.

  • You can add new extension attributes and methods to the existing object types in the Project to facilitate the configuration and construction optimization of the Project. For example, Android {} in the Android Project construction is an extension added by the AndroidGradle plug-in for the Project object.

Classification of plug-ins

There are two main types of plug-ins: scripted plug-ins and binary plug-ins.

Script plug-in

Script plug-ins are similar to those mentioned in the previous article. Create a new config.gradle and pass it

apply from:".. /config.gradle"Copy the code

For example, you can define some tool-like methods and the version numbers used by each dependency in a single Gradle file, so that you can call and manage the version numbers of each dependency in a unified manner.

Binary plug-in

Binary plug-in general through the Plugin interface, to implement the apply method. Generics in this method refer to objects to which this Plugin can be applied, typically to Project objects. Binary plug-ins generally come in three ways:

  • Build script: Directly implements the Plugin interface in gradle script files and applies it
  • BuildSrc Project: buildSrc is the default directory where Gradle configures custom plug-ins in the project. Rarely used in general
  • Standalone project: Standalone project, compiled for internal and external use

The first two application scenarios are very few, here is no more introduction, want to know their own Baidu ~, we focus on the last one.

Start a Standalone project

Since this is a standalone project, first we need to create a new moudle. The entire creation procedure is as follows:

  • Create a new moudle. The type can be Android. Then delete the directory clean, leaving only the build.gradle file and empty the build.gradle inside.

  • Create a SRC /main/groovy directory in moudle and create a new package name. Create a new resources/ meta-INF /gradle-plugins directory in the main directory and write a.properties file with the same name as the plugin ID. Gradle can then find the plugin implementation.

Modify the properties file:

implementation-class=com.xxxx.plugin.MyGradlePlugin
Copy the code

Modify the build.gralde file as follows:

apply plugin: 'java-gradle-plugin' apply plugin: 'kotlin' apply plugin: 'groovy' apply plugin: 'maven' apply plugin: Maven-publish 'repositories {mavenCentral()} group =' publishing '{repositories {mavenCentral()} group =' publishing '{repositories}  maven { url = uri("$rootDir/repo") } } publications { maven(MavenPublication) { from components.java } } } dependencies  { implementation fileTree(dir: "libs", include: ["*.jar"]) implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" //gradle sdk implementation gradleApi() //groovy sdk implementation localGroovy() }Copy the code

We rely on groovy-related plug-ins so that we can create Groovy files. Maven is relied on for subsequent local uploads and debugging.

Now let’s write a simple one to try it out. Create a plugin in your directory:

class MyGradlePlugin implements Plugin<Project> { @Override void apply(Project project) { project.task('MyGradlePlugin')  { doLast { println('task in MyGradlePlugin') } } } }Copy the code

Then go to Gradle -> myGradlePlugin -> Publishing -> Publish. When the execution is complete, the REPO repository is generated in the project root directory. This is the URL you configured in build.gradle.

Now that local Maven has been generated, it’s time for our reference. We reference our local Maven at build.gradle in the root directory. The following is an example:

    repositories {
        google()
        jcenter()
        maven {
            url = uri("$rootDir/repo")
        }
    }
Copy the code

After the local Maven dependency is complete, we will use the root directory to refer to our plugin dependencies:

apply plugin: "myGradlePlugin" dependencies { ... The classpath 'com. XXXX. The plugin: myGradlePlugin: 1.0.0'... }Copy the code

And then we sync. There we go. So how do we validate our own plugin? At the command line we type:

./gradlew MyGradlePlugin
Copy the code

Then you’ll see that it prints:

Task:MyGradlePlugin
task in MyGradlePlugin
Copy the code

Oh, my God! Oh, my God! It worked!

To make it harder, we need to dynamically configure some properties in build.gradle, and the plugin can read these dynamically configured properties. Since you need to configure the properties dynamically, let’s define the properties that need to be configured dynamically and create an Extension. Specific examples are as follows:

class MyGradlePluginExtension {
    String versionName
    String versionCode
    String versionInfo

    @Override
    String toString() {
        return "versionName = $versionName , versionCode = $versionCode , versionInfo = $versionInfo"
    }
}
Copy the code

We define version properties, such as version number, version name, version information, and so on. Now that we’ve defined it, how do we read these properties. Modify our plugin:

class MyGradlePlugin implements Plugin<Project> {

    @Override
    void apply(Project project) {
        project.extensions.create("MyGradlePluginExtension", MyGradlePluginExtension.class)
        project.task('MyGradlePluginExtension') {
            doLast {
                MyGradlePluginExtension releaseInfo = project.MyGradlePluginExtension
                println releaseInfo
            }
        }

    }
}
Copy the code

After modifying the code, you can see the logic as follows: create a MyGradlePluginExtension and define a task as MyGradlePluginExtension. That is, when we execute the Task of MyGradlePluginExtension, we read the properties of the Project MyGradlePluginExtension and output them.

Re-upload Maven, which I won’t talk about here, as mentioned earlier, and add the following code to the root directory:

MyGradlePluginExtension {versionName = 1.0 versionCode = 1.0versionInfo = "Test first version"}Copy the code

We then execute the task and see the panel output as follows:

Task :MyGradlePluginExtension versionName = 1.0, versionCode = 1.0, versionInfo = Test the first versionCopy the code

The dynamic configuration takes effect

conclusion

This section focuses on Gradle plugin classification and how to write a plugin and apply it. For more customizations, see the official documentation: Writing Custom Plug-ins

This post was first posted on my blog: How to create a Gradle plugin yourself

For more articles, please pay attention to my official number:Code the farmers work