androidkotlingradlegroovy

How to get parameters of a groovy class inside build.gradle(app) to a custom gradle plugin


I have created a custom gradle plugin for android written in Kotlin. Plugin works correctly. One thing I am missing is fetching of parameters from a class inside my Applications build.gradle (app level).

So I am applying MyPlugin to an app.

build.gradle (app level)

plugins{
   id 'com.example.MyPlugin'
}
....
....
ArchiveConfig{
   username 'James'
   password '12345678'
   debugApk false
}

inside MyPlugin.kt in MyPlugin project

open class MyPlugin : Plugin<Project>{

   val archiveConfig: ArchiveConfig = project.extensions.create("ArchiveConfig", ArchiveConfig())   

   override fun apply(p : Project) {
      //some code
   }
}

//I believe here I should somehow fetch that ArchiveConfig values from build.gradle which is inside

open class ArchiveConfig(var username: String? = null
                         var password: String? = null
                         vardebugApk: Boolean = false) : GroovyObjectSupport() {
   //do something with data in plugin
}

If I go with the described approach i get an error

Could not find method ArchiveConfig() for arguments [...]

Thanks ahead!


Solution

  • As per @tim_yates and his link to documentation for extension.

    In order to customize behaviour of our custom plugin or in other words if we want to send some parameters from app we are working on from build.gradle to custom plugin and then use those parameters in custom plugin we have to use extension objects.

    Example of usage would be:

    Application build.gradle (app level)

    //here we apply our plugin
    plugins{
     id 'com.example.MyPlugin'
    }
    ....
    ....
    //groovy class whose parameters we want to "send" to CustomPlugin for it to do some work
    ArchiveConfig{
       username 'James'
       password '12345678'
    }
    

    inside MyPlugin.kt in CustomPlugin project

     open class MyPluginExtension{
     var username : String = ""
     var password : String = ""
     }
    
     class MyPlugin : Plugin<Project>{
        override fun apply(p : Project) {
            val extension = project.extensions.create<MyPluginExtension>("ArchiveConfig")
        
         //do stuff with variables from ArchiveConfig
         //you access them with following
    
         val user = extension.username
         val pw = extension.password
        }
     }