Skip to content

Commit

Permalink
Handle exceptions & Load all scripts in script directory
Browse files Browse the repository at this point in the history
  • Loading branch information
R2turnTrue committed Jun 18, 2022
1 parent 36bd534 commit 39dd8c3
Showing 1 changed file with 30 additions and 15 deletions.
45 changes: 30 additions & 15 deletions src/main/kotlin/xyz/minejs/minepy/MinePyPlugin.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,16 @@ package xyz.minejs.minepy

import org.bukkit.command.CommandExecutor
import org.bukkit.plugin.java.JavaPlugin
import org.python.core.PyException
import org.python.util.PythonInterpreter
import java.io.File
import java.nio.file.Paths
import java.util.*
import kotlin.collections.ArrayList

lateinit var plugin: MinePyPlugin

class MinePyPlugin: JavaPlugin() {
lateinit var interpreter: PythonInterpreter
val interpreters = ArrayList<PythonInterpreter>()

override fun onEnable() {
plugin = this
Expand All @@ -22,25 +23,39 @@ class MinePyPlugin: JavaPlugin() {
PythonInterpreter.initialize(System.getProperties(), props, arrayOf(""))
loadScript()
getCommand("pyreload")?.setExecutor(CommandExecutor { sender, command, label, args ->
val endFunction = interpreter.get("end")
if(endFunction != null && endFunction.isCallable)
endFunction.__call__()
interpreter.close()
loadScript()
sender.sendMessage("Re-loaded script(s)!")
for (interpreter in interpreters) {
val endFunction = interpreter.get("end")
if(endFunction != null && endFunction.isCallable)
endFunction.__call__()
interpreter.close()
}
val errors = loadScript()
errors.forEach { error ->
sender.sendMessage("Error when loading ${error.key} - ${error.value.message}")
}
sender.sendMessage("Re-loaded script(s) with ${errors.size} error(s)!")
return@CommandExecutor true
})
}

fun loadScript() {
val scriptFile = File(dataFolder, "main.py")
fun loadScript(): WeakHashMap<String, PyException> {
if(!dataFolder.exists())
dataFolder.mkdir()
if(!scriptFile.exists())
scriptFile.createNewFile()

interpreter = PythonInterpreter()
interpreter.systemState.classLoader = this.classLoader
interpreter.execfile(scriptFile.inputStream())
val exceptionMap = WeakHashMap<String, PyException>()

dataFolder.listFiles()?.forEach { scriptFile ->
try {
interpreters.add(PythonInterpreter().also { interpreter ->
interpreter.systemState.classLoader = this.classLoader
interpreter.execfile(scriptFile.inputStream())
})
} catch (ex: PyException) {
ex.printStackTrace()
exceptionMap[scriptFile.name] = ex
}
}

return exceptionMap
}
}

0 comments on commit 39dd8c3

Please sign in to comment.