I have a Gradle build script (build.gradle
), in which I created some tasks. These tasks consist mostly of method calls. The called methods are also in the build script.
Now, here's the situation:
I am creating a fair amount of build scripts, which contain different tasks, but utilise the same methods from the original script. Thus, I would like to extract these "common methods" in some way, so I can easily re-use them instead of copying them for each new script I create.
If Gradle were PHP, something like the following would be ideal:
//script content
...
require("common-methods.gradle");
...
//more script content
But of course, that isn't possible. Or is it?
Anyway, how can I achieve this result? What is the best possible method to do this? I've read through the Gradle documentation already, but I can't seem to determine which method will be the easiest and best suited for this.
UPDATE:
I've managed to extract the methods in another file
(using apply from: 'common-methods.gradle'
),
so 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 executing a task from build.gradle
, I've bumped into a new problem: apparently, methods don't get recognized when they're in common-methods.gradle
.
How can that be fixed?
timestamp()
orcurrentWorkingDirectory()
methods astask
-s (for example). Utility functions and similar things are nominally scalar -- They wouldn't be tasks except that there are limitations on code-reuse in-built with Gradle and most build systems. I like the DRY world where I can make a thing ONE time and reuse it. In fact, extending @Pieter VDE's example I also use a "root.gradle
" pattern for my parent project -- The build.gradle file usually defines some project specifics and then justapply ${ROOT}
...