// Copyright 2017 the original author or authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.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.

[[custom_plugins]]
== Writing Custom Plugins

A Gradle plugin packages up reusable pieces of build logic, which can be used across many different projects and builds. Gradle allows you to implement your own plugins, so you can reuse your build logic, and share it with others.

You can implement a Gradle plugin in any language you like, provided the implementation ends up compiled as bytecode. In our examples, we are going to use Groovy as the implementation language. Groovy, Java or Kotlin are all good choices as the language to use to implement a plugin, as the Gradle API has been designed to work well with these languages. In general, a plugin implemented using Java or Kotlin, which are statically typed, will perform better than the same plugin implemented using Groovy.


[[sec:packaging_a_plugin]]
=== Packaging a plugin

There are several places where you can put the source for the plugin.

Build script::
You can include the source for the plugin directly in the build script. This has the benefit that the plugin is automatically compiled and included in the classpath of the build script without you having to do anything. However, the plugin is not visible outside the build script, and so you cannot reuse the plugin outside the build script it is defined in.

`buildSrc` project::
You can put the source for the plugin in the `__rootProjectDir__/buildSrc/src/main/groovy` directory. Gradle will take care of compiling and testing the plugin and making it available on the classpath of the build script. The plugin is visible to every build script used by the build. However, it is not visible outside the build, and so you cannot reuse the plugin outside the build it is defined in.
+
See <<organizing_build_logic>> for more details about the `buildSrc` project.

Standalone project::
You can create a separate project for your plugin. This project produces and publishes a JAR which you can then use in multiple builds and share with others. Generally, this JAR might include some plugins, or bundle several related task classes into a single library. Or some combination of the two.


In our examples, we will start with the plugin in the build script, to keep things simple. Then we will look at creating a standalone project.

[[sec:writing_a_simple_plugin]]
=== Writing a simple plugin

To create a Gradle plugin, you need to write a class that implements the api:org.gradle.api.Plugin[] interface. When the plugin is applied to a project, Gradle creates an instance of the plugin class and calls the instance's api:org.gradle.api.Plugin#apply[] method. The project object is passed as a parameter, which the plugin can use to configure the project however it needs to. The following sample contains a greeting plugin, which adds a `hello` task to the project.

++++
<sample id="customPlugin" dir="userguide/organizeBuildLogic/customPlugin" title="A custom plugin">
            <sourcefile file="build.gradle"/>
            <output args="-q hello"/>
        </sample>
++++

One thing to note is that a new instance of a plugin is created for each project it is applied to. Also note that the api:org.gradle.api.Plugin[] class is a generic type. This example has it receiving the api:org.gradle.api.Project[] type as a type parameter. A plugin can instead receive a parameter of type api:org.gradle.api.initialization.Settings[], in which case the plugin can be applied in a settings script, or a parameter of type api:org.gradle.api.invocation.Gradle[], in which case the plugin can be applied in an initialization script.

[[sec:getting_input_from_the_build]]
=== Making the plugin configurable

Most plugins need to obtain some configuration from the build script. One method for doing this is to use _extension objects_. The Gradle api:org.gradle.api.Project[] has an associated api:org.gradle.api.plugins.ExtensionContainer[] object that contains all the settings and properties for the plugins that have been applied to the project. You can provide configuration for your plugin by adding an extension object to this container. An extension object is simply a Java Bean compliant class. Groovy is a good language choice to implement an extension object because plain old Groovy objects contain all the getter and setter methods that a Java Bean requires. Java and Kotlin are other good choices.

Let's add a simple extension object to the project. Here we add a `greeting` extension object to the project, which allows you to configure the greeting.

++++
<sample id="customPluginWithConvention" dir="userguide/organizeBuildLogic/customPluginWithConvention" title="A custom plugin extension">
            <sourcefile file="build.gradle"/>
            <output args="-q hello"/>
        </sample>
++++

In this example, `GreetingPluginExtension` is a plain old Groovy object with a property called `message`. The extension object is added to the plugin list with the name `greeting`. This object then becomes available as a project property with the same name as the extension object.

Oftentimes, you have several related properties you need to specify on a single plugin. Gradle adds a configuration closure block for each extension object, so you can group settings together. The following example shows you how this works.

++++
<sample id="customPluginWithAdvancedConvention" dir="userguide/organizeBuildLogic/customPluginWithAdvancedConvention" title="A custom plugin with configuration closure">
            <sourcefile file="build.gradle"/>
            <output args="-q hello"/>
        </sample>
++++

In this example, several settings can be grouped together within the `greeting` closure. The name of the closure block in the build script (`greeting`) needs to match the extension object name. Then, when the closure is executed, the fields on the extension object will be mapped to the variables within the closure based on the standard Groovy closure delegate feature.

[[sec:working_with_files_in_custom_tasks_and_plugins]]
=== Working with files in custom tasks and plugins

When developing custom tasks and plugins, it's a good idea to be very flexible when accepting input configuration for file locations. To do this, you can leverage the api:org.gradle.api.Project#file(java.lang.Object)[] method to resolve values to files as late as possible.

++++
<sample id="lazyFileProperties" dir="userguide/tasks/customTaskWithFileProperty" title="Evaluating file properties lazily">
            <sourcefile file="build.gradle"/>
            <output args="-q sayGreeting"/>
        </sample>
++++

In this example, we configure the `greet` task `destination` property as a closure, which is evaluated with the api:org.gradle.api.Project#file(java.lang.Object)[] method to turn the return value of the closure into a `File` object at the last minute. You will notice that in the example above we specify the `greetingFile` property value after we have configured to use it for the task. This kind of lazy evaluation is a key benefit of accepting any value when setting a file property, then resolving that value when reading the property.

[[sec:mapping_extension_properties_to_task_properties]]
=== Mapping extension properties to task properties

Capturing user input from the build script through an extension and mapping it to input/output properties of a custom task is considered a best practice. The end user only interacts with the exposed DSL defined by the extension. The imperative logic is hidden in the plugin implementation.

The extension declaration in the build script as well as the mapping between extension properties and custom task properties occurs during Gradle's configuration phase of the build lifecycle. To avoid evaluation order issues, the actual value of a mapped property has to be resolved during the execution phase. For more information please see <<sec:build_phases>>. Gradle's API offers types for representing a property that should be lazily evaluated e.g. during execution time. Refer to <<lazy_configuration>> for more information.

The following demonstrates the usage of the type for mapping an extension property to a task property:

++++
<sample id="mapExtensionPropertiesToTaskProperties" dir="userguide/tasks/mapExtensionPropertiesToTaskProperties" includeLocation="true" title="Mapping extension properties to task properties">
            <sourcefile file="build.gradle"/>
            <output args="-q hello"/>
        </sample>
++++

[[sec:custom_plugins_standalone_project]]
=== A standalone project

Now we will move our plugin to a standalone project, so we can publish it and share it with others. This project is simply a Groovy project that produces a JAR containing the plugin classes. Here is a simple build script for the project. It applies the Groovy plugin, and adds the Gradle API as a compile-time dependency.

++++
<sample id="customPluginStandalone" dir="customPlugin/plugin" title="A build for a custom plugin" includeLocation="true">
            <sourcefile file="build.gradle" snippet="use-plugin"/>
        </sample>
++++

So how does Gradle find the api:org.gradle.api.Plugin[] implementation? The answer is you need to provide a properties file in the jar's `META-INF/gradle-plugins` directory that matches the id of your plugin.

++++
<sample id="customPluginStandalone" dir="customPlugin/plugin" title="Wiring for a custom plugin">
            <sourcefile file="src/main/resources/META-INF/gradle-plugins/org.samples.greeting.properties"/>
        </sample>
++++

Notice that the properties filename matches the plugin id and is placed in the resources folder, and that the `implementation-class` property identifies the api:org.gradle.api.Plugin[] implementation class.


[[sec:creating_a_plugin_id]]
==== Creating a plugin id

Plugin ids are fully qualified in a manner similar to Java packages (i.e. a reverse domain name). This helps to avoid collisions and provides a way to group plugins with similar ownership.

Your plugin id should be a combination of components that reflect namespace (a reasonable pointer to you or your organization) and the name of the plugin it provides. For example if you had a Github account named "foo" and your plugin was named "bar", a suitable plugin id might be `com.github.foo.bar`. Similarly, if the plugin was developed at the baz organization, the plugin id might be `org.baz.bar`.

Plugin ids should conform to the following:

* May contain any alphanumeric character, '.', and '-'.
* Must contain at least one '.' character separating the namespace from the name of the plugin.
* Conventionally use a lowercase reverse domain name convention for the namespace.
* Conventionally use only lowercase characters in the name.
* `org.gradle` and `com.gradleware` namespaces may not be used.
* Cannot start or end with a '.' character.
* Cannot contain consecutive '.' characters (i.e. '..').

Although there are conventional similarities between plugin ids and package names, package names are generally more detailed than is necessary for a plugin id. For instance, it might seem reasonable to add "gradle" as a component of your plugin id, but since plugin ids are only used for Gradle plugins, this would be superfluous. Generally, a namespace that identifies ownership and a name are all that are needed for a good plugin id.

[[sec:publishing_your_plugin]]
==== Publishing your plugin

If you are publishing your plugin internally for use within your organization, you can publish it like any other code artifact. See the <<publishing_ivy,ivy>> and <<publishing_maven,maven>> chapters on publishing artifacts.

If you are interested in publishing your plugin to be used by the wider Gradle community, you can publish it to the http://plugins.gradle.org[Gradle plugin portal]. This site provides the ability to search for and gather information about plugins contributed by the Gradle community. See the instructions http://plugins.gradle.org/docs/submit[here] on how to make your plugin available on this site.

[[sec:using_your_plugin_in_another_project]]
==== Using your plugin in another project

To use a plugin in a build script, you need to add the plugin classes to the build script's classpath. To do this, you use a "`buildscript { }`" block, as described in <<sec:applying_plugins_buildscript>>. The following example shows how you might do this when the JAR containing the plugin has been published to a local repository:

++++
<sample id="customPluginStandalone" dir="customPlugin/consumer" title="Using a custom plugin in another project">
                <test args="-p../plugin uploadArchives"/>
                <test args="hello"/>
                <sourcefile file="build.gradle" snippet="use-plugin"/>
            </sample>
++++

Alternatively, if your plugin is published to the plugin portal, you can use the incubating plugins DSL (see <<sec:plugins_block>>) to apply the plugin:

++++
<sample id="useCommunityPluginDSL" dir="plugins/dsl" title="Applying a community plugin with the plugins DSL">
                <sourcefile file="build.gradle" snippet="use-community-plugin"/>
            </sample>
++++


[[sec:writing_tests_for_your_plugin]]
==== Writing tests for your plugin

You can use the api:org.gradle.testfixtures.ProjectBuilder[] class to create api:org.gradle.api.Project[] instances to use when you test your plugin implementation.

++++
<sample id="customPluginStandalone" dir="customPlugin/plugin" title="Testing a custom plugin">
                <sourcefile file="src/test/groovy/org/gradle/GreetingPluginTest.groovy" snippet="test-plugin"/>
            </sample>
++++


[[sec:using_the_java_gradle_plugin_development_plugin]]
==== Using the Java Gradle Plugin development plugin

You can use the incubating <<java_gradle_plugin,Java Gradle Plugin development plugin>> to eliminate some of the boilerplate declarations in your build script and provide some basic validations of plugin metadata. This plugin will automatically apply the <<java_plugin,Java plugin>>, add the `gradleApi()` dependency to the compile configuration, and perform plugin metadata validations as part of the `jar` task execution.

++++
<sample id="useJavaGradlePluginPlugin" dir="javaGradlePlugin" title="Using the Java Gradle Plugin Development plugin">
                <sourcefile file="build.gradle" snippet="use-java-gradle-plugin-plugin"/>
            </sample>
++++

When publishing plugins to custom plugin repositories using the <<publishing_ivy,ivy>> or <<publishing_maven,maven>> publish plugins, the <<java_gradle_plugin,Java Gradle Plugin development plugin>> will also generate plugin marker artifacts named based on the plugin id which depend on the plugin's implementation artifact.

[[sec:implementing_a_dsl]]
=== Providing a configuration DSL for the plugin

As we saw above, you can use an extension object to provide configuration for your plugin. Using an extension object also extends the Gradle DSL to add a project property and DSL block for the plugin. An extension object is simply a regular object, and so you can provide DSL elements nested inside this block by adding properties and methods to the extension object.

Gradle provides several conveniences to help create a well-behaved DSL for your plugin.


[[sec:nested_dsl_elements]]
==== Nested DSL elements

When Gradle creates a task or extension object, Gradle _decorates_ the implementation class to mix in DSL support. To create a nested DSL element you can use the api:org.gradle.api.model.ObjectFactory[] type to create objects that are similarly decorated. These decorated objects can then be made visible to the DSL through properties and methods of the plugin's extension:

++++
<sample id="nestedDslElement" dir="userguide/organizeBuildLogic/customPluginWithNestedDsl" title="Nested DSL elements">
                <sourcefile file="build.gradle"/>
                <output args="-q hello"/>
            </sample>
++++

In this example, the plugin passes the project's `ObjectFactory` to the extension object through its constructor. The constructor uses this to create a nested object and makes this object available to the DSL through the `greeter` property.

[[sec:maintaining_multiple_domain_objects]]
==== Configuring a collection of objects

Gradle provides some utility classes for maintaining collections of objects, intended to work well with the Gradle DSL.

++++
<sample id="domainObjectContainer" dir="userguide/organizeBuildLogic/customPluginWithDomainObjectContainer" title="Managing a collection of objects">
                <sourcefile file="build.gradle"/>
                <output args="-q books"/>
            </sample>
++++

The api:org.gradle.api.Project#container(java.lang.Class)[] methods create instances of api:org.gradle.api.NamedDomainObjectContainer[], that have many useful methods for managing and configuring the objects. In order to use a type with any of the `project.container` methods, it MUST expose a property named "`name`" as the unique, and constant, name for the object. The `project.container(Class)` variant of the container method creates new instances by attempting to invoke the constructor of the class that takes a single string argument, which is the desired name of the object. See the above link for `project.container` method variants that allow custom instantiation strategies.
