<chapter id="custom_plugins">
    <title>Writing Custom Plugins</title>

    <para>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 custom plugins, so you can reuse your
        build logic, and share it with others.
    </para>

    <para>
        You can implement a custom plugin in any language you like, provided the implementation ends up compiled as
        bytecode. For the examples here, we are going to use Groovy as the implementation language. You could use
        Java or Scala instead, if you want.
    </para>

    <section>
        <title>Packaging a plugin</title>
        <para>There are several places where you can put the source for the plugin.
        </para>
        <variablelist>
            <varlistentry>
                <term>Build script</term>
                <listitem>
                    <para>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.
                    </para>
                </listitem>
            </varlistentry>
            <varlistentry>
                <term><filename>buildSrc</filename> project</term>
                <listitem>
                    <para>You can put the source for the plugin in the
                        <filename><replaceable>rootProjectDir</replaceable>/buildSrc/src/main/groovy</filename> 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.
                    </para>
                    <para>
                        See <xref linkend="organizing_build_logic"/> for more details about the <filename>buildSrc</filename>
                        project.</para>
                </listitem>
            </varlistentry>
            <varlistentry>
                <term>Standalone project</term>
                <listitem>
                    <para>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 custom plugins, or bundle several related task classes into a single library. Or
                        some combination of the two.
                    </para>
                </listitem>
            </varlistentry>
        </variablelist>
        <para> 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.
        </para>
    </section>

    <section>
        <title>Writing a simple plugin</title>
        <para>To create a custom plugin, you need to write an implementation of <apilink class="org.gradle.api.Plugin"/>.
            Gradle instantiates the plugin and calls the plugin instance's <apilink class="org.gradle.api.Plugin" method="apply"/> method when the
            plugin is used with a project. 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 <literal>hello</literal> task to the project.
        </para>

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

        <para>
            One thing to note is that a new instance of a given plugin is created for each project it is applied to. Also
            note that the <apilink class="org.gradle.api.Plugin"/> class is a generic type. This example has it receiving the
            <apilink class="org.gradle.api.Plugin"/> type as a type parameter. It's possible to write unusual custom
            plugins that take different type parameters, but this will be unlikely (until someone figures out more
            creative things to do here). 
        </para>
    </section>

    <section>
        <title>Getting input from the build</title>
        <para>Most plugins need to obtain some configuration from the build script. One method for doing this is to use <firstterm>extension objects</firstterm>.
             The Gradle <apilink class="org.gradle.api.Project"/> has an associated <apilink class="org.gradle.api.plugins.ExtensionContainer"/> object
             that helps keep track of all the settings and properties being passed to plugins. You can capture user input by telling
             the extension container about your plugin. To capture input, simply add a Java Bean compliant class into the extension container's list of
             extensions. Groovy is a good language choice for a plugin because plain old Groovy objects contain all the getter and setter methods
             that a Java Bean requires. 
        </para>

        <para>Let's add a simple extension object to the project. Here we add a <literal>greeting</literal> extension object to the
            project, which allows you to configure the greeting.
        </para>

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

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

        <para>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.
        </para>

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

        <para>In this example, several settings can be grouped together within the <literal>greeting</literal> closure.
            The name of the closure block in the build script (<literal>greeting</literal>) 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.
        </para>
    </section>

    <section>
        <title>Working with files in custom tasks and plugins</title>
        <para>
            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 <apilink class="org.gradle.api.Project" method="file(java.lang.Object)"/> method to resolve values to files as late as possible.
        </para>
        <sample id="lazyFileProperties" dir="userguide/tasks/customTaskWithFileProperty" title="Evaluating file properties lazily">
            <sourcefile file="build.gradle"/>
            <output args="-q sayGreeting"/>
        </sample>
        <para>
            In this example, we configure the <literal>greet</literal> task <literal>destination</literal> property as a closure, which is evaluated with
            the <apilink class="org.gradle.api.Project" method="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 <literal>greetingFile</literal> 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.
        </para>
    </section>
    
    <section>
        <title>A standalone project</title>
        <para>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.
        </para>

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

        <para>
                So how does Gradle find the <apilink class="org.gradle.api.Plugin"/> implementation? The answer is you need to provide a properties file in the jar's
            <filename>META-INF/gradle-plugins</filename> directory that matches the id of your plugin.
        </para>

        <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>	

        <para>
            Notice that the properties filename matches the plugin id and is placed in the resources folder, and
            that the <literal>implementation-class</literal> property identifies the <apilink class="org.gradle.api.Plugin"/> implementation class.
        </para>

        <section>
            <title>Creating a plugin id</title>
            <para>
                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.
            </para>
            <para>
                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 <literal>com.github.foo.bar</literal>.  Similarly, if the plugin was developed at the baz organization,
                the plugin id might be <literal>org.baz.bar</literal>.
            </para>
            <para>
                Plugin ids should conform to the following:
            </para>
            <itemizedlist>
                <listitem>May contain any alphanumeric character, '.', and '-'.</listitem>
                <listitem>Must contain at least one '.' character separating the namespace from the name of the plugin.</listitem>
                <listitem>Conventionally use a lowercase reverse domain name convention for the namespace.</listitem>
                <listitem>Conventionally use only lowercase characters in the name.</listitem>
                <listitem><literal>org.gradle</literal> and <literal>com.gradleware</literal> namespaces may not be used.</listitem>
                <listitem>Cannot start or end with a '.' character.</listitem>
                <listitem>Cannot contain consecutive '.' characters (i.e. '..').</listitem>
            </itemizedlist>
            <para>
                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.
            </para>
        </section>

        <section>
            <title>Publishing your plugin</title>
            <para>
                If you are publishing your plugin internally for use within your organization, you can publish it like
                any other code artifact.  See the <link linkend="publishing_ivy">ivy</link> and <link linkend="publishing_maven">maven</link>
                chapters on publishing artifacts.
            </para>
            <para>
                If you are interested in publishing your plugin to be used by the wider Gradle community, you can publish it to the
                <ulink url="http://plugins.gradle.org">Gradle plugin portal</ulink>.  This site provides the ability to search for and
                gather information about plugins contributed by the Gradle community.  See the instructions
                <ulink url="http://plugins.gradle.org/submit">here</ulink> on how to make your plugin available on this site.
            </para>
        </section>

        <section>
            <title>Using your plugin in another project</title>
            <para>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 “<literal>buildscript { }</literal>” block, as described in <xref linkend="sec:external_dependencies"/>.
                The following example shows how you might do this when the JAR containing the plugin has been published
                to a local repository:
            </para>
            <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>
            <para>
                Alternatively, if your plugin is published to the plugin portal, you can use the incubating plugins DSL (see <xref linkend="sec:plugins_block" />)
                to apply the plugin:
            </para>
            <sample id="useCommunityPluginDSL" dir="plugin-dsl" title="Applying a community plugin with the plugins DSL">
                <sourcefile file="build.gradle" snippet="use-community-plugin"/>
            </sample>
        </section>

        <section>
            <title>Writing tests for your plugin</title>
            <para>You can use the <apilink class="org.gradle.testfixtures.ProjectBuilder"/> class to create
                <apilink class="org.gradle.api.Project"/> instances to use when you test your plugin implementation.
            </para>
            <sample id="customPluginStandalone" dir="customPlugin/plugin" title="Testing a custom plugin">
                <sourcefile file="src/test/groovy/org/gradle/GreetingPluginTest.groovy" snippet="test-plugin"/>
            </sample>
        </section>

        <section>
            <title>Using the Java Gradle Plugin development plugin</title>
            <para>You can use the incubating <link linkend="javaGradle_plugin">Java Gradle Plugin development plugin</link>
                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 <link linkend="java_plugin">Java plugin</link>,
                add the <literal>gradleApi()</literal> dependency to the compile configuration, and perform plugin metadata
                validations as part of the <literal>jar</literal> task execution.
            </para>
            <sample id="useJavaGradlePluginPlugin" dir="javaGradlePlugin" title="Using the Java Gradle Plugin Development plugin">
                <sourcefile file="build.gradle" snippet="use-java-gradle-plugin-plugin"/>
            </sample>
        </section>
    </section>

    <section>
        <title>Maintaining multiple domain objects</title>

        <para>Gradle provides some utility classes for maintaining collections of objects, which work well with the Gradle build language.</para>

        <sample id="domainObjectContainer" dir="userguide/organizeBuildLogic/customPluginWithDomainObjectContainer" title="Managing domain objects">
            <sourcefile file="build.gradle"/>
            <output args="-q books"/>
        </sample>
        <para>
            The <apilink class="org.gradle.api.Project" method="container(java.lang.Class)"/> methods create instances of <apilink class="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 <literal>project.container</literal> methods, it MUST expose a property named “<literal>name</literal>”
            as the unique, and constant, name for the object. The <literal>project.container(Class)</literal> 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 <literal>project.container</literal> method variants that allow custom instantiation strategies.
        </para>
    </section>
</chapter>
