Skip to content

Commit

Permalink
Almost finished arg processing
Browse files Browse the repository at this point in the history
  • Loading branch information
Matt-MX committed Jul 5, 2024
1 parent 8260a8a commit 52ef299
Show file tree
Hide file tree
Showing 20 changed files with 144 additions and 53 deletions.
17 changes: 16 additions & 1 deletion api/.gradle/caches/paperweight/taskCache/reobfJar.log
Original file line number Diff line number Diff line change
@@ -1,2 +1,17 @@
Command: C:\Program Files\Java\jdk-17\bin\java.exe -Xmx1G -classpath C:\Users\Mangr\.gradle\caches\modules-2\files-2.1\net.fabricmc\tiny-remapper\0.10.1\c293b2384ae12af74f407fa3aaa553bba4ac6763\tiny-remapper-0.10.1-fat.jar net.fabricmc.tinyremapper.Main D:\PC\Projects\KtBukkitGui\api\build\libs\ktgui-2.4.1-dev-all.jar D:\PC\Projects\KtBukkitGui\api\build\libs\api-2.4.1.jar C:\Users\Mangr\.gradle\caches\paperweight-userdev\ff775525efc29c3503a07d1006e63e5695a742b7505cf63e157d49d32419c69f\module\io.papermc.paper\dev-bundle\1.20.4-R0.1-SNAPSHOT\paperweight\setupCache\extractDevBundle.dir\data\mojang+yarn-spigot-reobf.tiny mojang+yarn spigot C:\Users\Mangr\.gradle\caches\paperweight-userdev\ff775525efc29c3503a07d1006e63e5695a742b7505cf63e157d49d32419c69f\module\io.papermc.paper\dev-bundle\1.20.4-R0.1-SNAPSHOT\paperweight\setupCache\applyMojangMappedPaperclipPatch.jar --threads=1
Finished after 2784.17 ms.
Exception in thread "main" java.lang.RuntimeException: java.nio.file.FileSystemException: D:\PC\Projects\KtBukkitGui\api\build\libs\api-2.4.1.jar: The process cannot access the file because it is being used by another process
at net.fabricmc.tinyremapper.Main.main(Main.java:267)
Caused by: java.nio.file.FileSystemException: D:\PC\Projects\KtBukkitGui\api\build\libs\api-2.4.1.jar: The process cannot access the file because it is being used by another process
at java.base/sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:92)
at java.base/sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:103)
at java.base/sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:108)
at java.base/sun.nio.fs.WindowsFileSystemProvider.implDelete(WindowsFileSystemProvider.java:275)
at java.base/sun.nio.fs.AbstractFileSystemProvider.delete(AbstractFileSystemProvider.java:105)
at java.base/java.nio.file.Files.delete(Files.java:1152)
at jdk.zipfs/jdk.nio.zipfs.ZipFileSystem.sync(ZipFileSystem.java:1914)
at jdk.zipfs/jdk.nio.zipfs.ZipFileSystem.lambda$close$10(ZipFileSystem.java:494)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:569)
at jdk.zipfs/jdk.nio.zipfs.ZipFileSystem.close(ZipFileSystem.java:493)
at net.fabricmc.tinyremapper.FileSystemReference.close(FileSystemReference.java:131)
at net.fabricmc.tinyremapper.OutputConsumerPath.close(OutputConsumerPath.java:213)
at net.fabricmc.tinyremapper.Main.main(Main.java:266)
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import org.bukkit.permissions.PermissionDefault
import java.time.Duration
import java.util.*
import java.util.function.Consumer
import kotlin.math.exp

open class DeclarativeCommandBuilder(
val name: String
Expand Down Expand Up @@ -192,10 +193,10 @@ open class DeclarativeCommandBuilder(
}

operator fun FlagArgument.unaryPlus() = withFlag(this)
operator fun <T : Any> OptionArgument<T>.unaryPlus() = withOption(this)
operator fun <T : Any> OptionArgument<T>.unaryPlus() = this.apply { withOption(this) }
operator fun <T : Any> Argument<T>.unaryPlus() = OptionArgument(this).unaryPlus()

fun getCurrentCommand(context: SuggestionInvocation<*>): Pair<SuggestionInvocation<*>, DeclarativeCommandBuilder?> {
fun getCurrentCommand(context: StorageCommandContext<*>): Pair<StorageCommandContext<*>, DeclarativeCommandBuilder?> {
val firstArg = context.rawArgs.firstOrNull()
?: return context to this

Expand All @@ -208,7 +209,7 @@ open class DeclarativeCommandBuilder(
return context to this
}

fun getSuggestions(context: SuggestionInvocation<*>): List<String> {
fun getSuggestions(context: StorageCommandContext<*>): List<String> {
val cmds = subcommands
.filter { it.nameStarts(context.last) }
.map { listOf(it.name) + it.aliases }
Expand All @@ -218,7 +219,7 @@ open class DeclarativeCommandBuilder(
val suggestedArgs = arrayListOf(*cmdsList.toTypedArray())

for (arg in expectedArguments) {
val processor = ArgumentProcessor(this, list)
val processor = ArgumentProcessor(this, context, list)
val result = arg.consume(processor)

if (result.isEmpty() && !arg.isRequired()) continue
Expand Down Expand Up @@ -302,14 +303,9 @@ open class DeclarativeCommandBuilder(
}

// Move onto args

val argumentValues = hashMapOf<String, ArgumentContext<*>>()

// var expectedArgumentIndex = 0
// var providedArgumentIndex = 0

val argumentProcessor = ArgumentProcessor(this, context.rawArgs)
println(context.rawArgs)
val argumentProcessor = ArgumentProcessor(this, context, context.rawArgs)
for ((index, arg) in expectedArguments.withIndex()) {
if (argumentProcessor.done()) {
if (arg.isRequired()) {
Expand Down Expand Up @@ -357,6 +353,11 @@ open class DeclarativeCommandBuilder(
}
}

// If there are no args they might be using optionals or flags
if (expectedArguments.isEmpty()) {
argumentProcessor.next()
}

if (!argumentProcessor.done()) {
// Too many args, unknown command maybe?
if (unknownCommand.isPresent) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ class DeclarativeCommandWrapper(
}

override fun tabComplete(sender: CommandSender, alias: String, args: Array<out String>): MutableList<String> {
val context = SuggestionInvocation(Optional.of(sender), alias, args.toList().subList(0, args.size - 1))
val context = StorageCommandContext(sender, alias, args.toList().subList(0, args.size - 1))

val (newContext, finalCommand) = builder.getCurrentCommand(context)
val outArgs = finalCommand?.getSuggestions(newContext)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ open class Argument<T : Any>(
var invalidCallback = EventCallback<InvalidArgContext<*>>()
protected set
private var optional = false
// todo impl default value
private var default: T? = null

init {
withTypeSuggestions()
Expand Down Expand Up @@ -63,6 +63,12 @@ open class Argument<T : Any>(
this.optional = value
}

infix fun defaultValue(default: T) = apply {
this.default = default
}

fun getDefaultValue() = default

infix fun missing(block: InvalidArgContext<*>.() -> Unit) = apply {
this.missingCallback.callbacks.add(block)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,9 @@ fun interface ArgumentConsumer {
infix fun untilPartial(predicate: (ArgumentProcessor, String) -> Boolean) = untilFalsePartial { p, s -> !predicate(p, s) }

@JvmStatic
fun remaining() = untilFalse { processor, _ -> !processor.done() }
fun remaining() = untilFalse { processor, _ ->
!processor.done()
}

@JvmStatic
infix fun variable(amount: Int): ArgumentConsumer {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.mattmx.ktgui.commands.declarative.arg

import org.codehaus.plexus.util.cli.Arg
import java.util.*

class ArgumentContext<T : Any>(
Expand All @@ -22,4 +23,9 @@ class ArgumentContext<T : Any>(
fun asOptional() = value

override fun toString() = getOrNull().toString()

companion object {
fun <T : Any> empty(argument: Argument<T>) =
ArgumentContext(null, Optional.ofNullable(argument.getDefaultValue()), argument)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@ package com.mattmx.ktgui.commands.declarative.arg

import com.mattmx.ktgui.commands.declarative.DeclarativeCommandBuilder
import com.mattmx.ktgui.commands.declarative.arg.impl.*
import com.mattmx.ktgui.commands.declarative.invocation.StorageCommandContext

class ArgumentProcessor(
val command: DeclarativeCommandBuilder,
val context: StorageCommandContext<*>,
val args: List<String>
) {
var pointer = -1
Expand All @@ -18,18 +20,33 @@ class ArgumentProcessor(
while (current().let { it != null && command.optionsSyntax.match(it) }) {
val optionOrPointerId = command.optionsSyntax.removePrefixFrom(current()!!)

if (command.permittedFlags.any { it.chatName() == optionOrPointerId }) {
optionsAndFlagsValues[optionOrPointerId] = true
val flag = command.permittedFlags.firstOrNull { it.chatName() == optionOrPointerId }

if (flag != null) {
val passed = if (flag.requiresCheck.isEmpty) true else flag.requiresCheck.isPresent

if (passed) {
optionsAndFlagsValues[optionOrPointerId] = true
}

pointer++
} else if (command.permittedOptions.any { it.chatName() == optionOrPointerId }) {
} else {
println(command.permittedOptions)
val option = command.permittedOptions.firstOrNull {
it.chatName() == optionOrPointerId
}

if (option != null) {
val passed = if (option.requiresCheck.isEmpty) true else option.requiresCheck.get()(context)

// TODO this should read the argument type args (does that make sense?)
// e.g '--test "hello world"' -> hello world
if (passed) {
val value = peek(1) ?: continue
optionsAndFlagsValues[optionOrPointerId] = value
}

val value = peek(1) ?: continue
optionsAndFlagsValues[optionOrPointerId] = value
pointer += 2
} else break
pointer += 2
} else break
}
}

return current()
Expand All @@ -40,7 +57,7 @@ class ArgumentProcessor(
this.optionsAndFlagsValues.clear()
}

fun clone() = ArgumentProcessor(command, args).apply {
fun clone() = ArgumentProcessor(command, context, args).apply {
this.optionsAndFlagsValues = this@ArgumentProcessor.optionsAndFlagsValues
this.pointer = this@ArgumentProcessor.pointer
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,24 @@ package com.mattmx.ktgui.commands.declarative.arg.impl
import com.mattmx.ktgui.commands.declarative.DeclarativeCommandBuilder
import com.mattmx.ktgui.commands.declarative.arg.Argument
import com.mattmx.ktgui.commands.declarative.invocation.BaseCommandContext
import com.mattmx.ktgui.commands.declarative.invocation.RunnableCommandContext
import com.mattmx.ktgui.commands.declarative.invocation.StorageCommandContext
import java.util.*

class FlagArgument(
name: String
) : Argument<Boolean>(name, "boolean") {
// todo command auto builder permissions node
var requiresCheck = Optional.empty<(StorageCommandContext<*>) -> Boolean>()
var showsInSuggestions = true

infix fun requires(context: StorageCommandContext<*>.() -> Boolean) = apply {
this.requiresCheck = Optional.of(context)
}

infix fun requiresPermission(node: String) = requires {
sender.hasPermission(node)
}

fun chatName() = name().replace("_", "-")

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,23 +8,22 @@ import com.mattmx.ktgui.commands.declarative.invocation.BaseCommandContext

class MultiChoiceArgument<T : Any>(
name: String,
initialChoices: HashMap<String, T>
initialChoices: () -> HashMap<String, T>
) : Argument<T>(name, "multi-choice") {
private val choices = initialChoices
private val choices: () -> HashMap<String, T> = initialChoices

init {
this.consumes(
ArgumentConsumer.until { argumentProcessor, s ->
println("processing op '$s'")
choices.containsKey(s)
choices().containsKey(s)
}
)
suggests { choices.keys.toList() }
suggests { choices().keys.toList() }
}

override fun getValueOfString(
cmd: DeclarativeCommandBuilder,
context: BaseCommandContext<*>,
stringValue: String?
) = choices[stringValue]
) = choices()[stringValue]
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,30 @@
package com.mattmx.ktgui.commands.declarative.arg.impl

import com.mattmx.ktgui.commands.declarative.arg.Argument
import com.mattmx.ktgui.commands.declarative.invocation.RunnableCommandContext
import com.mattmx.ktgui.commands.declarative.invocation.StorageCommandContext
import java.util.Optional

class OptionArgument<T : Any>(
val sub: Argument<T>
) {
// todo command auto builder permissions node
var requiresCheck = Optional.empty<(StorageCommandContext<*>) -> Boolean>()
private set
var shownInSuggestions = true
private set

infix fun requires(context: StorageCommandContext<*>.() -> Boolean) = apply {
this.requiresCheck = Optional.of(context)
}

infix fun requiresPermission(node: String) = requires {
sender.hasPermission(node)
}

infix fun shownInSuggestions(value: Boolean) = apply {
this.shownInSuggestions = value
}

fun chatName() = sub.name().replace("_", "-")
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ class StringArgument(
val range = (min..max)

val matchesRange = stringValue.length in range
val matchesAllowed = allowed.any { it.matches(stringValue) }
val matchesAllowed = allowed.all { it.matches(stringValue) }
val meetsDisallowed = disallow.none { it.matches(stringValue) }

val all = matchesRange && matchesAllowed && meetsDisallowed
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package com.mattmx.ktgui.commands.declarative.arg.impl

import com.mattmx.ktgui.commands.declarative.arg.Argument
import com.mattmx.ktgui.commands.declarative.arg.ArgumentConsumer
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty

Expand Down Expand Up @@ -48,7 +47,10 @@ inline fun <reified E : Enum<E>> enumArgument(type: String = E::class.java.simpl
fun flag() = delegateArgument(FlagArgument(DELEGATED_ARG_NAME))

fun <T : Any> multiChoiceArgument(vararg choices: Pair<String, T>) =
delegateArgument(MultiChoiceArgument(DELEGATED_ARG_NAME, hashMapOf(*choices)))
delegateArgument(MultiChoiceArgument(DELEGATED_ARG_NAME) { hashMapOf(*choices) })

fun <T : Any> multiChoiceArgument(choiceSupplier: () -> HashMap<String, T>) =
delegateArgument(MultiChoiceArgument(DELEGATED_ARG_NAME) { choiceSupplier() })

fun <T : Any> simpleMappedArgument() =
delegateArgument(SimpleArgument<T>(DELEGATED_ARG_NAME, "type"))
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ class RunnableCommandContext<T : CommandSender>(

val <S : Any> Argument<S>.context: ArgumentContext<S>
get() = getArgumentContext(name())
?: error("The argument ${name()} is not available in this command context.")
?: ArgumentContext.empty(this)

operator fun <S : Any> Argument<S>.invoke(): S {
val ctx = context
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ open class StorageCommandContext<T : CommandSender>(
rawArgs: List<String>
) : BaseCommandContext<T>(sender, alias, rawArgs) {
val storage = hashMapOf<String, Any?>()
val last: String
get() = rawArgs.lastOrNull() ?: ""

override fun clone(newList: List<String>): StorageCommandContext<T> {
return StorageCommandContext(sender, alias, newList)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
package com.mattmx.ktgui.commands.suggestions

import com.mattmx.ktgui.commands.declarative.invocation.SuggestionInvocation
import com.mattmx.ktgui.commands.declarative.invocation.StorageCommandContext

fun interface CommandSuggestion<V> {
fun getSuggestion(invocation: SuggestionInvocation<*>): Collection<String>?
fun getSuggestion(invocation: StorageCommandContext<*>): Collection<String>?

fun getLastArgSuggestion(invocation: SuggestionInvocation<*>) = getSuggestion(invocation)
fun getLastArgSuggestion(invocation: StorageCommandContext<*>) = getSuggestion(invocation)
?.filter { it.startsWith((invocation.rawArgs.lastOrNull() ?: ""), true) }

fun getValue(argumentString: String?) : V? {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.mattmx.ktgui.commands.suggestions

import com.mattmx.ktgui.commands.declarative.invocation.StorageCommandContext
import com.mattmx.ktgui.commands.declarative.invocation.SuggestionInvocation
import kotlin.reflect.KProperty
import kotlin.reflect.jvm.javaMethod
Expand All @@ -9,7 +10,7 @@ open class SimpleCommandSuggestion<V, F>(
val list: () -> List<V>
) : CommandSuggestion<V> {

override fun getSuggestion(invocation: SuggestionInvocation<*>): List<String>? {
override fun getSuggestion(invocation: StorageCommandContext<*>): List<String>? {
val list = list()

return list.map { obj -> field.getter.javaMethod?.invoke(obj).toString() }
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
package com.mattmx.ktgui.commands.suggestions.impl

import com.mattmx.ktgui.commands.declarative.invocation.StorageCommandContext
import com.mattmx.ktgui.commands.declarative.invocation.SuggestionInvocation
import com.mattmx.ktgui.commands.suggestions.CommandSuggestion
import org.bukkit.Material

class MaterialCommandSuggestion : CommandSuggestion<Material> {
override fun getSuggestion(invocation: SuggestionInvocation<*>): List<String> {
override fun getSuggestion(invocation: StorageCommandContext<*>): List<String> {
return Material.values().map { it.key.toString() }
}

Expand Down
Loading

0 comments on commit 52ef299

Please sign in to comment.