feat(game): support quoted arguments in chat commands (#154)

Co-authored-by: Fiereu <contact@fiereu.de>
This commit is contained in:
calebriscandFiereu authored and GitHub committed 2026-08-10 19:14:25 +02:00
1 parent aba1226794
commit 0385dc8dcf
3 files changed
+74 -2

No files matched your search

@@ -28,8 +28,7 @@ constructor(
val text = message.trim()
if (!text.startsWith(PREFIX)) return false
// TODO: Support quoted arguments, for a command that takes a name with a space in it.
val parts = text.drop(1).split(Regex("\\s+")).filter { it.isNotEmpty() }
val parts = tokenizeCommandLine(text.drop(1))
val name = parts.firstOrNull()?.lowercase()
if (name == null) {
session.send(notice("Type /help to see what you can run."))
@@ -0,0 +1,39 @@
package de.fiereu.openmmo.server.game.services.command
/**
* Splits a command line into arguments. Runs of whitespace separate arguments, double quotes group
* words into one argument (`give "Great Ball" 5` -> `give`, `Great Ball`, `5`), and a backslash
* escapes the next character inside quotes. An unterminated quote takes the rest of the line.
*/
internal fun tokenizeCommandLine(line: String): List<String> {
val args = mutableListOf<String>()
val current = StringBuilder()
var inQuotes = false
var hasToken = false
var i = 0
while (i < line.length) {
val c = line[i]
when {
inQuotes && c == '\\' && i + 1 < line.length -> {
current.append(line[i + 1])
i++
}
c == '"' -> {
inQuotes = !inQuotes
hasToken = true
}
!inQuotes && c.isWhitespace() -> {
if (hasToken) args += current.toString()
current.clear()
hasToken = false
}
else -> {
current.append(c)
hasToken = true
}
}
i++
}
if (hasToken) args += current.toString()
return args
}
@@ -0,0 +1,34 @@
package de.fiereu.openmmo.server.game.services.command
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
class CommandTokenizerTest :
FunSpec({
test("splits plain arguments on whitespace runs") {
tokenizeCommandLine("give potion 5") shouldBe listOf("give", "potion", "5")
}
test("keeps a quoted argument together") {
tokenizeCommandLine("give \"Great Ball\" 5") shouldBe listOf("give", "Great Ball", "5")
}
test("joins a quote that starts mid-word") {
tokenizeCommandLine("whisper Nurse\" Joy\" hi") shouldBe
listOf("whisper", "Nurse Joy", "hi")
}
test("escapes a quote inside quotes") {
tokenizeCommandLine("say \"a \\\" mark\"") shouldBe listOf("say", "a \" mark")
}
test("an unterminated quote takes the rest of the line") {
tokenizeCommandLine("find \"Mr. Mime forever") shouldBe listOf("find", "Mr. Mime forever")
}
test("empty quotes make an empty argument") {
tokenizeCommandLine("rename \"\" after") shouldBe listOf("rename", "", "after")
}
test("empty line has no arguments") { tokenizeCommandLine("") shouldBe emptyList() }
})