Matt James
Matt James

Reputation: 275

How to share variable between Gradle buildSrc and rest of project?

I have a Gradle project that has a buildSrc directory. Both the main project and the buildSrc project need to know the URL of an Artifactory server. I would like to keep the URL in a single place, and I would like it to be kept in source control. I tried adding the URL to the gradle.properties file, but that seems to only get picked up by the main project, not by the buildSrc project.

How can I share a property between the two?

Upvotes: 13

Views: 3958

Answers (3)

Michal Kordas
Michal Kordas

Reputation: 10925

To read project properties you can put at the beginning of buildSrc/build.gradle the following snippet:

def props = new Properties() 
rootDir.toPath().resolveSibling(GRADLE_PROPERTIES).toFile().withInputStream {
    props.load(it)
}
props.each { key, val -> project.ext."$key" = val }

Upvotes: 5

Tom Panning
Tom Panning

Reputation: 4772

In Gradle, buildSrc is a different build, not just a project within the main project. So the easiest way to share properties, etc. between the main build and buildSrc is to put it in a separate gradle/sharedProperties.gradle file. Then your main project build.gradle can use

apply from: 'gradle/sharedProperties.gradle'

and buildSrc/build.gradle can use

apply from: '../gradle/sharedProperties.gradle'

Upvotes: 4

Peter Niederwieser
Peter Niederwieser

Reputation: 123920

There is no built-in way to share information between the buildSrc build and the main build. However, you could read your own properties file from both (using java.lang.Properties).

Upvotes: 0

Related Questions