Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move a gradle function from build.gradle into a plugin?

Tags:

gradle

Currently, I have a few utility functions defined in the top level build.gradle in a multi-project setup, for example like this:

def utilityMethod() {
    doSomethingWith(project) // project is magically defined
}

I would like to move this code into a plugin, which will make the utilityMethod available within a project that applies the plugin. How do I do that? Is it a project.extension?

like image 774
Christian Goetze Avatar asked Mar 20 '15 22:03

Christian Goetze


People also ask

How do I add plugins to build Gradle?

To add a Gradle plugin with dependencies, you can use code similar to the following: Plugin DSL GA versions. Plugin DSL non GA versions. Legacy Plugin Application.

Which task is executed to use Gradle build in plugin?

You can simply execute the task named init in the directory where you would like to create the Gradle build. There is no need to create a “stub” build. gradle file in order to apply the plugin. The Build Init plugin also uses the wrapper task to generate the Gradle Wrapper files for the build.

How do I convert build Gradle to kts?

Migrate one file at a timeRename the file to settings. gradle. kts and convert the file's contents to KTS. Make sure that your project still compiles after the migration of each build file.

When Gradle plugins are applied to a project it is possible to?

Applying a plugin to a project allows the plugin to extend the project's capabilities. It can do things such as: Extend the Gradle model (e.g. add new DSL elements that can be configured) Configure the project according to conventions (e.g. add new tasks or configure sensible defaults)


1 Answers

This seems to work using:

import org.gradle.api.Plugin
import org.gradle.api.Project

class FooPlugin implements Plugin<Project> {
    void apply(Project target) {
        target.extensions.create("foo", FooExtension)
        target.task('sometask', type: GreetingTask)
    }
}
class FooExtension{
    def sayHello(String text) {
        println "Hello " + text
    }
}

Then in the client build.gradle file you can do this:

task HelloTask << {
    foo.sayHello("DOM")
}

c:\plugintest>gradle -q HelloTask
Hello DOM

https://docs.gradle.org/current/userguide/custom_plugins.html

like image 180
Domc Avatar answered Sep 19 '22 09:09

Domc