Skip to content

Commit

Permalink
Use reflection for obtaining the AGP version since the Version class …
Browse files Browse the repository at this point in the history
…was moved between 3.5 and 3.6

Fixes: #2547
RELNOTES=Fix an issue in the Hilt Gradle Plugin where determining AGP version failed if the AGP version being used was older than 3.6.
PiperOrigin-RevId: 369441551
  • Loading branch information
danysantiago authored and Dagger Team committed Apr 20, 2021
1 parent e33bb84 commit 0218653
Showing 1 changed file with 18 additions and 3 deletions.
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
package dagger.hilt.android.plugin.util

import com.android.Version

/**
* Simple Android Gradle Plugin version class since there is no public API one. b/175816217
*/
Expand All @@ -20,7 +18,18 @@ internal data class SimpleAGPVersion(

companion object {

val ANDROID_GRADLE_PLUGIN_VERSION by lazy { parse(Version.ANDROID_GRADLE_PLUGIN_VERSION) }
// TODO(danysantiago): Migrate to AndroidPluginVersion once it is available (b/175816217)
val ANDROID_GRADLE_PLUGIN_VERSION by lazy {
val clazz =
findClass("com.android.Version")
?: findClass("com.android.builder.model.Version")
if (clazz != null) {
return@lazy parse(clazz.getField("ANDROID_GRADLE_PLUGIN_VERSION").get(null) as String)
}
error(
"Unable to obtain AGP version. It is likely that the AGP version being used is too old."
)
}

fun parse(version: String?) =
tryParse(version) ?: error("Unable to parse AGP version: $version")
Expand All @@ -37,5 +46,11 @@ internal data class SimpleAGPVersion(

return SimpleAGPVersion(parts[0].toInt(), parts[1].toInt())
}

private fun findClass(fqName: String) = try {
Class.forName(fqName)
} catch (ex: ClassNotFoundException) {
null
}
}
}

0 comments on commit 0218653

Please sign in to comment.