Skip to content

Instantly share code, notes, and snippets.

@pablisco
Last active Sep 7, 2020
Embed
What would you like to do?
Gradle Multi project settings Kotlin DSL

Gradle Multi project settings Kotlin DSL

This is a small Gradle DSL that can be used to include multiple modules. Let's imagine that we have a set up like this:

root
+-- app
+-- modules
    +-- core
    +-- androidx
        +-- core

The traditional way to include these structure would look something like this:

include(":app")
include(":modules:core")
include(":modules:androidx:core")

With this dsl we can do this instead:

include {
  ":app"()
  ":modules" {
    ":core"()
    ":androidx" {
      ":core"()
    }
  }
}

This looks more like the actual folder structure. In this example there aren't many modules, however it should be aparent that as the project grows this way of defining the project structure will scale better. Code should be easier to refactor, so changing the name of a parent module would reqauire to just change the name on one place and rename the folder. Easy peasy!

include {
":app"()
":modules" {
":core"()
":androidx" {
":core"()
}
}
}
class ModuleParentScope(private val name: String, private val parentPath: String = "") {
operator fun String.invoke(block: (ModuleParentScope.() -> Unit)? = null) {
val path = "$parentPath:$this"
logger.info("including: $path")
include(path)
if (block != null) {
ModuleParentScope(name = this, parentPath = path).block()
}
}
}
fun include(block: ModuleParentScope.() -> Unit) {
ModuleParentScope("").block()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment