Sergey
Sergey

Reputation: 1050

Read build script blocks from gradle plugin

There is a gradle plugin with id ("com.my.plugin").

The project using this plugin has the following build.gradle file:

...
apply plugin: 'com.my.plugin'
...
android {
    ...
    defaultConfig {
        ...
        testInstrumentationRunner "com.my.plugin.junit4.MyCustomRunner"
        ...
    }
    ...
}
...
dependencies {
    ...
    androidTestImplementation com.my:plugin-junit4:1.0.0-alpha04
    ...
}
...

The class implementing the plugin is as follows:

class MyPlugin: Plugin <Project> {
    override fun apply (project: Project) {
        project.afterEvaluate {
            // here I need to read testInstrumentationRunner value declared 
            // in the defaultConfig block of the build.gradle file
            // also here I need to read androidTestImplementation value declared 
            // in the dependencies block of the build.gradle file
        }
    }
}

In the project.afterEvaluate {...} block of the plugin I need to check for the values ​​of testInstrumentationRunner and androidTestImplementation declared in the build.gradle file of the project using this plugin. How to do it?

Upvotes: 0

Views: 292

Answers (1)

Cisco
Cisco

Reputation: 23042

Since you're using Kotlin for your plugin implementation, you'll need know the type of the android { } extension. Otherwise you will run into compilation errors.

Essentially, you need to retrieve a reference of the android extension in your plugin like so:

project.afterEvaluate {
    // we don't know the concrete type so this will be `Object` or `Any`
    val android = project.extensions.getByName("android")

    println(android::class.java) // figure out the type

    // assume we know the type now
    val typedAndroid = project.extensions.getByType(WhateverTheType::class.java)

    // Ok now Kotlin knows of the type and its properties
    println(typedAndroid.defaultConfig.testInstrumentationRunner)
}

I'm not familar with Android or its Gradle plugin. Google only led me to its Javadocs here which didn't help. So the above may or may not work.

Upvotes: 1

Related Questions