Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

gradle

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?

like image 717
Matt James Avatar asked Oct 27 '14 21:10

Matt James


People also ask

How do I declare a variable in Gradle?

Local variables are declared with the def keyword. They are only visible in the scope where they have been declared. Local variables are a feature of the underlying Groovy language. Local variables are declared with the val keyword.

How are environment variables used in Gradle properties?

Gradle can also set project properties when it sees specially-named system properties or environment variables. If the environment variable name looks like ORG_GRADLE_PROJECT_prop=somevalue , then Gradle will set a prop property on your project object, with the value of somevalue .

What is buildSrc in Gradle?

buildSrc is a directory at the Gradle project root, which can contain our build logic. This allows us to use the Kotlin DSL to write our custom build code with very little configuration and share this logic across the whole project.


2 Answers

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'
like image 137
Tom Panning Avatar answered Oct 11 '22 11:10

Tom Panning


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 }
like image 33
Michal Kordas Avatar answered Oct 11 '22 10:10

Michal Kordas