All Downloads are FREE. Search and download functionalities are using the official Maven repository.

name.remal.gradle_plugins.dsl.utils.findPluginId.kt Maven / Gradle / Ivy

package name.remal.gradle_plugins.dsl.utils

import io.github.classgraph.ClassGraph
import name.remal.asSynchronized
import name.remal.getMetaAnnotation
import name.remal.gradle_plugins.dsl.IMPLEMENTATION_CLASS_PLUGIN_DESCRIPTOR_KEY
import name.remal.gradle_plugins.dsl.Plugin
import name.remal.gradle_plugins.dsl.ProjectPluginClass
import name.remal.gradle_plugins.dsl.extensions.unwrapGradleGenerated
import name.remal.nullIfEmpty
import java.util.*

fun findPluginId(pluginClass: ProjectPluginClass): String? {
    val pluginClassUnwrapped = pluginClass.unwrapGradleGenerated()

    var currentClass: Class<*>? = pluginClassUnwrapped
    while (currentClass != null && Any::class.java != currentClass) {
        currentClass.getMetaAnnotation(Plugin::class.java)?.id?.nullIfEmpty()?.let { return it }
        currentClass = currentClass.superclass
    }

    val pluginIds = sortedSetOf(Comparator.comparingInt(String::length).reversed().then(Comparator.naturalOrder())).asSynchronized()
    ClassGraph()
        .overrideClassLoaders(pluginClassUnwrapped.classLoader)
        .whitelistPathsNonRecursive("META-INF/gradle-plugins")
        .scan().use {
            it.allResources.asSequence()
                .filter { it.path.endsWith(".properties") }
                .forEach { resource ->
                    val properties = Properties().also { props ->
                        try {
                            resource.open().use { props.load(it) }
                        } catch (e: Exception) {
                            return@forEach
                        }
                    }
                    val implementationClass = properties.getProperty(IMPLEMENTATION_CLASS_PLUGIN_DESCRIPTOR_KEY)
                    if (implementationClass == pluginClassUnwrapped.name) {
                        pluginIds.add(resource.path.substringAfterLast('/').substringBeforeLast('.'))
                    }
                }
        }

    return pluginIds.firstOrNull()
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy