Fix plugin loader

This commit is contained in:
Him188 2020-06-29 23:13:34 +08:00
parent 7c5a62d18e
commit 6ef9332217
4 changed files with 21 additions and 14 deletions

View File

@ -50,6 +50,8 @@ interface PluginLoader<P : Plugin, D : PluginDescription> {
fun disable(plugin: P)
}
fun <D : PluginDescription, P : Plugin> PluginLoader<P, D>.getDescription(plugin: P): D = plugin.description
open class PluginLoadException : RuntimeException {
constructor() : super()
constructor(message: String?) : super(message)

View File

@ -13,12 +13,16 @@ package net.mamoe.mirai.console.plugin
import kotlinx.atomicfu.locks.withLock
import net.mamoe.mirai.console.MiraiConsole
import net.mamoe.mirai.console.setting.internal.cast
import net.mamoe.mirai.utils.info
import java.io.File
import java.util.concurrent.locks.ReentrantLock
val Plugin.description: PluginDescription
get() = PluginManager.resolvedPlugins.firstOrNull { it == this }?.description ?: error("Plugin is unloaded")
get() = PluginManager.resolvedPlugins.firstOrNull { it == this }?.loader?.cast<PluginLoader<Plugin, PluginDescription>>()
?.getDescription(
this
) ?: error("Plugin is unloaded")
inline fun PluginLoader<*, *>.register() = PluginManager.registerPluginLoader(this)
inline fun PluginLoader<*, *>.unregister() = PluginManager.unregisterPluginLoader(this)

View File

@ -21,7 +21,7 @@ import net.mamoe.mirai.console.utils.ConsoleExperimentalAPI
import net.mamoe.mirai.utils.MiraiLogger
import net.mamoe.yamlkt.Yaml
import java.io.File
import java.net.URL
import java.net.URI
import kotlin.coroutines.CoroutineContext
import kotlin.reflect.full.createInstance
@ -54,17 +54,18 @@ object JarPluginLoader : AbstractFilePluginLoader<JvmPlugin, JvmPluginDescriptio
get() = this.description
override fun Sequence<File>.mapToDescription(): List<JvmPluginDescription> {
return this.associateWith { URL("jar:${it.absolutePath}!/plugin.yml") }.mapNotNull { (file, url) ->
kotlin.runCatching {
url.readText()
}.fold(
onSuccess = { yaml ->
Yaml.nonStrict.parse(JvmPluginDescription.serializer(), yaml)
},
onFailure = {
logger.error("Cannot load plugin file ${file.name}", it)
null
}
return this.associateWith { URI("jar:file:${it.absolutePath.replace('\\', '/')}!/plugin.yml").toURL() }
.mapNotNull { (file, url) ->
kotlin.runCatching {
url.readText()
}.fold(
onSuccess = { yaml ->
Yaml.nonStrict.parse(JvmPluginDescription.serializer(), yaml)
},
onFailure = {
logger.error("Cannot load plugin file ${file.name}", it)
null
}
)?.also { it._file = file }
}
}

View File

@ -141,7 +141,7 @@ internal fun KClass<*>.isPrimitiveOrBuiltInSerializableValue(): Boolean {
@PublishedApi
@Suppress("UNCHECKED_CAST")
internal inline fun <R, T> T.cast(): R = this as R
internal inline fun <R> Any.cast(): R = this as R
/**
* Copied from kotlinx.serialization, modifications are marked with "/* mamoe modify */"