io.appmetrica.gradle.aarcheck.imports.ImportChecker.kt Maven / Gradle / Ivy
package io.appmetrica.gradle.aarcheck.imports
import io.appmetrica.gradle.aarcheck.AarCheckException
import io.appmetrica.gradle.aarcheck.utils.NamesUtils
import io.appmetrica.gradle.aarcheck.utils.extractEntry
import io.appmetrica.gradle.aarcheck.utils.isClass
import javassist.ClassPool
import java.io.File
import java.util.jar.JarEntry
import java.util.jar.JarFile
import java.util.zip.ZipFile
object ImportChecker {
fun check(aarFile: File, forbiddenImports: List) {
if (forbiddenImports.isEmpty()) return
val imports = forbiddenImports.map(NamesUtils::unfixPackageName)
ZipFile(aarFile).use { zipFile ->
JarFile(zipFile.extractEntry("classes.jar")).use { jarFile ->
val classPool = ClassPool()
classPool.appendClassPath(jarFile.name)
for (jarEntry in jarFile.entries().toList().filter(JarEntry::isClass)) {
if (jarEntry.name.dropLast(".class".length) in imports) continue
val ctClass = classPool.get(NamesUtils.getFullClassName(jarEntry.name))
val forbiddenImportsFound = imports.intersect(ctClass.classFile.constPool.classNames)
if (forbiddenImportsFound.isNotEmpty()) {
val forbiddenImport = NamesUtils.fixPackageName(forbiddenImportsFound.first())
throw AarCheckException("Found forbidden import '$forbiddenImport' in '${ctClass.name}'")
}
}
}
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy