Skip to content

Instantly share code, notes, and snippets.

@pablisco
Last active September 7, 2020 11:31
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pablisco/e7f70822d02d4cd0c6e98377ebad5d61 to your computer and use it in GitHub Desktop.
Save pablisco/e7f70822d02d4cd0c6e98377ebad5d61 to your computer and use it in GitHub Desktop.
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