Hackily solve issue where Bukkit doesn't create a new Brigadier command per alias, so that command aliases get the full Brigadier treatment

This commit is contained in:
Alexander Söderberg 2020-09-19 22:49:03 +02:00
parent 1fede2b4c0
commit d83690cdcf
No known key found for this signature in database
GPG key ID: C0207FF7EA146678
14 changed files with 213 additions and 82 deletions

View file

@ -30,6 +30,7 @@ import com.intellectualsites.commands.CommandManager;
import com.intellectualsites.commands.CommandTree;
import com.intellectualsites.commands.arguments.CommandArgument;
import com.intellectualsites.commands.arguments.StaticArgument;
import com.intellectualsites.commands.arguments.parser.ArgumentParser;
import com.intellectualsites.commands.arguments.standard.BooleanArgument;
import com.intellectualsites.commands.arguments.standard.ByteArgument;
import com.intellectualsites.commands.arguments.standard.DoubleArgument;
@ -77,7 +78,7 @@ import java.util.function.Supplier;
*/
public final class CloudBrigadierManager<C, S> {
private final Map<Class<?>, Function<? extends CommandArgument<C, ?>,
private final Map<Class<?>, Function<? extends ArgumentParser<C, ?>,
? extends ArgumentType<?>>> mappers;
private final Map<Class<?>, Supplier<ArgumentType<?>>> defaultArgumentTypeSuppliers;
private final Supplier<CommandContext<C>> dummyContextProvider;
@ -101,7 +102,7 @@ public final class CloudBrigadierManager<C, S> {
private void registerInternalMappings() {
/* Map byte, short and int to IntegerArgumentType */
this.registerMapping(new TypeToken<ByteArgument<C>>() {
this.registerMapping(new TypeToken<ByteArgument.ByteParser<C>>() {
}, argument -> {
final boolean hasMin = argument.getMin() != Byte.MIN_VALUE;
final boolean hasMax = argument.getMax() != Byte.MAX_VALUE;
@ -113,7 +114,7 @@ public final class CloudBrigadierManager<C, S> {
return IntegerArgumentType.integer();
}
});
this.registerMapping(new TypeToken<ShortArgument<C>>() {
this.registerMapping(new TypeToken<ShortArgument.ShortParser<C>>() {
}, argument -> {
final boolean hasMin = argument.getMin() != Short.MIN_VALUE;
final boolean hasMax = argument.getMax() != Short.MAX_VALUE;
@ -125,7 +126,7 @@ public final class CloudBrigadierManager<C, S> {
return IntegerArgumentType.integer();
}
});
this.registerMapping(new TypeToken<IntegerArgument<C>>() {
this.registerMapping(new TypeToken<IntegerArgument.IntegerParser<C>>() {
}, argument -> {
final boolean hasMin = argument.getMin() != Integer.MIN_VALUE;
final boolean hasMax = argument.getMax() != Integer.MAX_VALUE;
@ -138,7 +139,7 @@ public final class CloudBrigadierManager<C, S> {
}
});
/* Map float to FloatArgumentType */
this.registerMapping(new TypeToken<FloatArgument<C>>() {
this.registerMapping(new TypeToken<FloatArgument.FloatParser<C>>() {
}, argument -> {
final boolean hasMin = argument.getMin() != Float.MIN_VALUE;
final boolean hasMax = argument.getMax() != Float.MAX_VALUE;
@ -151,7 +152,7 @@ public final class CloudBrigadierManager<C, S> {
}
});
/* Map double to DoubleArgumentType */
this.registerMapping(new TypeToken<DoubleArgument<C>>() {
this.registerMapping(new TypeToken<DoubleArgument.DoubleParser<C>>() {
}, argument -> {
final boolean hasMin = argument.getMin() != Double.MIN_VALUE;
final boolean hasMax = argument.getMax() != Double.MAX_VALUE;
@ -164,10 +165,10 @@ public final class CloudBrigadierManager<C, S> {
}
});
/* Map boolean to BoolArgumentType */
this.registerMapping(new TypeToken<BooleanArgument<C>>() {
this.registerMapping(new TypeToken<BooleanArgument.BooleanParser<C>>() {
}, argument -> BoolArgumentType.bool());
/* Map String properly to StringArgumentType */
this.registerMapping(new TypeToken<StringArgument<C>>() {
this.registerMapping(new TypeToken<StringArgument.StringParser<C>>() {
}, argument -> {
switch (argument.getStringMode()) {
case QUOTED:
@ -189,7 +190,7 @@ public final class CloudBrigadierManager<C, S> {
* @param <K> cloud argument type
* @param <O> Brigadier argument type value
*/
public <T, K extends CommandArgument<C, T>, O> void registerMapping(@Nonnull final TypeToken<K> argumentType,
public <T, K extends ArgumentParser<C, T>, O> void registerMapping(@Nonnull final TypeToken<K> argumentType,
@Nonnull final Function<? extends K,
? extends ArgumentType<O>> mapper) {
this.mappers.put(argumentType.getRawType(), mapper);
@ -206,33 +207,25 @@ public final class CloudBrigadierManager<C, S> {
this.defaultArgumentTypeSuppliers.put(clazz, supplier);
}
/**
* Get a Brigadier {@link ArgumentType} from a cloud {@link CommandArgument}
*
* @param argumentType cloud argument type
* @param argument cloud argument
* @param <T> cloud argument value type (generic)
* @param <K> cloud argument type (generic)
* @return Brigadier argument type
*/
@Nullable
@SuppressWarnings("all")
private <T, K extends CommandArgument<?, ?>> Pair<ArgumentType<?>, Boolean> getArgument(
private <T, K extends ArgumentParser<?, ?>> Pair<ArgumentType<?>, Boolean> getArgument(
@Nonnull final Class<?> valueType,
@Nonnull final TypeToken<T> argumentType,
@Nonnull final K argument) {
final CommandArgument<C, ?> commandArgument = (CommandArgument<C, ?>) argument;
final ArgumentParser<C, ?> commandArgument = (ArgumentParser<C, ?>) argument;
Function function = this.mappers.get(argumentType.getRawType());
if (function == null) {
return this.createDefaultMapper(commandArgument);
return this.createDefaultMapper(valueType, commandArgument);
}
return new Pair<>((ArgumentType<?>) function.apply(commandArgument), !argument.getValueType().equals(String.class));
return new Pair<>((ArgumentType<?>) function.apply(commandArgument), !(argument instanceof StringArgument.StringParser));
}
@Nonnull
private <T, K extends CommandArgument<C, T>> Pair<ArgumentType<?>, Boolean> createDefaultMapper(
@Nonnull final CommandArgument<C, T>
argument) {
final Supplier<ArgumentType<?>> argumentTypeSupplier = this.defaultArgumentTypeSuppliers.get(argument.getValueType());
private <T, K extends ArgumentParser<C, T>> Pair<ArgumentType<?>, Boolean> createDefaultMapper(
@Nonnull final Class<?> clazz,
@Nonnull final ArgumentParser<C, T> argument) {
final Supplier<ArgumentType<?>> argumentTypeSupplier = this.defaultArgumentTypeSuppliers.get(clazz);
if (argumentTypeSupplier != null) {
return new Pair<>(argumentTypeSupplier.get(), true);
}
@ -306,8 +299,9 @@ public final class CloudBrigadierManager<C, S> {
.requires(sender -> permissionChecker.test(sender, root.getNodeMeta().getOrDefault("permission", "")))
.executes(executor);
} else {
final Pair<ArgumentType<?>, Boolean> pair = this.getArgument(TypeToken.of(root.getValue().getClass()),
root.getValue());
final Pair<ArgumentType<?>, Boolean> pair = this.getArgument(root.getValue().getValueType(),
TypeToken.of(root.getValue().getParser().getClass()),
root.getValue().getParser());
final SuggestionProvider<S> provider = pair.getRight() ? null : suggestionProvider;
argumentBuilder = RequiredArgumentBuilder
.<S, Object>argument(root.getValue().getName(), (ArgumentType<Object>) pair.getLeft())

View file

@ -74,13 +74,16 @@ public final class BukkitTest extends JavaPlugin {
Function.identity(),
Function.identity()
);
((PaperCommandManager<CommandSender>) mgr).registerBrigadier();
final AnnotationParser<CommandSender> annotationParser
= new AnnotationParser<>(mgr, CommandSender.class, p ->
BukkitCommandMetaBuilder.builder().withDescription(p.get(StandardParameters.DESCRIPTION,
"No description")).build());
annotationParser.parse(this);
//noinspection all
((PaperCommandManager<CommandSender>) mgr).registerBrigadier();
mgr.command(mgr.commandBuilder("gamemode", this.metaWithDescription("Your ugli"), "gajmöde")
.argument(EnumArgument.required(GameMode.class, "gamemode"))
.argument(StringArgument.<CommandSender>newBuilder("player")
@ -99,8 +102,8 @@ public final class BukkitTest extends JavaPlugin {
.setGameMode(c.<GameMode>get("gamemode")
.orElse(GameMode.SURVIVAL)))
.build())
.command(mgr.commandBuilder("kenny")
.literal("sux")
.command(mgr.commandBuilder("kenny", "k")
.literal("sux", "s")
.argument(IntegerArgument
.<CommandSender>newBuilder("perc")
.withMin(PERC_MIN).withMax(PERC_MAX).build())
@ -174,7 +177,7 @@ public final class BukkitTest extends JavaPlugin {
@CommandMethod(value = "annotation|a <input> [number]", permission = "some.permission.node")
private void annotatedCommand(@Nonnull final Player player,
@Argument("input") @Completions("one,two,duck") @Nonnull final String input,
@Argument("number") @Range(max = "100") final int number) {
@Argument("number") @Range(min = "10", max = "100") final int number) {
player.sendMessage(ChatColor.GOLD + "Your input was: " + ChatColor.AQUA + input + ChatColor.GREEN + " (" + number + ")");
}

View file

@ -25,7 +25,6 @@ package com.intellectualsites.commands.bukkit;
import com.intellectualsites.commands.Command;
import com.intellectualsites.commands.arguments.CommandArgument;
import com.intellectualsites.commands.arguments.StaticArgument;
import com.intellectualsites.commands.exceptions.ArgumentParseException;
import com.intellectualsites.commands.exceptions.InvalidCommandSenderException;
import com.intellectualsites.commands.exceptions.InvalidSyntaxException;
@ -51,13 +50,15 @@ final class BukkitCommand<C> extends org.bukkit.command.Command implements Plugi
private final Command<C> cloudCommand;
@SuppressWarnings("unchecked")
BukkitCommand(@Nonnull final Command<C> cloudCommand,
BukkitCommand(@Nonnull final String label,
@Nonnull final List<String> aliases,
@Nonnull final Command<C> cloudCommand,
@Nonnull final CommandArgument<C, ?> command,
@Nonnull final BukkitCommandManager<C> manager) {
super(command.getName(),
super(label,
cloudCommand.getCommandMeta().getOrDefault("description", ""),
"",
((StaticArgument<C>) command).getAlternativeAliases());
aliases);
this.command = command;
this.manager = manager;
this.cloudCommand = cloudCommand;
@ -74,48 +75,52 @@ final class BukkitCommand<C> extends org.bukkit.command.Command implements Plugi
this.manager.executeCommand(sender,
builder.toString())
.whenComplete(((commandResult, throwable) -> {
if (throwable != null) {
if (throwable instanceof InvalidSyntaxException) {
this.manager.handleException(sender,
InvalidSyntaxException.class,
(InvalidSyntaxException) throwable, (c, e) ->
commandSender.sendMessage(ChatColor.RED + "Invalid Command Syntax. "
+ "Correct command syntax is: "
+ ChatColor.GRAY + "/"
+ ((InvalidSyntaxException) throwable).getCorrectSyntax())
);
} else if (throwable instanceof InvalidCommandSenderException) {
this.manager.handleException(sender,
InvalidCommandSenderException.class,
(InvalidCommandSenderException) throwable, (c, e) ->
commandSender.sendMessage(ChatColor.RED + throwable.getMessage())
);
} else if (throwable instanceof NoPermissionException) {
this.manager.handleException(sender,
NoPermissionException.class,
(NoPermissionException) throwable, (c, e) ->
commandSender.sendMessage(MESSAGE_NO_PERMS)
);
} else if (throwable instanceof NoSuchCommandException) {
this.manager.handleException(sender,
NoSuchCommandException.class,
(NoSuchCommandException) throwable, (c, e) ->
commandSender.sendMessage(MESSAGE_UNKNOWN_COMMAND)
);
} else if (throwable instanceof ArgumentParseException) {
this.manager.handleException(sender,
ArgumentParseException.class,
(ArgumentParseException) throwable, (c, e) ->
commandSender.sendMessage(ChatColor.RED + "Invalid Command Argument: "
+ ChatColor.GRAY + throwable.getCause()
.getMessage())
);
} else {
commandSender.sendMessage(throwable.getMessage());
throwable.printStackTrace();
}
}
}));
if (throwable != null) {
if (throwable instanceof InvalidSyntaxException) {
this.manager.handleException(sender,
InvalidSyntaxException.class,
(InvalidSyntaxException) throwable, (c, e) ->
commandSender.sendMessage(
ChatColor.RED + "Invalid Command Syntax. "
+ "Correct command syntax is: "
+ ChatColor.GRAY + "/"
+ ((InvalidSyntaxException) throwable)
.getCorrectSyntax())
);
} else if (throwable instanceof InvalidCommandSenderException) {
this.manager.handleException(sender,
InvalidCommandSenderException.class,
(InvalidCommandSenderException) throwable, (c, e) ->
commandSender.sendMessage(
ChatColor.RED + throwable.getMessage())
);
} else if (throwable instanceof NoPermissionException) {
this.manager.handleException(sender,
NoPermissionException.class,
(NoPermissionException) throwable, (c, e) ->
commandSender.sendMessage(MESSAGE_NO_PERMS)
);
} else if (throwable instanceof NoSuchCommandException) {
this.manager.handleException(sender,
NoSuchCommandException.class,
(NoSuchCommandException) throwable, (c, e) ->
commandSender.sendMessage(MESSAGE_UNKNOWN_COMMAND)
);
} else if (throwable instanceof ArgumentParseException) {
this.manager.handleException(sender,
ArgumentParseException.class,
(ArgumentParseException) throwable, (c, e) ->
commandSender.sendMessage(
ChatColor.RED + "Invalid Command Argument: "
+ ChatColor.GRAY + throwable.getCause()
.getMessage())
);
} else {
commandSender.sendMessage(throwable.getMessage());
throwable.printStackTrace();
}
}
}));
return true;
}

View file

@ -50,6 +50,8 @@ public class BukkitCommandManager<C> extends CommandManager<C> {
private final Function<CommandSender, C> commandSenderMapper;
private final Function<C, CommandSender> backwardsCommandSenderMapper;
private boolean splitAliases = false;
/**
* Construct a new Bukkit command manager
*
@ -113,4 +115,12 @@ public class BukkitCommandManager<C> extends CommandManager<C> {
return this.backwardsCommandSenderMapper.apply(sender).hasPermission(permission);
}
protected final void setSplitAliases(final boolean value) {
this.splitAliases = value;
}
protected final boolean getSplitAliases() {
return this.splitAliases;
}
}

View file

@ -25,6 +25,7 @@ package com.intellectualsites.commands.bukkit;
import com.intellectualsites.commands.Command;
import com.intellectualsites.commands.arguments.CommandArgument;
import com.intellectualsites.commands.arguments.StaticArgument;
import com.intellectualsites.commands.internal.CommandRegistrationHandler;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandMap;
@ -34,7 +35,9 @@ import org.bukkit.help.GenericCommandHelpTopic;
import javax.annotation.Nonnull;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
final class BukkitPluginRegistrationHandler<C> implements CommandRegistrationHandler {
@ -74,14 +77,37 @@ final class BukkitPluginRegistrationHandler<C> implements CommandRegistrationHan
} else {
label = commandArgument.getName();
}
@SuppressWarnings("unchecked") final List<String> aliases = ((StaticArgument<C>) commandArgument).getAlternativeAliases();
@SuppressWarnings("unchecked") final BukkitCommand<C> bukkitCommand = new BukkitCommand<>(
commandArgument.getName(),
(this.bukkitCommandManager.getSplitAliases() ? Collections.<String>emptyList() : aliases),
(Command<C>) command,
(CommandArgument<C, ?>) commandArgument,
this.bukkitCommandManager);
this.registeredCommands.put(commandArgument, bukkitCommand);
this.commandMap.register(commandArgument.getName(), this.bukkitCommandManager.getOwningPlugin().getName().toLowerCase(),
bukkitCommand);
if (this.bukkitCommandManager.getSplitAliases()) {
for (final String alias : aliases) {
if (!this.bukkitCommands.containsKey(alias)) {
@SuppressWarnings("unchecked") final BukkitCommand<C> aliasCommand = new BukkitCommand<>(
alias,
Collections.emptyList(),
(Command<C>) command,
(CommandArgument<C, ?>) commandArgument,
this.bukkitCommandManager);
this.commandMap.register(alias, this.bukkitCommandManager.getOwningPlugin()
.getName().toLowerCase(),
bukkitCommand);
}
}
}
return true;
}
}

View file

@ -72,6 +72,7 @@ public class PaperCommandManager<C>
final PaperBrigadierListener<C> brigadierListener = new PaperBrigadierListener<>(this);
Bukkit.getPluginManager().registerEvents(brigadierListener,
this.getOwningPlugin());
this.setSplitAliases(true);
return brigadierListener;
} catch (final Throwable e) {
this.getOwningPlugin().getLogger().severe("Failed to register Brigadier listener");

View file

@ -81,7 +81,7 @@ public class CloudVelocityTest {
@CommandMethod("test <num> [str]")
private void testCommand(@Nonnull @Argument("str") final String string,
@Nonnull final CommandSource source,
@Argument("num") @Range(max = "33") final int num) {
@Argument("num") @Range(min = "10", max = "33") final int num) {
source.sendMessage(TextComponent.builder()
.append("You wrote: ", NamedTextColor.GOLD)
.append(string, NamedTextColor.LIGHT_PURPLE)