Gradle: Using string interpolation in model DSL

1.1k views Asked by At

How can I substitute a project property in a string in a model DSL? I tried the following:

apply plugin: 'com.android.model.native'

model {
    android {
        ...

        sources {
            main {
                jni {
                    source {
                        srcDirs "src"
                        include "*.cpp"
                    }
                    exportedHeaders {
                        srcDir "${project.rootDir}/include"
                    }
                }
            }
        }
    }
}

But I got this error:

Error:Attempt to read a write only view of model of type 'org.gradle.model.ModelMap<org.gradle.language.base.FunctionalSourceSet>' given to rule 'android { ... } @ android/build.gradle line 6, column 5'

It works if I assign the property value to a variable outside of the model block and substitute that variable instead:

def fooDir = project.rootDir
...
srcDir "${fooDir}/include"

But that's a bit inconvenient.

1

There are 1 answers

0
dcow On

It's a weird error, but it means you are trying to access a property that has not been declared as an input for the rule you are creating. To declare something as an input you have to use the "special syntax" for the model dsl. For example, to access the project.buildDir, you must use:

$.buildDir

Unfortunately, the project.rootDir is not bound to a model path yet. Caching the value in a variable accessible to your model rules (as you have done) seems to be a decent workaround for now.