A plugin you write
A convention script is a build script with an id. A plugin is a class, and a class can hold a task, read a property and be tested. This lesson writes one in Groovy, gives it an id in buildSrc, applies it to a project and lints its source.
The plugin class
buildSrc/build.gradle
plugins {
id 'groovy'
id 'java-gradle-plugin'
}
repositories {
mavenLocal()
}
dependencies {
implementation localGroovy()
}
buildSrc/src/main/groovy/com/example/GreetingPlugin.groovy
package com.example
import org.gradle.api.Plugin
import org.gradle.api.Project
class GreetingPlugin implements Plugin<Project> {
@Override
void apply(Project project) {
project.tasks.register('greeting') {
group = 'shop'
description = 'Prints the name of the project'
doLast {
println "hello from ${project.name}"
}
}
}
}
apply is the whole interface: Gradle hands the plugin a project, and the plugin does to it what a build script would do. The task is registered lazily, so a build that never asks for greeting never creates it.
Registering it
The java-gradle-plugin block gives the class an id and writes the descriptor that makes the id resolvable. The file below is the same buildSrc/build.gradle with that block:
buildSrc/build.gradle
plugins {
id 'groovy'
id 'java-gradle-plugin'
}
repositories {
mavenLocal()
}
dependencies {
implementation localGroovy()
}
gradlePlugin {
plugins {
greeting {
id = 'shop.greeting'
implementationClass = 'com.example.GreetingPlugin'
}
}
}
Applying it
settings.gradle
rootProject.name = 'shop'
include 'app'
app/build.gradle
plugins {
id 'shop.greeting'
}
gradle greeting
gradle -q :app:greeting --console=plain --offline --no-daemon
hello from app
The task exists because the project applied the plugin, and it prints the name of the project it was applied to. The same plugin applied to three projects gives three tasks, and the block that registers it is written once.
CodeNarc on the plugin
Groovy code deserves a linter like any other, and CodeNarc is the one this repository carries. The checker of these lessons runs it over every Groovy source of a page, so the class above was linted with the code of the page:
python3 container/tools/course_check/code_blocks.py --lang groovy --lint container/src/dvps/gradle/048_plugins_you_write.php
Zero violations, and every rule of the default set was checked, because CodeNarc reports nothing when it finds nothing. A violation would be printed with the file, the line and the name of the rule, and the page would have to show it or fix the code; that is how the Groovy lesson pages of this site are kept clean.
Related
- Convention plugins versus subprojects: the script form of shared build logic.
- Write a task: the register call inside the plugin.
- Gradle in CI and Docker: where a published plugin is used from.
Article author: Arthur Isaev