Search code examples
kotlingradle-kotlin-dsl

Get gradle property from settings


So i am trying to transition my app to Kotlin DSL the issue i am facing is with accessing gradle.properties the way i was doing with groovy was like that, i am trying to access gradle.properties props from my settings.gradle.kts file

def propName = 'prop.name.something'
def propDisabled = Boolean.valueOf(properties[propName])

I tried several ways of accessing it with settings.extra[propName].toBoolean. It just seems there should be more straight way to access those properties?


Solution

  • The proper way to access a property declared in gradle.properties in settings.gradle.kts is by delegating it to the settings object:

    val myProperty: String by settings
    

    Note that it is mandatory to specify the property type String explicitly here.

    This will get the property myProperty from the gradle.properties file. Note that if you use it in the pluginManagement { ... } block, then the property declaration needs to be placed inside pluginManagement { ... }, too, as this block is evaluated before everything else in the script.

    However, if a property name contains symbols that are illegal in Kotlin identifiers, such as ., which is not allowed even in backticked identifiers, then you can't access it as a delegated property. There's no way to access such a property from the Gradle model as of Gradle 6.7, but, given that gradle.properties is just a .properties file, you can read it into a Java Properties instance:

    val properties = File(rootDir, "gradle.properties").inputStream().use { 
        java.util.Properties().apply { load(it) } 
    }
    val propNameSomething = properties.getValue("prop.name.something") as String