How to access Kotlin DSL extensions from non-build-gradle file?

2.2k views Asked by At

There are few Kotlin Extensions that come along with org.gradle.kotlin.dsl like android or publishing etc. Say, for publishing, the extension is defined as below

fun org.gradle.api.Project.`publishing`(configure: org.gradle.api.publish.PublishingExtension.() -> Unit): Unit =
    (this as org.gradle.api.plugins.ExtensionAware).extensions.configure("publishing", configure)

That means within mybuild.gradle.kts I can call

publishing {
    // blablabla
}

In my case, I have a separate file that handles publishing defined as random.gradle.kts and is located at totally random directory.

Here, I want to access this publishing extension but not able to do it.

Any suggestions are welcomed.

To give another example android is also not accessible. In my build.gradle.kts I can access android but in my random.gradle.kts I am not able to do it.

android extension is defined as below

val org.gradle.api.Project.`android`: com.android.build.gradle.LibraryExtension get() =
    (this as org.gradle.api.plugins.ExtensionAware).extensions.getByName("android") as com.android.build.gradle.LibraryExtension

In fact, LibraryExtension is also not accessible.

So, how to pass or import those extensions to my random.gradle.kts?

1

There are 1 answers

0
Dan Brough On

    //build.gradle.kts tested with gradle 6.7
    
    subprojects {
      afterEvaluate {
        (extensions.findByType(com.android.build.gradle.LibraryExtension::class)
          ?: extensions.findByType(com.android.build.gradle.AppExtension::class))?.apply {
    
          println("Found android subproject $name")
          lintOptions.isAbortOnError = false
          compileSdkVersion(30)
          
          if (this is com.android.build.gradle.AppExtension) 
            println("$name is an application")
          
          if (this is com.android.build.gradle.LibraryExtension) {
    
            val publishing =
              extensions.findByType(PublishingExtension::class.java) ?: return@afterEvaluate
    
            val sourcesJar by tasks.registering(Jar::class) {
              archiveClassifier.set("sources")
              from(sourceSets.getByName("main").java.srcDirs)
            }
    
            afterEvaluate {
              publishing.apply {
                val projectName = name
                publications {
                  val release by registering(MavenPublication::class) {
                    components.forEach {
                      println("Publication component: ${it.name}")
                    }
                    from(components["release"])
                    artifact(sourcesJar.get())
                    artifactId = projectName
                    groupId = ProjectVersions.GROUP_ID
                    version = ProjectVersions.VERSION_NAME
                  }
                }
              }
            }
          }
        }
      }
    }