Raz
Raz

Reputation: 499

how to include "global" files in gradle

I have multiple projects with their own build.gradle and settings.gradle. i want to add a "global" file which is named also build.gradle (or some other name, it dosent matter) to one of the projects, my question is: how do i include the new file from all the other projects (build.gradle or setting.gradle files) ?

Upvotes: 0

Views: 231

Answers (1)

Mark Fisher
Mark Fisher

Reputation: 9886

I don't think you can do this for settings.gradle, but you can load other build.gradle files readily enough with

apply from: "$rootDir/../OtherProject/path/to/your.gradle"

this particular example would assume your projects root directories are contained in a single directory.

Of course because you are loading it raw between projects, non of the definitions from OtherProject/settings.gradle would be loaded, so references may fail in the loaded file unless it is truly global in nature.

However, you might want to instead consider using a multiproject build and restructuring your projects in a way that groups them more logically together rather than hard hacking build scripts between disparate projects.

Also, if you're trying to share common tasks etc between projects, consider converting them to a plugin and including that in each project that needs the functionality.

EDIT: Showing linking between projects

To access global values, you use ext. See the ext gradle docs for more examples.

Proj1/build.gradle:

apply from: "$rootDir/../Proj2/build.gradle"

task printX << {
    # this is the full syntax
    println project.ext.x

    # however, anything on project.ext becomes global too, so you
    # can reference it directly as just "x"
    println "x[a] = ${x['a']}"
    println x['b']

    # showing it's just the map we expect
    def keysOfX = x.keySet()
    println keysOfX
}

Proj2/build.gradle:

ext {
    x = [a: 1, b: 2]
}

Running the task:

> cd Proj1
> gradle printX
:printX
{a=1, b=2}
x[a] = 1
2
[a, b]

BUILD SUCCESSFUL

Total time: 2.894 secs

Upvotes: 2

Related Questions