jim
jim

Reputation: 575

Can I read Gradle properties in the 'settings.gradle.kts' file?

I'm using Gradle Kotlin DSL. I want to know whether it's possible to read Gradle properties in the settings.gradle.kts file?

I have gradle.properties file like this:

nexus_username=something
nexus_password=somepassword

I've tried the following but still it can't read the properties:

dependencyResolutionManagement {
    repositories {
        maven {
            setUrl("https://some.repository/")
            credentials {
                val properties =
                    File(System.getProperty("user.home")+"\\.gradle", "gradle.properties").inputStream().use {
                        java.util.Properties().apply { load(it) }
                    }
                username = properties["nexus_username"].toString()
                password = properties["nexus_password"].toString()
            }
        }
    }
}

Upvotes: 31

Views: 18998

Answers (3)

ursa
ursa

Reputation: 4611

You can access credentials from ~/.gradle/gradle.properties using built-in credentials management:

// build.gradle or settings.gradle
repositories {
    ...
    maven {
        name = "someRepositoryId"
        url = uri("https://some.repository/")
        credentials(PasswordCredentials)
    }
}

Credentials would be resolved by repository name and Username/Password suffixes:

// ~/.gradle/gradle.properties
someRepositoryIdUsername=<user>
someRepositoryIdPassword=<password>

Upvotes: 2

You can access gradle parameters using providers (since 6.2)

val usernameProvider = providers.gradleProperty("nexus_username")
val passwordProvider = providers.gradleProperty("nexus_password")

dependencyResolutionManagement {
    repositories {
        maven {
            setUrl("https://some.repository/")
            credentials {
                username = usernameProvider.getOrNull()
                password = passwordProvider.getOrNull()
            }
        }
    }
}

To work on Groovy, you need to replace the variable declaration with:

def usernameProvider = providers.gradleProperty("nexus_username")
def passwordProvider = providers.gradleProperty("nexus_password")

Based on answer

Upvotes: 15

Bradley Thompson
Bradley Thompson

Reputation: 486

You can access values set in gradle.properties in both build.gradle.kts and settings.gradle.kts using delegate properties (Kotlin DSL only, because delegate properties is a Kotlin feature!).

gradle.properties

kotlin.code.style=official
# Your values here
testValue=coolStuff

build.gradle.kts

val testValue: String by project

settings.gradle.kts

val testValue: String by settings

Upvotes: 35

Related Questions