= Implementing Gradle plugins

Writing plugin code is a routine activity for advanced build authors.
The activity usually involves writing the plugin implementation, creating custom task type for executing desired functionality and making the runtime behavior configurable for the end user by exposing a declarative and expressive DSL.
In this section you will learn established practices to make you a better plugin developer and how to make a plugin as accessible and useful for consumers as possible.

This section assumes you have:

- Basic understanding of software engineering practices
- Knowledge of Gradle fundamentals like project organization, task creation and configuration as well as the Gradle build lifecycle
- Working knowledge in writing Java code

[[plugin-development-plugin]]
== Using the Plugin Development plugin for writing plugins

Setting up a Gradle plugin project should require as little boilerplate code as possible.
The <<java_gradle_plugin.adoc#,Java Gradle Plugin Development plugin>> provides aid in this concern.
To get started add the following code to your _build.gradle_ file:

====
include::sample[dir="snippets/plugins/customPlugin/groovy/java-gradle-plugin",files="build.gradle[tags=use-and-configure-plugin]"]
include::sample[dir="snippets/plugins/customPlugin/kotlin/java-gradle-plugin",files="build.gradle.kts[tags=use-and-configure-plugin]"]
====

By applying the plugin, necessary plugins are applied and relevant dependencies are added.
It also helps with validating the plugin metadata before publishing the binary artifact to the Gradle plugin portal.
Every plugin project should apply this plugin.

[[writing-and-using-custom-task-types]]
== Prefer writing and using custom task types

Gradle tasks can be defined as ad-hoc tasks, simple task definitions of type `DefaultTask` with one or many actions, or as <<custom_tasks.adoc#,enhanced tasks>>, the ones that use a custom task type and expose its configurability with the help of properties.
Generally speaking, custom tasks provide the means for reusability, maintainability, configurability and testability.
The same principles hold true when providing tasks as part of plugins.
Always prefer custom task types over ad-hoc tasks.
Consumers of your plugin will also have the chance to reuse the existing task type if they want to add more tasks to the build script.

Let’s say you implemented a plugin that resolves the latest version of a dependency in a binary repository by making HTTP calls by providing a custom task type.
The custom task is provided by a plugin that takes care of communicating via HTTP and processing the response in machine-readable format like XML or JSON.

.LatestArtifactVersion.java
[source,java]
----
include::{snippetsPath}/developingPlugins/customTask/groovy/buildSrc/src/main/java/org/myorg/LatestArtifactVersion.java[]
----

The end user of the task can now easily create multiple tasks of that type with different configuration.
All the imperative, potentially complex logic is completely hidden in the custom task implementation.

====
include::sample[dir="snippets/developingPlugins/customTask/groovy",files="build.gradle[tags=direct-task-register]"]
include::sample[dir="snippets/developingPlugins/customTask/kotlin",files="build.gradle.kts[tags=direct-task-register]"]
====

== Benefiting from incremental tasks

Gradle uses declared inputs and outputs to determine if a task is up-to-date and needs to perform any work.
If none of the inputs or outputs have changed, Gradle can skip that task.
Gradle calls this mechanism incremental build support.
The advantage of <<more_about_tasks.adoc#sec:up_to_date_checks,incremental build support>> is that it can significantly improve the performance of a build.

It’s very common for Gradle plugins to introduce custom task types.
As a plugin author that means that you’ll have to annotate all properties of a task with input or output annotations.
It’s highly recommended to equip every task with the information to run up-to-date checking.
Remember: for up-to-date checking to work properly a task needs to define both inputs and outputs.

Let’s consider the following sample task for illustration.
The task generates a given number of files in an output directory.
The text written to those files is provided by a String property.

.Generate.java
[source,java]
----
include::{snippetsPath}/developingPlugins/incrementalTask/groovy/buildSrc/src/main/java/Generate.java[]
----

The first section of this guide talks about the <<plugin-development-plugin,Plugin Development plugin>>.
As an added benefit of applying the plugin to your project, the task `validateTaskProperties` automatically checks for an existing input/output annotation for every public property defined in a custom task type implementation.

[[modeling_dsl_like_apis]]
== Modeling DSL-like APIs

DSLs exposed by plugins should be readable and easy to understand.
For illustration let's consider the following extension provided by a plugin.
In its current form it offers a "flat" list of properties for configuring the creation of a web site.

====
include::sample[dir="snippets/developingPlugins/pluginExtension/groovy",files="build-flat.gradle[]"]
include::sample[dir="snippets/developingPlugins/pluginExtension/kotlin",files="build-flat.gradle.kts[]"]
====

As the number of exposed properties grows, you might want to introduce a nested, more expressive structure.
The following code snippet adds a new configuration block named `customData` as part of the extension.
You might have noticed that it provides a stronger indication of what those properties mean.

====
include::sample[dir="snippets/developingPlugins/pluginExtension/groovy",files="build.gradle[]"]
include::sample[dir="snippets/developingPlugins/pluginExtension/kotlin",files="build.gradle.kts[]"]
====

It's fairly easy to implement the backing objects of such an extension.
First of all, you'll need to introduce a new data object for managing the properties `websiteUrl` and `vcsUrl`.

.CustomData.java
[source,java]
----
include::{snippetsPath}/developingPlugins/pluginExtension/groovy/buildSrc/src/main/java/org/myorg/CustomData.java[]
----

In the extension, you'll need to create an instance of the `CustomData` class and a method that can delegate the captured values to the data instance.
To configure underlying data objects define a parameter of type link:{javadocPath}/org/gradle/api/Action.html[Action].
The following example demonstrates the use of `Action` in an extension definition.

.SiteExtension.java
[source,java]
----
include::{snippetsPath}/developingPlugins/pluginExtension/groovy/buildSrc/src/main/java/org/myorg/SiteExtension.java[]
----

=== Extensions vs. Conventions

Some of the Gradle core plugins expose configurability with the help of a so-called link:{javadocPath}/org/gradle/api/plugins/Convention.html[Convention].
`Convention` is the preceding concept of an extension and serves a similar purpose.
The main difference between both concepts is that `Convention` does not allow for defining a namespace to model a DSL-like API making it hard to distinguish from the Gradle core DSL.
Please avoid using the `Convention` concept when writing new plugins.
The long term plan is to migrate all Gradle core plugins to use extensions and remove the `Convention` concept altogether.

[[capturing_user_input_to_configure_plugin_runtime_behavior]]
== Capturing user input to configure plugin runtime behavior

Plugins often times come with default conventions that make sensible assumptions about the consuming project.
The Java plugin, for example, searches for Java source files in the directory `src/main/java`.
Default conventions are helpful to streamline project layouts but fall short when dealing with custom project structures, legacy project requirements or a different user preference.

Plugins should expose a way to reconfigure the default runtime behavior.
The section <<writing-and-using-custom-task-types,Prefer writing and using custom task types>> describes one way to achieve configurability: by declaring setter methods for task properties.
The more sophisticated solution to the problem is to expose an extension.
An extension captures user input through a custom DSL that fully blends into the DSL exposed by Gradle core.

The following example applies a plugin that exposes an extension with the name `binaryRepo` to capture a server URL:

====
include::sample[dir="snippets/developingPlugins/customTask/groovy",files="build.gradle[tags=plugin-extension]"]
include::sample[dir="snippets/developingPlugins/customTask/kotlin",files="build.gradle.kts[tags=plugin-extension]"]
====

Let's assume that you'll also want to do something with the value of `serverUrl` once captured.
In many cases the exposed extension property is directly mapped to a task property that actually uses the value when performing work.
To avoid evaluation order problems you should use link:{user-manual}lazy_configuration.html#lazy_properties[the public API `Property`] which was introduced in Gradle 4.0.

Let's have a look at the internals of the plugin `BinaryRepositoryVersionPlugin` to give you a better idea.
The plugin creates the extension of type `BinaryRepositoryExtension` and maps the extension property `serverUrl` to the task property `serverUrl.`

.BinaryRepositoryVersionPlugin.java
[source,java]
----
include::{snippetsPath}/developingPlugins/customTask/groovy/buildSrc/src/main/java/org/myorg/BinaryRepositoryVersionPlugin.java[]
----

Instead of using a plain `String` type, the extension defines the properties `coordinates` and `serverUrl` with type `Property<String>`.
The abstract getters for the properties are automatically initialized by Gradle.
The values of a property can then be changed on the property object obtained through the corresponding getter method.

NOTE: The Gradle classloader automatically injects setter methods alongside all getter methods with the return type `Property`.
It allows developers to simplify code like `obj.prop.set 'foo'` to `obj.prop = 'foo'` in the Groovy DSL.

.BinaryRepositoryExtension.java
[source,java]
----
include::{snippetsPath}/developingPlugins/customTask/groovy/buildSrc/src/main/java/org/myorg/BinaryRepositoryExtension.java[]
----

The task property also defines the `serverUrl` with type `Property`.
It allows for mapping the state of the property without actually accessing its value until needed for processing - that is in the task action.

.LatestArtifactVersion.java
[source,java]
----
include::{snippetsPath}/developingPlugins/customTask/groovy/buildSrc/src/main/java/org/myorg/LatestArtifactVersion.java[]
----

NOTE: We encourage plugin developers to migrate their plugins to the public property API as soon as possible.
Plugins that are not based on Gradle 4.0 yet may continue to use the internal "convention mapping" API.
Please be aware that the "convention mapping" API is undocumented and might be removed with later versions of Gradle.

== Declaring a DSL configuration container

Sometimes you might want to expose a way for users to define multiple, named data objects of the same type.
Let's consider the following build script for illustration purposes.

====
include::sample[dir="snippets/developingPlugins/namedDomainObjectContainer/groovy",files="build.gradle[]"]
include::sample[dir="snippets/developingPlugins/namedDomainObjectContainer/kotlin",files="build.gradle.kts[]"]
====

The DSL exposed by the plugin exposes a _container_ for defining a set of environments.
Each environment configured by the user has an arbitrary but declarative name and is represented with its own DSL configuration block.
The example above instantiates a development, staging and production environment including its respective URL.

Obviously, each of these environments needs to have a data representation in code to capture the values.
The name of an environment is immutable and can be passed in as constructor parameter.
At the moment the only other parameter stored by the data object is an URL.
The POJO `ServerEnvironment` shown below fulfills those requirements.

.ServerEnvironment.java
[source,java]
----
include::{snippetsPath}/developingPlugins/namedDomainObjectContainer/groovy/buildSrc/src/main/java/org/myorg/ServerEnvironment.java[]
----

Gradle exposes the factory method
link:{javadocPath}/org/gradle/api/model/ObjectFactory.html#domainObjectContainer-java.lang.Class-org.gradle.api.NamedDomainObjectFactory-[ObjectFactory.domainObjectContainer(Class, NamedDomainObjectFactory)]
to create a container of data objects.
The parameter the method takes is the class representing the data.
The created instance of type link:{javadocPath}/org/gradle/api/NamedDomainObjectContainer.html[NamedDomainObjectContainer] can be exposed to the end user by adding it to the extension container with a specific name.

.ServerEnvironmentPlugin.java
[source,java]
----
include::{snippetsPath}/developingPlugins/namedDomainObjectContainer/groovy/buildSrc/src/main/java/org/myorg/ServerEnvironmentPlugin.java[]
----

It's very common for a plugin to post-process the captured values within the plugin implementation e.g. to configure tasks.
In the example above, a deployment task is created dynamically for every environment that was configured by the user.

== Reacting to plugins

Configuring the runtime behavior of existing plugins and tasks in a build is a common pattern in Gradle plugin implementations.
For example a plugin could assume that it is applied to a Java-based project and automatically reconfigure the standard source directory.

[[convention-api-usage-example]]
.InhouseStrongOpinionConventionJavaPlugin.java
[source,java]
----
include::{snippetsPath}/developingPlugins/reactingToPlugins/groovy/buildSrc/src/main/java/InhouseStrongOpinionConventionJavaPlugin.java[]
----

The drawback to this approach is that it automatically forces the project to apply the Java plugin and therefore imposes a strong opinion on it.
In practice, the project applying the plugin might not even deal with Java code.
Instead of automatically applying the Java plugin the plugin could just react to the fact that the consuming project applies the Java plugin.
Only if that is the case then certain configuration is applied.

.InhouseConventionJavaPlugin.java
[source,java]
----
include::{snippetsPath}/developingPlugins/reactingToPlugins/groovy/buildSrc/src/main/java/InhouseConventionJavaPlugin.java[]
----

Reacting to plugins should be preferred over blindly applying other plugins if there is not a good reason for assuming that the consuming project has the expected setup.
The same concept applies to task types.

.InhouseConventionWarPlugin.java
[source,java]
----
include::{snippetsPath}/developingPlugins/reactingToPlugins/groovy/buildSrc/src/main/java/InhouseConventionWarPlugin.java[]
----

== Providing default dependencies for plugins

The implementation of a plugin sometimes requires the use of an external dependency.
You might want to automatically download an artifact using Gradle’s dependency management mechanism and later use it in the action of a task type declared in the plugin.
Optimally, the plugin implementation doesn’t need to ask the user for the coordinates of that dependency - it can simply predefine a sensible default version.

Let’s have a look at an example.
You wrote a plugin that downloads files containing data for further processing.
The plugin implementation declares a custom configuration that allows for <<declaring_dependencies.adoc#,assigning those external dependencies with dependency coordinates>>.

.DataProcessingPlugin.java
[source,java]
----
include::{snippetsPath}/developingPlugins/defaultDependency/groovy/buildSrc/src/main/java/org/myorg/DataProcessingPlugin.java[]
----

.DataProcessing.java
[source,java]
----
include::{snippetsPath}/developingPlugins/defaultDependency/groovy/buildSrc/src/main/java/org/myorg/DataProcessing.java[]
----

Now, this approach is very convenient for the end user as there’s no need to actively declare a dependency.
The plugin already provides all the knowledge about this implementation detail.
But what if the user would like to redefine the default dependency.
No problem...the plugin also exposes the custom configuration that can be used to assign a different dependency.
Effectively, the default dependency is overwritten.

====
include::sample[dir="snippets/developingPlugins/defaultDependency/groovy",files="build.gradle[]"]
include::sample[dir="snippets/developingPlugins/defaultDependency/kotlin",files="build.gradle.kts[]"]
====

You will find that this pattern works well for tasks that require an external dependency when the action of the task is actually executed.
You can go further and abstract the version to be used for the external dependency by exposing an extension property (e.g.
`toolVersion` in link:{groovyDslPath}/org.gradle.testing.jacoco.plugins.JacocoPluginExtension.html[the JaCoCo plugin]).

== Assigning appropriate plugin identifiers

A descriptive plugin identifier makes it easy for consumers to apply the plugin to a project.
The ID should reflect the purpose of the plugin with a single term.
Additionally, a domain name should be added to avoid conflicts between other plugins with similar functionality.
In the previous sections, dependencies shown in code examples use the group ID `org.myorg`.
We could use the same identifier as domain name.

When publishing multiple plugins as part of a single JAR artifact the same naming conventions should apply.
This serves as a nice way to group related plugins together.
There’s no limitation to the number of plugins that can be registered by identifier.
For illustration, the Gradle Android plugin defines two different plugins.

The identifiers for plugins written as a class should be defined in the build script of the project containing the plugin classes.
For this, the `java-gradle-plugin` needs to be applied.

====
include::sample[dir="snippets/developingPlugins/pluginIdentifier/groovy",files="buildSrc/build.gradle[]"]
include::sample[dir="snippets/developingPlugins/pluginIdentifier/kotlin",files="buildSrc/build.gradle.kts[]"]
====

Note that identifiers for <<custom_plugins.adoc#sec:precompiled_plugins,precompiled script plugins>> are automatically registered based on the file name of the script plugin.
