1 /* 2 * Copyright (C) 2022 The Dagger Authors. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package dagger.hilt.android.plugin.util 18 19 /** 20 * Simple Android Gradle Plugin version class since there is no public API one. b/175816217 21 */ 22 data class SimpleAGPVersion( 23 val major: Int, 24 val minor: Int, 25 ) : Comparable<SimpleAGPVersion> { 26 toStringnull27 override fun toString(): String { 28 return "$major.$minor" 29 } 30 compareTonull31 override fun compareTo(other: SimpleAGPVersion): Int { 32 return compareValuesBy( 33 this, 34 other, 35 compareBy(SimpleAGPVersion::major).thenBy(SimpleAGPVersion::minor) 36 ) { it } 37 } 38 39 companion object { 40 41 // TODO(danysantiago): Migrate to AndroidPluginVersion once it is available (b/175816217) <lambda>null42 val ANDROID_GRADLE_PLUGIN_VERSION by lazy { 43 val clazz = 44 findClass("com.android.Version") 45 ?: findClass("com.android.builder.model.Version") 46 if (clazz != null) { 47 return@lazy parse(clazz.getField("ANDROID_GRADLE_PLUGIN_VERSION").get(null) as String) 48 } 49 error( 50 "Unable to obtain AGP version. It is likely that the AGP version being used is too old." 51 ) 52 } 53 parsenull54 fun parse(version: String?) = 55 tryParse(version) ?: error("Unable to parse AGP version: $version") 56 57 private fun tryParse(version: String?): SimpleAGPVersion? { 58 if (version == null) { 59 return null 60 } 61 62 val parts = version.split('.') 63 if (parts.size == 1) { 64 return SimpleAGPVersion(parts[0].toInt(), 0) 65 } 66 67 return SimpleAGPVersion(parts[0].toInt(), parts[1].toInt()) 68 } 69 findClassnull70 private fun findClass(fqName: String) = 71 try { 72 Class.forName(fqName) 73 } catch (ex: ClassNotFoundException) { 74 null 75 } 76 } 77 } 78