1 package dagger.hilt.android.plugin.util 2 3 /** 4 * Simple Android Gradle Plugin version class since there is no public API one. b/175816217 5 */ 6 internal data class SimpleAGPVersion( 7 val major: Int, 8 val minor: Int, 9 ) : Comparable<SimpleAGPVersion> { 10 compareTonull11 override fun compareTo(other: SimpleAGPVersion): Int { 12 return compareValuesBy( 13 this, 14 other, 15 compareBy(SimpleAGPVersion::major).thenBy(SimpleAGPVersion::minor) 16 ) { it } 17 } 18 19 companion object { 20 21 // TODO(danysantiago): Migrate to AndroidPluginVersion once it is available (b/175816217) <lambda>null22 val ANDROID_GRADLE_PLUGIN_VERSION by lazy { 23 val clazz = 24 findClass("com.android.Version") 25 ?: findClass("com.android.builder.model.Version") 26 if (clazz != null) { 27 return@lazy parse(clazz.getField("ANDROID_GRADLE_PLUGIN_VERSION").get(null) as String) 28 } 29 error( 30 "Unable to obtain AGP version. It is likely that the AGP version being used is too old." 31 ) 32 } 33 parsenull34 fun parse(version: String?) = 35 tryParse(version) ?: error("Unable to parse AGP version: $version") 36 37 private fun tryParse(version: String?): SimpleAGPVersion? { 38 if (version == null) { 39 return null 40 } 41 42 val parts = version.split('.') 43 if (parts.size == 1) { 44 return SimpleAGPVersion(parts[0].toInt(), 0) 45 } 46 47 return SimpleAGPVersion(parts[0].toInt(), parts[1].toInt()) 48 } 49 findClassnull50 private fun findClass(fqName: String) = try { 51 Class.forName(fqName) 52 } catch (ex: ClassNotFoundException) { 53 null 54 } 55 } 56 } 57