Place for properties visible from both buildSrc and project

Where can i set a property that will be available both from buildSrc’s build.gradle and my projects build.gradle’s?

project level gradle.properties not available from buildSrc

Goal: I want to share some props, like repo url’s

The buildSrc project is looking for properties in a gradle.properties file in the buildSrc directory. A simple thing would just be to create a symbolic link there to the gradle.properties file in the root project.

├── buildSrc
│   ├── build.gradle
│   └── gradle.properties -> ../gradle.properties
└── gradle.properties

Alternatively if you want a more cross-platform way of doing this you could put properties in a .gradle file and then just apply to both projects.

properties.gradle

ext {
  repoUrl = 'http://repo.mycompany.org'
}

build.gradle

apply from: 'properties.gradle'

buildSrc/build.gradle

apply from: "${rootDir.parentFile}/properties.gradle"
4 Likes

This is what I was looking for, however I do have a follow up question.

I found this answer: http://stackoverflow.com/a/26598652
So based on using java.lang.Properties as an alternative solution, how do you tell code in buildSrc where the root or base directory is.

It appears that the relative path from the perspective of code in buildSrc is always where you execute the build from.

So if I wanted to do something like this:

Properties projectProperties = new java.util.Properties()
FileInputStream fis = new FileInputStream(“gradle.properties”)
projectProperties.load(fis)

If you’re not in the root directory when you execute the build then it won’t find the file.

Can you do this:

Properties projectProperties = new java.util.Properties()
FileInputStream fis = new FileInputStream("$rootDir/gradle.properties")
projectProperties.load(fis)

This is with a situation where you don’t have a buildSrc/build.gradle file.

1 Like

@robleach It’s not clear to me where this code you are showing will live? Is this in a build script or in a Java source file that lives in the buildSrc project?

Sorry, it is Groovy code under buildSrc/src/main/groovy/UCD.groovy.

I think what I would do is restructure your code to take the file location as some kind of argument. The working directory is not going to be predictable and project.rootDir is only available from within a build script.

Okay at least that answers my follow up question. Thanks.

Here’s a copy-paste snippet for anyone else who comes along and wants gradle.properties in their root dir to be visible to buildSrc.

/*** file: gradle/loadProps.gradle ***/
Properties properties = new Properties()
FileInputStream input = new FileInputStream(file('../gradle.properties'))
properties.load(input)
input.close()

for (String key : properties.stringPropertyNames()) {
	ext.set(key, properties.getProperty(key))
}

/*** file: buildSrc/build.gradle ***/
apply from: '../gradle/loadProps.gradle'
1 Like

How about properties visible from buildSrc/settings.gradle?