io.github.molumn.catrix.kommand.Kommand.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of catrix-api Show documentation
Show all versions of catrix-api Show documentation
Kotlin/JVM library for terminal command development
package io.github.molumn.catrix.kommand
import io.github.molumn.catrix.annotations.KommandDSL
import io.github.molumn.catrix.common.Interactive
import io.github.molumn.catrix.common.exceptions.NoDefinedExecutorException
import io.github.molumn.catrix.common.exceptions.UnknownKommandException
import io.github.molumn.catrix.kommand.node.NodeType
import io.github.molumn.catrix.utils.FakeSystem
class RegisteredKommand(
val name: String,
private val subcommand: List>,
private val executor: ((Interactive, KommandContext, FakeSystem) -> Boolean)?
) {
fun execute(args: Array, interactive: Interactive = Interactive) {
val system = FakeSystem()
val contents = HashMap>()
if (args.isEmpty()) {
val context = KommandContext(this, HashMap())
executor?.invoke(interactive, context, system)
?: throw NoDefinedExecutorException("Command Inputs [${context.getCommandInputs()}] has no defined executor")
return
}
var arg = args[0]
var node: AbstractRegisteredKommandNode<*>? = subcommand.find { it.check(arg) }
node ?: throw UnknownKommandException("unknown kommand : $arg")
require(node.condition.invoke(system)) { "Condition Error" }
contents[node.name] = KommandContent(node.name, arg, node.extract(arg))
for (index in 1 until args.size) {
arg = args[index]
node = node?.find(arg)
node ?: throw UnknownKommandException("unknown kommand : $arg")
require(node.condition.invoke(system)) { "Condition Error" }
contents[node.name] = KommandContent(node.name, arg, node.extract(arg))
}
val context = KommandContext(this, contents)
node!!.executor?.invoke(interactive, context, system)
?: throw NoDefinedExecutorException("Command Inputs [${context.getCommandInputs()}] has no defined executor")
}
}
@KommandDSL
class Kommand(
val name: String
) {
private val subcommand: MutableList = mutableListOf()
private var executor: ((Interactive, KommandContext, FakeSystem) -> Boolean)? = null
fun register(name: String, init: LiteralNode.() -> Unit) {
subcommand.add(LiteralNode(name).apply(init))
}
fun argument(node: Pair>, init: ArgumentNode.() -> Unit) {
subcommand.add(ArgumentNode(node.first, node.second).apply(init))
}
fun execute(executor: (interactive: Interactive, context: KommandContext, system: FakeSystem) -> Boolean) {
this.executor = executor
}
internal fun build() : RegisteredKommand =
RegisteredKommand(name, subcommand.map { it.build() }, executor)
}
fun kommand(name: String, registry: Kommand.() -> Unit) : RegisteredKommand {
return Kommand(name).apply(registry).build()
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy