// Copyright (C) 2023 Gradle, Inc.
//
// Licensed under the Creative Commons Attribution-Noncommercial-ShareAlike 4.0 International License.;
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      https://creativecommons.org/licenses/by-nc-sa/4.0/
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

[[implemention_plugins]]
= 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,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/kotlin/java-gradle-plugin",files="build.gradle.kts[tags=use-and-configure-plugin]"]
include::sample[dir="snippets/plugins/customPlugin/groovy/java-gradle-plugin",files="build.gradle[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#custom_tasks,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[tags=snippet]
----

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/kotlin",files="build.gradle.kts[tags=direct-task-register]"]
include::sample[dir="snippets/developingPlugins/customTask/groovy",files="build.gradle[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 <<incremental_build.adoc#incremental_build,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[tags=snippet]
----

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 `validatePlugins` 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/kotlin",files="build-flat.gradle.kts[]"]
include::sample[dir="snippets/developingPlugins/pluginExtension/groovy",files="build-flat.gradle[]"]
====

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/kotlin",files="build.gradle.kts[]"]
include::sample[dir="snippets/developingPlugins/pluginExtension/groovy",files="build.gradle[]"]
====

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[tags=snippet]
----

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[tags=snippet]
----

[[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/kotlin",files="build.gradle.kts[tags=plugin-extension]"]
include::sample[dir="snippets/developingPlugins/customTask/groovy",files="build.gradle[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 <<lazy_configuration#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[tags=snippet]
----

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[tags=snippet]
----

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[tags=snippet]
----

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/kotlin",files="build.gradle.kts[]"]
include::sample[dir="snippets/developingPlugins/namedDomainObjectContainer/groovy",files="build.gradle[]"]
====

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[tags=snippet]
----

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[tags=snippet]
----

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[tags=snippet]
----

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[tags=snippet]
----

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[tags=snippet]
----

== Reacting to build features

Plugins can access the status of build features in the build.
The link:{javadocPath}/org/gradle/api/configuration/BuildFeatures.html[Build Features API] allows checking whether the user requested a particular Gradle feature and if it is active in the current build.
An example of a build feature is the <<configuration_cache.adoc#config_cache,configuration cache>>.

There are two main use cases:

- Using the status of build features in reports or statistics.
- Incrementally adopting experimental Gradle features by disabling incompatible plugin functionality.

Below is an example of a plugin that utilizes both of the cases.

.Reacting to build features
[source,java]
----
include::{snippetsPath}/developingPlugins/reactingToBuildFeatures/groovy/buildSrc/src/main/java/MyPlugin.java[tags=my-plugin]
----
<1> The `BuildFeatures` service can be injected into plugins, tasks, and other managed types.
<2> Accessing the `requested` status of a feature for reporting.
<3> Using the `active` status of a feature to disable incompatible functionality.

=== Build feature properties

The status properties of a `BuildFeature` are represented with `Provider<Boolean>` types.

The link:{javadocPath}/org/gradle/api/configuration/BuildFeature.html#getRequested--[`BuildFeature.getRequested()`] status of a build feature determines if the user requested to enable or disable the feature.
If the user did neither, then the *value of the provider is undefined*.

When the `requested` provider value is:

- not present (undefined) -- the user neither opted in nor opted out from using the feature;
- `true` -- the user opted in for using the feature, e.g., using a build option;
- `false` -- the user opted out from using the feature, e.g., by setting a Gradle property to `false`.

The link:{javadocPath}/org/gradle/api/configuration/BuildFeature.html#getActive--[`BuildFeature.getActive()`] status of a build feature is always defined.
It represents the effective state of the feature in the build.

When the `active` provider value is:

- `true` -- the feature _may_ affect the build behavior in a way specific to the feature;
- `false` -- the feature will not affect the build behavior.

Note that the `active` status does not depend on the `requested` status.
Even if the user requested a feature, it may still not be active due to other build options used in the build.
Gradle can also activate a feature by default, even if the user did not specify a preference.

== 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#declaring-dependencies,assigning those external dependencies with dependency coordinates>>.

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

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

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/kotlin",files="build.gradle.kts[]"]
include::sample[dir="snippets/developingPlugins/defaultDependency/groovy",files="build.gradle[]"]
====

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/kotlin",files="buildSrc/build.gradle.kts[]"]
include::sample[dir="snippets/developingPlugins/pluginIdentifier/groovy",files="buildSrc/build.gradle[]"]
====

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.

[[plugin-with-variants]]
== Providing multiple variants of a plugin for different Gradle versions

NOTE: The support for multi-variant plugins currently requires you to use the raw <<variant_model.adoc#understanding-variant-selection,variant aware dependency management>> APIs of Gradle.
More conveniences around this may be provided in the future.

Currently, the most convenient way to configure additional plugin variants is to use <<feature_variants.adoc#feature_variants,feature variants>>, a concept available in all Gradle projects that apply one of the Java plugins.
As described in the <<feature_variants.adoc#feature_variants,documentation>>, there are several options to design feature variants.
They may be bundled inside the same Jar, or each variant may come with its own Jar.
Here we show how each plugin variant is developed in isolation.
That is, in a separate source set that is compiled separately and packaged in a separate Jar.
Other setups are possible though.

The following sample demonstrates how to add a variant that is compatible with Gradle 7+ while the "main" variant is compatible with older versions.
Note that only Gradle versions 7 or higher can be explicitly targeted by a variant, as support for this was only added in Gradle 7.

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

First, we declare a separate _source set_, and a _feature variant_ based on that, for our Gradle7 plugin variant.
We need to do some specific wiring to turn the feature into a proper Gradle plugin variant:

<1> Assign the <<component_capabilities.adoc#declaring-component-capabilities,implicit capability that corresponds to the components GAV>> to the variant.
<2> Assign the <<variant_attributes.adoc#sub:gradle_plugins_default_attributes,Gradle API version attribute>> to all <<declaring_dependencies.adoc#sec:resolvable-consumable-configs,consumable configurations>> of our Gradle7 variant. This information is used by Gradle to determine which variant to select during plugin resolution.
<3> Configure the `processGradle7Resources` task to make sure the plugin descriptor file is added to the Gradle7 variant Jar.
<4> Add a dependency to the `gradleApi()` for our new variant so that the API is visible during compilation time.

Note that there is currently no convenient way to access the API of other Gradle versions as the one you are building the plugin with.
Ideally, every variant should be able to declare a dependency to the API of the minimal Gradle version it supports.
This will be improved in the future.

The above snippet assumes that all variants of your plugin have the plugin class at the same location.
That is, if you followed this chapter and your plugin class is `org.example.GreetingPlugin`, you need to create a second variant of that class in `src/gradle7/java/org/example`.

== Using version-specific variants of multi-variant plugins

Given a dependency on a multi-variant plugin, Gradle will automatically choose its variant that best matches the current Gradle version when it resolves any of:

* plugins specified in the <<plugins.adoc#sec:plugins_block,`plugins {}` block>>;
* `buildscript` classpath dependencies;
* dependencies in the root project of the <<sharing_build_logic_between_subprojects.adoc#sec:using_buildsrc,build source (`buildSrc`)>> that appear on the compile or runtime classpath;
* dependencies in a project that applies the <<java_gradle_plugin.adoc#java_gradle_plugin,Java Gradle Plugin Development plugin>> or the <<kotlin_dsl.adoc#sec:kotlin-dsl_plugin,Kotlin DSL plugin>>, appearing on the compile or runtime classpath.

The best matching variant is the variant that targets the highest Gradle API version not exceeding the current build's Gradle version.

In all other cases, a plugin variant that does not specify the supported Gradle API version is preferred, if such a variant is present.

In projects that use plugins as dependencies, it is possible to request the variants of plugin dependencies that support a different Gradle version.
This allows a multi-variant plugin that depends on other plugins to access their APIs which are exclusively provided in their version-specific variants.

This snippet makes the <<#plugin-with-variants,plugin variant `gradle7` defined above>> consume the matching variants of its dependencies on other multi-variant plugins.

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

== Reporting problems

Plugins can report problems through Gradle's problem-reporting APIs.
The APIs report rich, structured information about problems happening during the build.
This information can be used by different user interfaces such as Gradle's console output, Build Scans, or IDEs to communicate problems to the user in the most appropriate way.

The following example shows an issue reported from a plugin:

====
include::sample[dir="snippets/developingPlugins/problemReporting/kotlin/buildSrc/src/main/java/org/myorg",files="ProblemReportingPlugin.java[tags=snippet]"]
====

<1> The `Problem` service is injected into the plugin.
<2> A problem reporter, is created for the plugin. While the namespace is up to the plugin author, it is recommended to use the plugin ID.
<3> A problem is reported. This problem is recoverable so that the build will continue.

For a full example, see our link:../samples/sample_problems_api_usage.html[end-to-end sample].

=== Problem building

When reporting a problem, a wide variety of information can be provided.
The link:{javaDocPath}/org/gradle/api/problems/ProblemSpec.html[ProblemSpec] describes all the information that can be provided.

=== Reporting problems

When it comes to reporting problems, we support three different modes:

- link:{javadocPath}/org/gradle/api/problems/ProblemReporter.html#reporting-org.gradle.api.Action-[Reporting] a problem is used for reporting problems that are recoverable, and the build should continue.
- link:{javadocPath}/org/gradle/api/problems/ProblemReporter.html#throwing-org.gradle.api.Action-[Throwing] a problem is used for reporting problems that are not recoverable, and the build should fail.
- link:{javadocPath}/org/gradle/api/problems/ProblemReporter.html#rethrowing-java.lang.RuntimeException-org.gradle.api.Action-[Rethrowing] a problem is used to wrap an already thrown exception. Otherwise, the behavior is the same as `Throwing`.

See the link:{javaDocPath}/org/gradle/api/problems/ProblemReporter.html[ProblemReporter] documentation for more details.

=== Problem aggregation

When reporting problems, Gradle will aggregate similar problems when it sends them through the Tooling API based on the problem's category label.

 - When a problem is reported, the _first_ occurrence is going to be reported as a link:{javaDocPath}/org/gradle/tooling/events/problems/ProblemDescriptor.html[ProblemDescriptor], containing the complete information about the problem.
 - Any subsequent occurrences of the same problem will be reported as a link:{javaDocPath}org/gradle/tooling/events/problems/ProblemAggregationDescriptor.html[ProblemAggregationDescriptor]. This descriptor will arrive at the _end_ of the build and contain the number of occurrences of the problem.
 - If for any bucket (i.e., category and label pairing), the number of collected occurrences is greater than 10.000, then it will be sent immediately instead of at the end of the build.
