Extract common methods from Gradle build script

I have a Gradle build script ( build.gradle ) in which I created some tasks. These tasks consist mainly of method calls. The called methods are also in the assembly script.

Now, here is the situation:

I create a large number of build scripts that contain different tasks, but use the same methods from the original script. Thus, I would like to somehow extract these "common methods", so I can easily use them instead of copying for every new script that I create.

If Gradle were PHP, then it would be ideal:

 //script content ... require("common-methods.gradle"); ... //more script content 

But of course this is not possible. Or that?

In any case, how can I achieve this result? What is the best way to do this? I have already read the Gradle documentation, but I can not determine which method will be the simplest and most suitable for this.

Thanks in advance!




UPDATE:

I managed to extract methods in another file

(using apply from: 'common-methods.gradle' ),

therefore, the structure is as follows:

 parent/ /build.gradle // The original build script /common-methods.gradle // The extracted methods /gradle.properties // Properties used by the build script 

After completing the task from build.gradle I ran into a new problem: apparently, the methods are not recognized when they are in common-methods.gradle .

Any ideas on how to fix this?

+74
build.gradle gradle
Sep 10 '13 at 9:22
source share
3 answers

You cannot exchange methods, but you can share additional properties that contain a closure that comes down to the same thing. For example, declare ext.foo = { ... } in common-methods.gradle , use apply from: to apply the script, and then call the closure with foo() .

+70
Sep 10 '13 at 12:19
source share

Based on Peter’s answer , I export my methods as follows:

Contents helpers/common-methods.gradle :

 // Define methods as usual def commonMethod1(param) { return true } def commonMethod2(param) { return true } // Export methods by turning them into closures ext { commonMethod1 = this.&commonMethod1 otherNameForMethod2 = this.&commonMethod2 } 

And this is how I use these methods in another script:

 // Use double-quotes, otherwise $ won't work apply from: "$rootDir/helpers/common-methods.gradle" // You can also use URLs //apply from: "https://bitbucket.org/mb/build_scripts/raw/master/common-methods.gradle" task myBuildTask { def myVar = commonMethod1("parameter1") otherNameForMethod2(myVar) } 

Here's more about converting methods to closures in Groovy.

+132
Apr 25 '14 at 10:43
source share

Using Kotlin dsl , it works as follows:

build.gradle.kts :

 apply { from("external.gradle.kts") } val foo = extra["foo"] as () -> Unit foo() 

external.gradle.kts :

 extra["foo"] = fun() { println("Hello world!") } 
+3
02 Sep '18 at 17:47
source share



All Articles