From 341e271bd0a9193ac3a4ebd05cacc39b45dc5a6e Mon Sep 17 00:00:00 2001 From: BadgersMC Date: Mon, 16 Nov 2026 21:48:49 -0500 Subject: [PATCH 1/2] feat(paper): compose shared command roots and support ACF migration arguments --- docs/paper-command-composition.md | 46 ++++ .../paper/commands/PaperCommandDefinition.kt | 9 +- .../paper/commands/PaperCommandPlanner.kt | 54 ++++ .../paper/commands/PaperCommandRegistry.kt | 256 +++++++++++------- .../paper/commands/PaperCommandScanner.kt | 45 ++- .../paper/commands/annotations/Greedy.kt | 6 + .../fixtures/invalid/InvalidGreedyFixture.kt | 13 + .../commands/PaperCommandCompositionTest.kt | 90 ++++++ 8 files changed, 405 insertions(+), 114 deletions(-) create mode 100644 docs/paper-command-composition.md create mode 100644 nexus-paper/src/main/kotlin/net/badgersmc/nexus/paper/commands/PaperCommandPlanner.kt create mode 100644 nexus-paper/src/main/kotlin/net/badgersmc/nexus/paper/commands/annotations/Greedy.kt create mode 100644 nexus-paper/src/test/kotlin/fixtures/invalid/InvalidGreedyFixture.kt create mode 100644 nexus-paper/src/test/kotlin/net/badgersmc/nexus/paper/commands/PaperCommandCompositionTest.kt diff --git a/docs/paper-command-composition.md b/docs/paper-command-composition.md new file mode 100644 index 0000000..86e8543 --- /dev/null +++ b/docs/paper-command-composition.md @@ -0,0 +1,46 @@ +# Paper command composition (LumaGuilds migration prerequisites) + +The `nexus-paper` command adapter groups classes with the same `@Command(name = "...")` into one Brigadier root tree. This supports splitting a large command into independently injectable, independently reviewable command classes without duplicating registration for the same literal. + +## Example + +```kotlin +@Command(name = "guild", aliases = ["g"]) +class GuildRoot(private val menus: GuildMenus) { + @Subcommand("") // /guild and /g + fun menu(@Context player: Player) = menus.open(player) +} + +@Command(name = "guild", aliases = ["g"]) +class GuildHomes(private val homes: GuildHomeService) { + @Subcommand("home") // /guild home [name] + @Permission("guild.home") + fun home( + @Context player: Player, + @Arg("name", required = false) name: String = "main" + ) = homes.teleport(player, name) + + @Subcommand("announce") + fun announce(@Context player: Player, @Arg("message") @Greedy message: String) { + // `message` includes whitespace through end of input. + } +} +``` + +## Rules + +- Repeated root names are composed into one registration and aliases are deduplicated; different root permissions or descriptions are rejected. +- Two handlers cannot claim the same literal path, including the empty root/default path; errors occur before the Paper lifecycle registration event. +- Nested literals share parents; child and parent permissions remain separate. Prefix visibility is permitted if any descendant is permitted; executing a route always checks its own permission and player-only requirement. +- `@Subcommand("")` denotes the root/default handler (not ACF's `@Default`). +- `@Arg(required = false)` and `@Arg(defaultValue = "...")` produce executable shorter Brigadier paths. Optional args must be trailing. Omitted arguments use the annotation default, the Kotlin parameter default, or `null` if nullable. Non-null optional parameters without either default are rejected by scanning. +- `@Greedy` is valid only on the final String `@Arg`; useful for guild chat and announcements. +- `@Suggests("providerName")` still resolves from the `suggestionProviders` map supplied to `registerPaperCommands()`. +- `@Arg("name")` supplies the Brigadier argument name even when the Kotlin parameter identifier differs. +- These are Nexus annotations, not drop-in ACF annotations. Migrate source deliberately, retaining command aliases, permissions and completion contracts. + +## Boundaries + +This is **command infrastructure only**, not the LumaGuilds migration. The existing NexusContext DI and lifecycle APIs remain unchanged. Large ACF command suites need a command-by-command parity inventory: syntax, optional/greedy arguments, async/main-thread constraints, player-only behavior, command help, and completions. Remaining ACF features (such as `@Conditions`, custom contexts, or automated help) must be implemented or deliberately rewritten before removal. + +Run `./gradlew :nexus-paper:test` on JDK 25. Do not publish a Nexus version until CI and the LumaGuilds command parity review pass. diff --git a/nexus-paper/src/main/kotlin/net/badgersmc/nexus/paper/commands/PaperCommandDefinition.kt b/nexus-paper/src/main/kotlin/net/badgersmc/nexus/paper/commands/PaperCommandDefinition.kt index 38a9259..d50e9d8 100644 --- a/nexus-paper/src/main/kotlin/net/badgersmc/nexus/paper/commands/PaperCommandDefinition.kt +++ b/nexus-paper/src/main/kotlin/net/badgersmc/nexus/paper/commands/PaperCommandDefinition.kt @@ -5,22 +5,21 @@ import net.badgersmc.nexus.commands.annotations.Command import kotlin.reflect.KClass import kotlin.reflect.KFunction -/** Full metadata for a root command discovered via classpath scanning. */ +/** Full metadata for a command handler discovered via classpath scanning. */ data class PaperCommandDefinition( val commandClass: KClass<*>, val annotation: Command, val subcommands: List ) -/** Metadata for a single @Subcommand method. */ +/** Metadata for one @Subcommand method. An empty path is the root/default handler. */ data class PaperSubcommandDefinition( - /** Path segments — e.g., ["admin", "setup"] for @Subcommand("admin setup") */ val path: List, val method: KFunction<*>, val parameters: List, val permission: String?, val isPlayerOnly: Boolean, val isAsync: Boolean, - /** Maps parameter names to suggestion provider names (from @Suggests). */ - val suggestions: Map = emptyMap() + val suggestions: Map = emptyMap(), + val greedyParameters: Set = emptySet() ) diff --git a/nexus-paper/src/main/kotlin/net/badgersmc/nexus/paper/commands/PaperCommandPlanner.kt b/nexus-paper/src/main/kotlin/net/badgersmc/nexus/paper/commands/PaperCommandPlanner.kt new file mode 100644 index 0000000..5f63d6a --- /dev/null +++ b/nexus-paper/src/main/kotlin/net/badgersmc/nexus/paper/commands/PaperCommandPlanner.kt @@ -0,0 +1,54 @@ +package net.badgersmc.nexus.paper.commands + +import net.badgersmc.nexus.commands.CommandException + +/** + * Groups command classes by their shared Brigadier root, without changing the public + * @Command API. An ACF-style split can therefore define /guild subcommands in + * independent classes without registering competing root command trees. + */ +internal object PaperCommandPlanner { + data class Root( + val name: String, + val description: String, + val permission: String, + val aliases: List, + val definitions: List + ) + + fun plan(definitions: List): List { + val roots = definitions.groupBy { it.annotation.name.lowercase() } + val occupiedNames = mutableMapOf() + return roots.map { (name, group) -> + val permissions = group.map { it.annotation.permission }.distinct() + if (permissions.size != 1) { + throw CommandException("Conflicting root permissions for /$name: $permissions") + } + val descriptions = group.map { it.annotation.description }.filter { it.isNotBlank() }.distinct() + if (descriptions.size > 1) { + throw CommandException("Conflicting root descriptions for /$name: $descriptions") + } + val paths = mutableMapOf() + group.forEach { definition -> + definition.subcommands.forEach { sub -> + val path = sub.path.joinToString(" ").lowercase() + val owner = "${definition.commandClass.simpleName}::${sub.method.name}" + val previous = paths.putIfAbsent(path, owner) + if (previous != null) { + throw CommandException("Duplicate /$name $path handlers: $previous and $owner") + } + } + } + val aliases = group.flatMap { it.annotation.aliases.toList() } + .filterNot { it.equals(name, ignoreCase = true) } + .distinctBy { it.lowercase() } + (listOf(name) + aliases).forEach { alias -> + val previous = occupiedNames.putIfAbsent(alias.lowercase(), name) + if (previous != null && previous != name) { + throw CommandException("Command alias '$alias' conflicts between /$previous and /$name") + } + } + Root(name, descriptions.firstOrNull() ?: "", permissions.single(), aliases, group) + } + } +} diff --git a/nexus-paper/src/main/kotlin/net/badgersmc/nexus/paper/commands/PaperCommandRegistry.kt b/nexus-paper/src/main/kotlin/net/badgersmc/nexus/paper/commands/PaperCommandRegistry.kt index 9d8c91b..8067871 100644 --- a/nexus-paper/src/main/kotlin/net/badgersmc/nexus/paper/commands/PaperCommandRegistry.kt +++ b/nexus-paper/src/main/kotlin/net/badgersmc/nexus/paper/commands/PaperCommandRegistry.kt @@ -1,7 +1,7 @@ package net.badgersmc.nexus.paper.commands import com.mojang.brigadier.Command -import com.mojang.brigadier.builder.ArgumentBuilder +import com.mojang.brigadier.arguments.StringArgumentType import com.mojang.brigadier.builder.LiteralArgumentBuilder import com.mojang.brigadier.context.CommandContext import com.mojang.brigadier.suggestion.SuggestionProvider @@ -17,7 +17,9 @@ import net.badgersmc.nexus.paper.commands.arguments.PaperArgumentResolvers import org.bukkit.entity.Player import org.bukkit.plugin.java.JavaPlugin import org.slf4j.LoggerFactory -import kotlin.reflect.full.callSuspend +import kotlin.reflect.KClass +import kotlin.reflect.KParameter +import kotlin.reflect.full.callSuspendBy class PaperCommandRegistry( private val plugin: JavaPlugin, @@ -27,157 +29,207 @@ class PaperCommandRegistry( ) { private val logger = LoggerFactory.getLogger(PaperCommandRegistry::class.java) + private data class Route(val metadata: PaperSubcommandDefinition, val bean: Any) + private class LiteralNode(val name: String) { + val children = linkedMapOf() + var handler: Route? = null + + fun reachableRoutes(): List = + listOfNotNull(handler) + children.values.flatMap { it.reachableRoutes() } + } + fun registerAll(definitions: List) { + val plans = PaperCommandPlanner.plan(definitions) // fail before registering the lifecycle callback plugin.lifecycleManager.registerEventHandler(LifecycleEvents.COMMANDS) { event -> - for (def in definitions) { + for (plan in plans) { try { - val bean = beanFactory.createFactory(def.commandClass).invoke() - val tree = buildCommandTree(def, bean) - event.registrar().register( - tree, - def.annotation.description, - def.annotation.aliases.toList() - ) - logger.debug("Registered Paper command '/{}'", def.annotation.name) + val handlers = plan.definitions.map { definition -> + val bean = beanFactory.createFactory(definition.commandClass).invoke() + definition.subcommands.map { Route(it, bean) } + }.flatten() + val tree = buildCommandTree(plan, handlers) + event.registrar().register(tree, plan.description, plan.aliases) + logger.debug("Registered Paper command '/{}' with {} handlers", plan.name, handlers.size) } catch (e: Exception) { - logger.error("Failed to register command '${def.annotation.name}'", e) + logger.error("Failed to register command '${plan.name}'", e) throw CommandException("Command registration failed: ${e.message}", e) } } - logger.info("Registered {} Paper commands", definitions.size) + logger.info("Registered {} Paper command roots from {} classes", plans.size, definitions.size) } } private fun buildCommandTree( - def: PaperCommandDefinition, - bean: Any + plan: PaperCommandPlanner.Root, + routes: List ): LiteralCommandNode { - val root = Commands.literal(def.annotation.name) - - if (def.annotation.permission.isNotEmpty()) { - root.requires { it.sender.hasPermission(def.annotation.permission) } + val root = Commands.literal(plan.name) + if (plan.permission.isNotEmpty()) { + root.requires { it.sender.hasPermission(plan.permission) } } - for (sub in def.subcommands) { - attachSubcommand(root, sub, bean) + val nodes = linkedMapOf() + routes.forEach { route -> + if (route.metadata.path.isEmpty()) { + root.executes { ctx -> runRoute(ctx, route) } + } else { + var current = nodes.getOrPut(route.metadata.path[0]) { LiteralNode(route.metadata.path[0]) } + route.metadata.path.drop(1).forEach { literal -> + current = current.children.getOrPut(literal) { LiteralNode(literal) } + } + current.handler = route + } } - + nodes.values.forEach { node -> root.then(buildLiteral(node)) } return root.build() } - private fun attachSubcommand( - root: LiteralArgumentBuilder, - sub: PaperSubcommandDefinition, - bean: Any + private fun buildLiteral(node: LiteralNode): LiteralArgumentBuilder { + val builder = Commands.literal(node.name) + // Shared intermediate nodes must remain reachable for any authorized descendant. + // Individual handlers still verify their own permission before invocation. + val routes = node.reachableRoutes() + builder.requires { source -> routes.any { allowed(source, it.metadata) } } + node.handler?.let { attachArguments(builder, it) } + node.children.values.forEach { child -> builder.then(buildLiteral(child)) } + return builder + } + + private fun attachArguments( + literal: LiteralArgumentBuilder, + route: Route ) { - // Build EVERYTHING bottom-up: Brigadier's then() calls build() immediately on the child, - // so adding children to a builder AFTER it was passed to then() has no effect on the - // already-built node. This applies to literal path segments too, not just args — a prior - // top-down loop over path segments silently dropped argument children of multi-segment - // subcommands like @Subcommand("auction start"). - - val argParams = sub.parameters.filter { it.isArg } - val argBuilders = argParams.map { param -> + val args = route.metadata.parameters.filter { it.isArg } + val builders = args.map { param -> val resolver = PaperArgumentResolvers.get(param.type) ?: throw CommandException("No resolver for ${param.type.simpleName}") - val builder = Commands.argument(param.name, resolver.argumentType()) - val providerName = sub.suggestions[param.name] - if (providerName != null) { + val type = if (param.name in route.metadata.greedyParameters) { + StringArgumentType.greedyString() + } else { + resolver.argumentType() + } + @Suppress("UNCHECKED_CAST") + val builder = Commands.argument(param.name, type as com.mojang.brigadier.arguments.ArgumentType) + route.metadata.suggestions[param.name]?.let { providerName -> val provider = suggestionProviders[providerName] - ?: throw CommandException( - "No suggestion provider '$providerName' registered " + - "(referenced by @Suggests on parameter '${param.name}')" - ) + ?: throw CommandException("No suggestion provider '$providerName' for '${param.name}'") builder.suggests(provider) } builder } - // Build literal path bottom-up. The deepest literal carries requires + executes (or the - // first arg). Each parent literal is built fresh and gets its child via then(). - val literalBuilders = sub.path.map { Commands.literal(it) } - val deepest = literalBuilders.last() - - val permission = sub.permission - deepest.requires { source -> - (permission == null || source.sender.hasPermission(permission)) && - (!sub.isPlayerOnly || source.sender is Player) + if (builders.isEmpty()) { + literal.executes { ctx -> runRoute(ctx, route) } + return } - if (argBuilders.isNotEmpty()) { - argBuilders.last().executes { ctx -> - executeSubcommand(ctx, sub, bean) - Command.SINGLE_SUCCESS - } - for (i in argBuilders.size - 2 downTo 0) { - argBuilders[i].then(argBuilders[i + 1]) - } - deepest.then(argBuilders.first()) - } else { - deepest.executes { ctx -> - executeSubcommand(ctx, sub, bean) - Command.SINGLE_SUCCESS + // Optional trailing arguments add executable prefixes, including the literal + // itself when every @Arg is optional. + if (args.all { it.isOptional }) { + literal.executes { ctx -> runRoute(ctx, route) } + } + for (i in builders.indices) { + if (i == builders.lastIndex || args.drop(i + 1).all { it.isOptional }) { + builders[i].executes { ctx -> runRoute(ctx, route) } } } - - // Chain literals bottom-up. - for (i in literalBuilders.size - 2 downTo 0) { - literalBuilders[i].then(literalBuilders[i + 1]) + for (i in builders.size - 2 downTo 0) { + builders[i].then(builders[i + 1]) } - - root.then(literalBuilders.first()) + builders.first().requires { source -> allowed(source, route.metadata) } + literal.then(builders.first()) } - private fun executeSubcommand( - ctx: CommandContext, - sub: PaperSubcommandDefinition, - bean: Any - ) { - val source = ctx.source - val params = buildParams(ctx, sub, source) + private fun allowed(source: CommandSourceStack, sub: PaperSubcommandDefinition): Boolean = + (sub.permission == null || source.sender.hasPermission(sub.permission)) && + (!sub.isPlayerOnly || source.sender is Player) + + private fun runRoute(ctx: CommandContext, route: Route): Int { + if (!allowed(ctx.source, route.metadata)) { + ctx.source.sender.sendMessage("You do not have permission to use this command.") + return 0 + } + val sub = route.metadata if (sub.isAsync) { nexusScope.launch { try { - if (sub.method.isSuspend) { - sub.method.callSuspend(bean, *params) - } else { - sub.method.call(bean, *params) - } + invoke(ctx, route) } catch (e: Exception) { logger.error("Async command '${sub.path}' failed", e) } } } else { try { - sub.method.call(bean, *params) + // A suspend method is marked async by the scanner. + invokeSync(ctx, route) } catch (e: Exception) { logger.error("Command '${sub.path}' failed", e) + return 0 } } + return Command.SINGLE_SUCCESS } - private fun buildParams( + private fun argumentValues( ctx: CommandContext, - sub: PaperSubcommandDefinition, - source: CommandSourceStack - ): Array = sub.parameters.map { param -> - when { - param.isArg -> { - val resolver = PaperArgumentResolvers.get(param.type)!! - resolver.extract(ctx, param.name) - } - param.isContext -> when (param.type.simpleName) { - "CommandSourceStack" -> source - "Player" -> source.sender as? Player - ?: throw CommandException("Command requires a player sender") - "CommandSender" -> source.sender - "Server" -> source.sender.server - else -> throw CommandException( - "Unsupported @Context type '${param.type.simpleName}'" - ) + route: Route + ): Map { + val sub = route.metadata + val method = sub.method + val values = linkedMapOf(method.parameters.first() to route.bean) + sub.parameters.forEachIndexed { index, param -> + val reflected = method.parameters[index + 1] + when { + param.isContext -> values[reflected] = when (param.type.simpleName) { + "CommandSourceStack" -> ctx.source + "Player" -> ctx.source.sender as? Player + ?: throw CommandException("Command requires a player sender") + "CommandSender" -> ctx.source.sender + "Server" -> ctx.source.sender.server + else -> throw CommandException("Unsupported @Context type '${param.type.simpleName}'") + } + param.isArg && hasArgument(ctx, param.name) -> { + val resolver = PaperArgumentResolvers.get(param.type) + ?: throw CommandException("No resolver for ${param.type.simpleName}") + values[reflected] = resolver.extract(ctx, param.name) + } + param.isArg && !param.argAnnotation?.defaultValue.isNullOrEmpty() -> { + values[reflected] = parseDefault(param.type, param.argAnnotation!!.defaultValue) + } + param.isArg && reflected.isOptional -> Unit // Kotlin callBy applies method default + param.isArg && reflected.type.isMarkedNullable -> values[reflected] = null + else -> throw CommandException("Missing required argument '${param.name}'") } - else -> throw CommandException("Parameter '${param.name}' has no annotation") } - }.toTypedArray() + return values + } + + private fun hasArgument(ctx: CommandContext, name: String): Boolean = + try { + ctx.getArgument(name, Any::class.java) + true + } catch (_: IllegalArgumentException) { + false + } + + private fun parseDefault(type: KClass<*>, value: String): Any = when (type) { + String::class -> value + Int::class -> value.toInt() + Long::class -> value.toLong() + Double::class -> value.toDouble() + Float::class -> value.toFloat() + Boolean::class -> value.toBooleanStrict() + else -> throw CommandException("Unsupported default value type: ${type.simpleName}") + } + + private fun invokeSync(ctx: CommandContext, route: Route) { + route.metadata.method.callBy(argumentValues(ctx, route)) + } + + private suspend fun invoke(ctx: CommandContext, route: Route) { + val values = argumentValues(ctx, route) + if (route.metadata.method.isSuspend) route.metadata.method.callSuspendBy(values) + else route.metadata.method.callBy(values) + } } diff --git a/nexus-paper/src/main/kotlin/net/badgersmc/nexus/paper/commands/PaperCommandScanner.kt b/nexus-paper/src/main/kotlin/net/badgersmc/nexus/paper/commands/PaperCommandScanner.kt index 1f815be..0b59bb6 100644 --- a/nexus-paper/src/main/kotlin/net/badgersmc/nexus/paper/commands/PaperCommandScanner.kt +++ b/nexus-paper/src/main/kotlin/net/badgersmc/nexus/paper/commands/PaperCommandScanner.kt @@ -7,6 +7,7 @@ import net.badgersmc.nexus.commands.annotations.Arg import net.badgersmc.nexus.commands.annotations.Command import net.badgersmc.nexus.commands.annotations.Context import net.badgersmc.nexus.paper.commands.annotations.Async +import net.badgersmc.nexus.paper.commands.annotations.Greedy import net.badgersmc.nexus.paper.commands.annotations.Permission import net.badgersmc.nexus.paper.commands.annotations.PlayerOnly import net.badgersmc.nexus.paper.commands.annotations.Subcommand @@ -34,11 +35,11 @@ class PaperCommandScanner { } return commandClasses.map { processClass(it) }.also { list -> - logger.info("Discovered {} Paper commands in package '{}'", list.size, basePackage) + logger.info("Discovered {} Paper command classes in package '{}'", list.size, basePackage) } } - private fun processClass(klass: KClass<*>): PaperCommandDefinition { + internal fun processClass(klass: KClass<*>): PaperCommandDefinition { val annotation = klass.findAnnotation() ?: throw CommandException("Class ${klass.simpleName} missing @Command") @@ -46,6 +47,7 @@ class PaperCommandScanner { .filter { it.hasAnnotation() } .map { method -> val subAnnotation = method.findAnnotation()!! + // Empty @Subcommand("") is the root/default route. val path = subAnnotation.value.trim().split(" ").filter { it.isNotEmpty() } val permission = method.findAnnotation()?.value ?: annotation.permission.ifEmpty { null } @@ -53,12 +55,40 @@ class PaperCommandScanner { val isAsync = method.hasAnnotation() || method.isSuspend val suggestionsMap = mutableMapOf() - val parameters = method.parameters.drop(1) // skip 'this' + val greedyParameters = mutableSetOf() + val parameters = method.parameters.drop(1) .mapIndexed { idx, param -> - buildParameter(klass, method, param, idx, suggestionsMap) + val result = buildParameter(klass, method, param, idx, suggestionsMap) + if (param.hasAnnotation()) { + if (!result.isArg || result.type != String::class) { + throw CommandException("@Greedy requires a String @Arg in ${klass.simpleName}::${method.name}") + } + greedyParameters.add(result.name) + } + result } + val args = parameters.filter { it.isArg } + if (args.dropLast(1).any { it.name in greedyParameters }) { + throw CommandException("@Greedy must be the final @Arg in ${klass.simpleName}::${method.name}") + } + if (args.dropLastWhile { it.isOptional }.any { it.isOptional }) { + throw CommandException("Required @Arg after optional @Arg in ${klass.simpleName}::${method.name}") + } + // Non-null optional parameters without a Kotlin default or annotation default + // cannot be invoked when Brigadier omits that argument. + parameters.forEachIndexed { index, parameter -> + val reflected = method.parameters[index + 1] + if (parameter.isOptional && !reflected.isOptional && !reflected.type.isMarkedNullable + && parameter.argAnnotation?.defaultValue.isNullOrEmpty() + ) { + throw CommandException("Optional '${parameter.name}' needs a Kotlin default, nullable type or @Arg defaultValue") + } + } - PaperSubcommandDefinition(path, method, parameters, permission, isPlayerOnly, isAsync, suggestionsMap) + PaperSubcommandDefinition( + path, method, parameters, permission, isPlayerOnly, isAsync, + suggestionsMap, greedyParameters + ) } if (subcommands.isEmpty()) throw CommandException( @@ -87,11 +117,12 @@ class PaperCommandScanner { "in ${klass.simpleName}::${method.name}" ) } + val name = arg?.name?.takeIf { it.isNotBlank() } ?: param.name ?: "param$idx" if (suggests != null && arg != null) { - suggestionsMap[param.name ?: "param$idx"] = suggests.value + suggestionsMap[name] = suggests.value } return CommandParameter( - name = param.name ?: "param$idx", + name = name, type = param.type.classifier as KClass<*>, index = idx, argAnnotation = arg, diff --git a/nexus-paper/src/main/kotlin/net/badgersmc/nexus/paper/commands/annotations/Greedy.kt b/nexus-paper/src/main/kotlin/net/badgersmc/nexus/paper/commands/annotations/Greedy.kt new file mode 100644 index 0000000..7b45c04 --- /dev/null +++ b/nexus-paper/src/main/kotlin/net/badgersmc/nexus/paper/commands/annotations/Greedy.kt @@ -0,0 +1,6 @@ +package net.badgersmc.nexus.paper.commands.annotations + +/** Captures the rest of the command line as a single String argument. Must be the final @Arg. */ +@Target(AnnotationTarget.VALUE_PARAMETER) +@Retention(AnnotationRetention.RUNTIME) +annotation class Greedy diff --git a/nexus-paper/src/test/kotlin/fixtures/invalid/InvalidGreedyFixture.kt b/nexus-paper/src/test/kotlin/fixtures/invalid/InvalidGreedyFixture.kt new file mode 100644 index 0000000..526147b --- /dev/null +++ b/nexus-paper/src/test/kotlin/fixtures/invalid/InvalidGreedyFixture.kt @@ -0,0 +1,13 @@ +package fixtures.invalid + +import net.badgersmc.nexus.commands.annotations.Arg +import net.badgersmc.nexus.commands.annotations.Command +import net.badgersmc.nexus.paper.commands.annotations.Greedy +import net.badgersmc.nexus.paper.commands.annotations.Subcommand + +@Suppress("UnusedParameter", "EmptyFunctionBlock") +@Command(name = "invalid-greedy") +class InvalidGreedyFixture { + @Subcommand("send") + fun send(@Arg("text") @Greedy text: String, @Arg("extra") extra: String) {} +} diff --git a/nexus-paper/src/test/kotlin/net/badgersmc/nexus/paper/commands/PaperCommandCompositionTest.kt b/nexus-paper/src/test/kotlin/net/badgersmc/nexus/paper/commands/PaperCommandCompositionTest.kt new file mode 100644 index 0000000..42ee3df --- /dev/null +++ b/nexus-paper/src/test/kotlin/net/badgersmc/nexus/paper/commands/PaperCommandCompositionTest.kt @@ -0,0 +1,90 @@ +package net.badgersmc.nexus.paper.commands + +import net.badgersmc.nexus.commands.CommandException +import net.badgersmc.nexus.commands.annotations.Arg +import net.badgersmc.nexus.commands.annotations.Command +import net.badgersmc.nexus.paper.commands.annotations.Greedy +import net.badgersmc.nexus.paper.commands.annotations.Permission +import net.badgersmc.nexus.paper.commands.annotations.Subcommand +import fixtures.invalid.InvalidGreedyFixture +import org.junit.jupiter.api.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertNotNull +import kotlin.test.assertTrue + +@Suppress("UnusedParameter", "EmptyFunctionBlock") +@Command(name = "guild", aliases = ["g"]) +class GuildRootFixture { + @Subcommand("") + fun menu() {} + + @Subcommand("help") + fun help() {} +} + +@Suppress("UnusedParameter", "EmptyFunctionBlock") +@Command(name = "guild", aliases = ["g"]) +class GuildHomeFixture { + @Subcommand("home") + @Permission("guild.home") + fun home(@Arg("name", required = false) name: String = "main") {} + + @Subcommand("home activate") + fun activate(@Arg("name") name: String) {} + + @Subcommand("lookup") + fun lookup(@Arg("guildName") suppliedName: String) {} + + @Subcommand("announce") + fun announce(@Arg("message") @Greedy message: String) {} +} + +class PaperCommandCompositionTest { + private val scanner = PaperCommandScanner() + private val loader = GuildRootFixture::class.java.classLoader + + @Test + fun `shared root classes compose to one guild command with aliases`() { + val definitions = scanner.scanCommands(GuildRootFixture::class.java.packageName, loader) + .filter { it.commandClass == GuildRootFixture::class || it.commandClass == GuildHomeFixture::class } + val plan = PaperCommandPlanner.plan(definitions) + assertEquals(1, plan.size) + assertEquals("guild", plan.single().name) + assertEquals(listOf("g"), plan.single().aliases) + assertEquals(2, plan.single().definitions.size) + assertTrue(plan.single().definitions.any { def -> def.subcommands.any { it.path.isEmpty() } }) + assertTrue(plan.single().definitions.any { def -> + def.subcommands.any { it.path == listOf("home", "activate") } + }) + } + + @Test + fun `scanner records optional and greedy arguments`() { + val scannerMethod = GuildHomeFixture::class + val definition = scanner.scanCommands(GuildRootFixture::class.java.packageName, loader) + .first { it.commandClass == scannerMethod } + val home = assertNotNull(definition.subcommands.find { it.path == listOf("home") }) + assertTrue(home.parameters.single().isOptional) + val announce = assertNotNull(definition.subcommands.find { it.path == listOf("announce") }) + assertEquals(setOf("message"), announce.greedyParameters) + assertEquals("guildName", definition.subcommands.single { it.path == listOf("lookup") }.parameters.single().name) + } + + @Test + fun `duplicate routes are rejected before registration`() { + val definitions = scanner.scanCommands(GuildRootFixture::class.java.packageName, loader) + .filter { it.commandClass == GuildRootFixture::class || it.commandClass == GuildHomeFixture::class } + val duplicate = definitions.last().copy(subcommands = listOf(definitions.first().subcommands.first())) + assertFailsWith { + PaperCommandPlanner.plan(listOf(definitions.first(), duplicate)) + } + } + + @Test + fun `greedy argument must be last`() { + assertFailsWith { + scanner.processClass(InvalidGreedyFixture::class) + } + } +} From d2146ff9ce875bb43186612d1c4d901221cf51a0 Mon Sep 17 00:00:00 2001 From: BadgersMC Date: Mon, 16 Nov 2026 21:53:54 -0500 Subject: [PATCH 2/2] refactor(paper): satisfy Detekt command validation checks --- .../paper/commands/PaperCommandPlanner.kt | 2 + .../paper/commands/PaperCommandRegistry.kt | 48 +++++++++++-------- .../paper/commands/PaperCommandScanner.kt | 8 ++-- 3 files changed, 36 insertions(+), 22 deletions(-) diff --git a/nexus-paper/src/main/kotlin/net/badgersmc/nexus/paper/commands/PaperCommandPlanner.kt b/nexus-paper/src/main/kotlin/net/badgersmc/nexus/paper/commands/PaperCommandPlanner.kt index 5f63d6a..1c12009 100644 --- a/nexus-paper/src/main/kotlin/net/badgersmc/nexus/paper/commands/PaperCommandPlanner.kt +++ b/nexus-paper/src/main/kotlin/net/badgersmc/nexus/paper/commands/PaperCommandPlanner.kt @@ -16,6 +16,8 @@ internal object PaperCommandPlanner { val definitions: List ) + // Root validation rejects distinct configuration errors rather than masking conflicts. + @Suppress("ThrowsCount") fun plan(definitions: List): List { val roots = definitions.groupBy { it.annotation.name.lowercase() } val occupiedNames = mutableMapOf() diff --git a/nexus-paper/src/main/kotlin/net/badgersmc/nexus/paper/commands/PaperCommandRegistry.kt b/nexus-paper/src/main/kotlin/net/badgersmc/nexus/paper/commands/PaperCommandRegistry.kt index 8067871..4058dee 100644 --- a/nexus-paper/src/main/kotlin/net/badgersmc/nexus/paper/commands/PaperCommandRegistry.kt +++ b/nexus-paper/src/main/kotlin/net/badgersmc/nexus/paper/commands/PaperCommandRegistry.kt @@ -180,31 +180,41 @@ class PaperCommandRegistry( val values = linkedMapOf(method.parameters.first() to route.bean) sub.parameters.forEachIndexed { index, param -> val reflected = method.parameters[index + 1] - when { - param.isContext -> values[reflected] = when (param.type.simpleName) { - "CommandSourceStack" -> ctx.source - "Player" -> ctx.source.sender as? Player - ?: throw CommandException("Command requires a player sender") - "CommandSender" -> ctx.source.sender - "Server" -> ctx.source.sender.server - else -> throw CommandException("Unsupported @Context type '${param.type.simpleName}'") - } - param.isArg && hasArgument(ctx, param.name) -> { - val resolver = PaperArgumentResolvers.get(param.type) - ?: throw CommandException("No resolver for ${param.type.simpleName}") - values[reflected] = resolver.extract(ctx, param.name) - } - param.isArg && !param.argAnnotation?.defaultValue.isNullOrEmpty() -> { - values[reflected] = parseDefault(param.type, param.argAnnotation!!.defaultValue) + if (param.isContext) { + values[reflected] = contextValue(ctx.source, param.type.simpleName) + } else { + when { + hasArgument(ctx, param.name) -> + values[reflected] = providedValue(ctx, param) + !param.argAnnotation?.defaultValue.isNullOrEmpty() -> + values[reflected] = parseDefault(param.type, param.argAnnotation!!.defaultValue) + reflected.isOptional -> Unit // Kotlin callBy applies the method default + reflected.type.isMarkedNullable -> values[reflected] = null + else -> throw CommandException("Missing required argument '${param.name}'") } - param.isArg && reflected.isOptional -> Unit // Kotlin callBy applies method default - param.isArg && reflected.type.isMarkedNullable -> values[reflected] = null - else -> throw CommandException("Missing required argument '${param.name}'") } } return values } + private fun contextValue(source: CommandSourceStack, typeName: String?): Any = when (typeName) { + "CommandSourceStack" -> source + "Player" -> source.sender as? Player + ?: throw CommandException("Command requires a player sender") + "CommandSender" -> source.sender + "Server" -> source.sender.server + else -> throw CommandException("Unsupported @Context type '$typeName'") + } + + private fun providedValue( + ctx: CommandContext, + param: net.badgersmc.nexus.commands.CommandParameter + ): Any { + val resolver = PaperArgumentResolvers.get(param.type) + ?: throw CommandException("No resolver for ${param.type.simpleName}") + return resolver.extract(ctx, param.name) + } + private fun hasArgument(ctx: CommandContext, name: String): Boolean = try { ctx.getArgument(name, Any::class.java) diff --git a/nexus-paper/src/main/kotlin/net/badgersmc/nexus/paper/commands/PaperCommandScanner.kt b/nexus-paper/src/main/kotlin/net/badgersmc/nexus/paper/commands/PaperCommandScanner.kt index 0b59bb6..01002db 100644 --- a/nexus-paper/src/main/kotlin/net/badgersmc/nexus/paper/commands/PaperCommandScanner.kt +++ b/nexus-paper/src/main/kotlin/net/badgersmc/nexus/paper/commands/PaperCommandScanner.kt @@ -39,6 +39,8 @@ class PaperCommandScanner { } } + // Multiple distinct validation failures intentionally use typed CommandExceptions. + @Suppress("ThrowsCount") internal fun processClass(klass: KClass<*>): PaperCommandDefinition { val annotation = klass.findAnnotation() ?: throw CommandException("Class ${klass.simpleName} missing @Command") @@ -78,9 +80,9 @@ class PaperCommandScanner { // cannot be invoked when Brigadier omits that argument. parameters.forEachIndexed { index, parameter -> val reflected = method.parameters[index + 1] - if (parameter.isOptional && !reflected.isOptional && !reflected.type.isMarkedNullable - && parameter.argAnnotation?.defaultValue.isNullOrEmpty() - ) { + val hasKotlinDefault = reflected.isOptional || reflected.type.isMarkedNullable + val hasAnnotationDefault = !parameter.argAnnotation?.defaultValue.isNullOrEmpty() + if (parameter.isOptional && !hasKotlinDefault && !hasAnnotationDefault) { throw CommandException("Optional '${parameter.name}' needs a Kotlin default, nullable type or @Arg defaultValue") } }