This commit is contained in:
Owen 2024-04-29 08:33:36 +02:00 committed by GitHub
commit 2278309cea
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
17 changed files with 4260 additions and 37 deletions

View File

@ -9,6 +9,8 @@ import java.util.function.Predicate;
* Brigadier {@link Command}, {@link SuggestionProvider}, and permission checker for Bukkit {@link Command}s.
*
* @param <S> command source type
* @deprecated For removal, use the new brigadier api.
*/
@Deprecated(forRemoval = true) // Paper
public interface BukkitBrigadierCommand <S extends BukkitBrigadierCommandSource> extends Command<S>, Predicate<S>, SuggestionProvider<S> {
}

View File

@ -6,6 +6,10 @@ import org.bukkit.command.CommandSender;
import org.bukkit.entity.Entity;
import org.jetbrains.annotations.Nullable;
/**
* @deprecated For removal, use the new brigadier api.
*/
@Deprecated(forRemoval = true) // Paper
public interface BukkitBrigadierCommandSource {
@Nullable

View File

@ -28,8 +28,10 @@ import org.jetbrains.annotations.NotNull;
* <p>If your logic is not safe to run asynchronously, only react to the synchronous version.</p>
*
* <p>This is a draft/experimental API and is subject to change.</p>
* @deprecated For removal, use the new brigadier api.
*/
@ApiStatus.Experimental
@Deprecated
public class AsyncPlayerSendCommandsEvent <S extends BukkitBrigadierCommandSource> extends PlayerEvent {
private static final HandlerList handlers = new HandlerList();

View File

@ -20,8 +20,10 @@ import org.jetbrains.annotations.NotNull;
* run at a later point in the server lifetime due to plugins, a server reload, etc.</p>
*
* <p>This is a draft/experimental API and is subject to change.</p>
* @deprecated For removal, use the new brigadier api.
*/
@ApiStatus.Experimental
@Deprecated
public class CommandRegisteredEvent<S extends BukkitBrigadierCommandSource> extends ServerEvent implements Cancellable {
private static final HandlerList handlers = new HandlerList();

View File

@ -1,6 +1,7 @@
package io.papermc.paper.brigadier;
import com.mojang.brigadier.Message;
import io.papermc.paper.command.brigadier.MessageComponentSerializer;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.ComponentLike;
import net.kyori.adventure.text.TextComponent;
@ -8,7 +9,9 @@ import org.checkerframework.checker.nullness.qual.NonNull;
/**
* Helper methods to bridge the gaps between Brigadier and Paper-MojangAPI.
* @deprecated For removal, use the new brigadier api.
*/
@Deprecated(forRemoval = true) // Paper
public final class PaperBrigadier {
private PaperBrigadier() {
throw new RuntimeException("PaperBrigadier is not to be instantiated!");
@ -23,7 +26,7 @@ public final class PaperBrigadier {
* @return A new Brigadier {@link Message}
*/
public static @NonNull Message message(final @NonNull ComponentLike componentLike) {
return PaperBrigadierProvider.instance().message(componentLike);
return MessageComponentSerializer.message().serialize(componentLike.asComponent());
}
/**
@ -37,6 +40,6 @@ public final class PaperBrigadier {
* @return The created {@link Component}
*/
public static @NonNull Component componentFromMessage(final @NonNull Message message) {
return PaperBrigadierProvider.instance().componentFromMessage(message);
return MessageComponentSerializer.message().deserialize(message);
}
}

View File

@ -1,30 +0,0 @@
package io.papermc.paper.brigadier;
import com.mojang.brigadier.Message;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.ComponentLike;
import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
import org.checkerframework.checker.nullness.qual.NonNull;
import static java.util.Objects.requireNonNull;
interface PaperBrigadierProvider {
final class Holder {
private static @MonotonicNonNull PaperBrigadierProvider INSTANCE;
}
static @NonNull PaperBrigadierProvider instance() {
return requireNonNull(Holder.INSTANCE, "PaperBrigadierProvider has not yet been initialized!");
}
static void initialize(final @NonNull PaperBrigadierProvider instance) {
if (Holder.INSTANCE != null) {
throw new IllegalStateException("PaperBrigadierProvider has already been initialized!");
}
Holder.INSTANCE = instance;
}
@NonNull Message message(@NonNull ComponentLike componentLike);
@NonNull Component componentFromMessage(@NonNull Message message);
}

File diff suppressed because it is too large Load Diff

View File

@ -91,7 +91,7 @@ new file mode 100644
index 0000000000000000000000000000000000000000..ca71c688b37ce2c8b712a4f9216cf872c8edf78e
--- /dev/null
+++ b/src/test/java/io/papermc/paper/permissions/MinecraftCommandPermissionsTest.java
@@ -0,0 +1,82 @@
@@ -0,0 +1,86 @@
+package io.papermc.paper.permissions;
+
+import com.mojang.brigadier.tree.CommandNode;
@ -138,6 +138,10 @@ index 0000000000000000000000000000000000000000..ca71c688b37ce2c8b712a4f9216cf872
+ Set<String> missing = new LinkedHashSet<>();
+ Set<String> foundPerms = new HashSet<>();
+ for (CommandNode<CommandSourceStack> child : root.getChildren()) {
+ // Ignore aliases
+ if (child.getRedirect() != null) {
+ child = child.getRedirect();
+ }
+ final String vanillaPerm = VanillaCommandWrapper.getPermission(child);
+ if (!perms.contains(vanillaPerm)) {
+ missing.add("Missing permission for " + child.getName() + " (" + vanillaPerm + ") command");

View File

@ -240,12 +240,12 @@ index 61115db85b81e627d11a0de21691a2ca69aafe2c..ba2a2ca0c36e61cb3cc00fafc7a5dd9f
}
diff --git a/src/test/java/io/papermc/paper/permissions/MinecraftCommandPermissionsTest.java b/src/test/java/io/papermc/paper/permissions/MinecraftCommandPermissionsTest.java
index ca71c688b37ce2c8b712a4f9216cf872c8edf78e..2f3ff50bf3f70b6b404d02d5ffcc079162a63bc1 100644
index 23faad674e1761e31febc398cdc0ddc632a6dd28..8d85caa1ab5ff53d445e5677a8b5fb9cc09ef9de 100644
--- a/src/test/java/io/papermc/paper/permissions/MinecraftCommandPermissionsTest.java
+++ b/src/test/java/io/papermc/paper/permissions/MinecraftCommandPermissionsTest.java
@@ -45,6 +45,9 @@ public class MinecraftCommandPermissionsTest extends AbstractTestingBase {
Set<String> foundPerms = new HashSet<>();
for (CommandNode<CommandSourceStack> child : root.getChildren()) {
@@ -49,6 +49,9 @@ public class MinecraftCommandPermissionsTest extends AbstractTestingBase {
child = child.getRedirect();
}
final String vanillaPerm = VanillaCommandWrapper.getPermission(child);
+ if ("bukkit.command.paper.pgive".equals(vanillaPerm)) { // skip our custom give command
+ continue;

File diff suppressed because it is too large Load Diff

View File

@ -1,12 +1,122 @@
package io.papermc.testplugin;
import com.mojang.brigadier.Command;
import io.papermc.paper.command.brigadier.BasicCommand;
import io.papermc.paper.command.brigadier.CommandSourceStack;
import io.papermc.paper.command.brigadier.Commands;
import io.papermc.paper.plugin.lifecycle.event.LifecycleEventManager;
import io.papermc.paper.plugin.lifecycle.event.types.LifecycleEvents;
import io.papermc.testplugin.example.ExampleAdminCommand;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.bukkit.command.CommandSender;
import org.bukkit.command.defaults.BukkitCommand;
import org.bukkit.event.Listener;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import org.jetbrains.annotations.NotNull;
public final class TestPlugin extends JavaPlugin implements Listener {
@Override
public void onEnable() {
this.getServer().getPluginManager().registerEvents(this, this);
// legacy registration via CommandMap
this.registerLegacyCommands();
// registration via lifecycle event system
this.registerViaLifecycleEvents();
}
private void registerViaLifecycleEvents() {
final LifecycleEventManager<Plugin> lifecycleManager = this.getLifecycleManager();
lifecycleManager.registerEventHandler(LifecycleEvents.COMMANDS, event -> {
final Commands commands = event.registrar();
// ensure plugin commands override
commands.register(Commands.literal("tag")
.executes(ctx -> {
ctx.getSource().getSender().sendPlainMessage("overriden command");
return Command.SINGLE_SUCCESS;
})
.build(),
null,
Collections.emptyList()
);
});
lifecycleManager.registerEventHandler(LifecycleEvents.COMMANDS.newHandler(event -> {
final Commands commands = event.registrar();
commands.register(this.getPluginMeta(), Commands.literal("root_command")
.then(Commands.literal("sub_command")
.requires(source -> source.getSender().hasPermission("testplugin.test"))
.executes(ctx -> {
ctx.getSource().getSender().sendPlainMessage("root_command sub_command");
return Command.SINGLE_SUCCESS;
})).build(),
null,
Collections.emptyList()
);
commands.register(this.getPluginMeta(), "example", "test", Collections.emptyList(), new BasicCommand() {
@Override
public int execute(@NotNull final CommandSourceStack commandSourceStack, final @NotNull String[] args) {
System.out.println(Arrays.toString(args));
return Command.SINGLE_SUCCESS;
}
@Override
public @NotNull Collection<String> suggest(final @NotNull CommandSourceStack commandSourceStack, final @NotNull String[] args) {
System.out.println(Arrays.toString(args));
return List.of("apple", "banana");
}
});
commands.register(this.getPluginMeta(), Commands.literal("water")
.requires(source -> {
System.out.println("isInWater check");
return source.getExecutor().isInWater();
})
.executes(ctx -> {
ctx.getSource().getExecutor().sendMessage("You are in water!");
return Command.SINGLE_SUCCESS;
}).then(Commands.literal("lava")
.requires(source -> {
System.out.println("isInLava check");
return source.getExecutor().isInLava();
})
.executes(ctx -> {
ctx.getSource().getExecutor().sendMessage("You are in lava!");
return Command.SINGLE_SUCCESS;
})).build(),
null,
Collections.emptyList());
ExampleAdminCommand.register(this, commands);
}).priority(10));
}
private void registerLegacyCommands() {
this.getServer().getCommandMap().register("fallback", new BukkitCommand("hi", "cool hi command", "<>", List.of("hialias")) {
@Override
public boolean execute(@NotNull CommandSender sender, @NotNull String commandLabel, @NotNull String[] args) {
sender.sendMessage("hi");
return true;
}
});
this.getServer().getCommandMap().register("fallback", new BukkitCommand("cooler-command", "cool hi command", "<>", List.of("cooler-command-alias")) {
@Override
public boolean execute(@NotNull CommandSender sender, @NotNull String commandLabel, @NotNull String[] args) {
sender.sendMessage("hi");
return true;
}
});
this.getServer().getCommandMap().getKnownCommands().values().removeIf((command) -> {
return command.getName().equals("hi");
});
}
}

View File

@ -1,13 +1,60 @@
package io.papermc.testplugin;
import com.mojang.brigadier.Command;
import io.papermc.paper.command.brigadier.Commands;
import io.papermc.paper.command.brigadier.argument.ArgumentTypes;
import io.papermc.paper.command.brigadier.argument.range.DoubleRangeProvider;
import io.papermc.paper.plugin.bootstrap.BootstrapContext;
import io.papermc.paper.plugin.bootstrap.PluginBootstrap;
import io.papermc.paper.plugin.lifecycle.event.LifecycleEventManager;
import io.papermc.paper.plugin.lifecycle.event.types.LifecycleEvents;
import io.papermc.testplugin.example.MaterialArgumentType;
import java.util.Collections;
import org.bukkit.Material;
import org.jetbrains.annotations.NotNull;
public class TestPluginBootstrap implements PluginBootstrap {
@Override
public void bootstrap(@NotNull BootstrapContext context) {
final LifecycleEventManager<BootstrapContext> lifecycleManager = context.getLifecycleManager();
lifecycleManager.registerEventHandler(LifecycleEvents.COMMANDS, event -> {
final Commands commands = event.registrar();
commands.register(Commands.literal("material")
.then(Commands.literal("item")
.then(Commands.argument("mat", MaterialArgumentType.item())
.executes(ctx -> {
ctx.getSource().getSender().sendPlainMessage(ctx.getArgument("mat", Material.class).name());
return Command.SINGLE_SUCCESS;
})
)
).then(Commands.literal("block")
.then(Commands.argument("mat", MaterialArgumentType.block())
.executes(ctx -> {
ctx.getSource().getSender().sendPlainMessage(ctx.getArgument("mat", Material.class).name());
return Command.SINGLE_SUCCESS;
})
)
)
.build(),
null,
Collections.emptyList()
);
});
lifecycleManager.registerEventHandler(LifecycleEvents.COMMANDS.newHandler(event -> {
final Commands commands = event.registrar();
commands.register(Commands.literal("heya")
.then(Commands.argument("range", ArgumentTypes.doubleRange())
.executes((ct) -> {
ct.getSource().getSender().sendPlainMessage(ct.getArgument("range", DoubleRangeProvider.class).range().toString());
return 1;
})
).build(),
null,
Collections.emptyList()
);
}).priority(10));
}
}

View File

@ -0,0 +1,25 @@
package io.papermc.testplugin.example;
import com.mojang.brigadier.ImmutableStringReader;
import com.mojang.brigadier.Message;
import com.mojang.brigadier.exceptions.CommandExceptionType;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import io.papermc.paper.command.brigadier.MessageComponentSerializer;
import net.kyori.adventure.text.Component;
public class ComponentCommandExceptionType implements CommandExceptionType {
private final Message message;
public ComponentCommandExceptionType(final Component message) {
this.message = MessageComponentSerializer.message().serialize(message);
}
public CommandSyntaxException create() {
return new CommandSyntaxException(this, this.message);
}
public CommandSyntaxException createWithContext(final ImmutableStringReader reader) {
return new CommandSyntaxException(this, this.message, reader.getString(), reader.getCursor());
}
}

View File

@ -0,0 +1,153 @@
package io.papermc.testplugin.example;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import io.papermc.paper.command.brigadier.CommandSourceStack;
import io.papermc.paper.command.brigadier.Commands;
import io.papermc.paper.command.brigadier.argument.MessageArgumentResponse;
import io.papermc.paper.command.brigadier.argument.ArgumentTypes;
import io.papermc.paper.command.brigadier.argument.resolvers.BlockPositionResolver;
import io.papermc.paper.command.brigadier.argument.resolvers.selector.PlayerSelectorArgumentResolver;
import io.papermc.paper.math.BlockPosition;
import io.papermc.testplugin.TestPlugin;
import net.kyori.adventure.chat.ChatType;
import net.kyori.adventure.text.Component;
import org.bukkit.Bukkit;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import java.util.List;
public class ExampleAdminCommand {
public static void register(TestPlugin plugin, Commands commands) {
final LiteralArgumentBuilder<CommandSourceStack> adminBuilder = Commands.literal("admin")
.executes((ct) -> {
ct.getSource().getSender().sendPlainMessage("root admin");
return 1;
})
.then(
Commands.literal("tp")
.then(
Commands.argument("player", ArgumentTypes.player()).executes((source) -> {
CommandSourceStack sourceStack = source.getSource();
Player resolved = source.getArgument("player", PlayerSelectorArgumentResolver.class).resolve(sourceStack).get(0);
if (resolved == source.getSource().getExecutor()) {
source.getSource().getExecutor().sendMessage(Component.text("Can't teleport to self!"));
return 0;
}
Entity entity = source.getSource().getExecutor();
if (entity != null) {
entity.teleport(resolved);
}
return 1;
})
)
)
.then(
Commands.literal("tp-self")
.executes((cmd) -> {
if (cmd.getSource().getSender() instanceof Player player) {
player.teleport(cmd.getSource().getLocation());
}
return com.mojang.brigadier.Command.SINGLE_SUCCESS;
})
)
.then(
Commands.literal("broadcast")
.then(
Commands.argument("message", ArgumentTypes.component()).executes((source) -> {
Component message = source.getArgument("message", Component.class);
Bukkit.broadcast(message);
return 1;
})
)
)
.then(
Commands.literal("ice_cream").then(
Commands.argument("type", new IceCreamTypeArgument()).executes((context) -> {
IceCreamType argumentResponse = context.getArgument("type", IceCreamType.class); // Gets the raw argument
context.getSource().getSender().sendMessage(Component.text("You like: " + argumentResponse));
return 1;
})
)
)
.then(
Commands.literal("execute")
.redirect(commands.getDispatcher().getRoot().getChild("execute"))
)
.then(
Commands.literal("signed_message").then(
Commands.argument("msg", ArgumentTypes.signedMessage()).executes((context) -> {
MessageArgumentResponse argumentResponse = context.getArgument("msg", MessageArgumentResponse.class); // Gets the raw argument
// This is a better way of getting signed messages, includes the concept of "disguised" messages.
argumentResponse.resolveSignedMessage("msg", context)
.thenAccept((signedMsg) -> {
context.getSource().getSender().sendMessage(signedMsg, ChatType.SAY_COMMAND.bind(Component.text("STATIC")));
});
return 1;
})
)
)
.then(
Commands.literal("setblock").then(
Commands.argument("block", ArgumentTypes.blockState())
.then(Commands.argument("pos", ArgumentTypes.blockPos())
.executes((context) -> {
CommandSourceStack sourceStack = context.getSource();
BlockPosition position = context.getArgument("pos", BlockPositionResolver.class).resolve(sourceStack);
BlockState state = context.getArgument("block", BlockState.class);
// TODO: better block state api here? :thinking:
Block block = context.getSource().getLocation().getWorld().getBlockAt(position.blockX(), position.blockY(), position.blockZ());
block.setType(state.getType());
block.setBlockData(state.getBlockData());
return 1;
})
)
)
);
commands.register(plugin.getPluginMeta(), adminBuilder.build(), "Cool command showcasing what you can do!", List.of("alias_for_admin_that_you_shouldnt_use", "a"));
Bukkit.getCommandMap().register(
"legacy",
new Command("legacy_command") {
@Override
public boolean execute(@NotNull CommandSender sender, @NotNull String commandLabel, @NotNull String[] args) {
throw new UnsupportedOperationException();
}
@Override
public @NotNull List<String> tabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args) throws IllegalArgumentException {
return List.of(String.join(" ", args));
}
}
);
Bukkit.getCommandMap().register(
"legacy",
new Command("legacy_fail") {
@Override
public boolean execute(@NotNull CommandSender sender, @NotNull String commandLabel, @NotNull String[] args) {
return false;
}
@Override
public @NotNull List<String> tabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args) throws IllegalArgumentException {
return List.of(String.join(" ", args));
}
}
);
}
}

View File

@ -0,0 +1,9 @@
package io.papermc.testplugin.example;
public enum IceCreamType {
VANILLA,
CHOCOLATE,
BLUE_MOON,
STRAWBERRY,
WHOLE_MILK
}

View File

@ -0,0 +1,48 @@
package io.papermc.testplugin.example;
import com.mojang.brigadier.Message;
import com.mojang.brigadier.arguments.ArgumentType;
import com.mojang.brigadier.arguments.StringArgumentType;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import io.papermc.paper.command.brigadier.MessageComponentSerializer;
import io.papermc.paper.command.brigadier.argument.CustomArgumentType;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import org.jetbrains.annotations.NotNull;
import java.util.concurrent.CompletableFuture;
public class IceCreamTypeArgument implements CustomArgumentType.Converted<IceCreamType, String> {
@Override
public @NotNull IceCreamType convert(String nativeType) throws CommandSyntaxException {
try {
return IceCreamType.valueOf(nativeType.toUpperCase());
} catch (Exception e) {
Message message = MessageComponentSerializer.message().serialize(Component.text("Invalid species %s!".formatted(nativeType), NamedTextColor.RED));
throw new CommandSyntaxException(new SimpleCommandExceptionType(message), message);
}
}
@Override
public @NotNull ArgumentType<String> getNativeType() {
return StringArgumentType.word();
}
@Override
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> context, SuggestionsBuilder builder) {
for (IceCreamType species : IceCreamType.values()) {
builder.suggest(species.name(), MessageComponentSerializer.message().serialize(Component.text("COOL! TOOLTIP!", NamedTextColor.GREEN)));
}
return CompletableFuture.completedFuture(
builder.build()
);
}
}

View File

@ -0,0 +1,88 @@
package io.papermc.testplugin.example;
import com.mojang.brigadier.arguments.ArgumentType;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import io.papermc.paper.command.brigadier.argument.CustomArgumentType;
import io.papermc.paper.command.brigadier.argument.ArgumentTypes;
import java.util.concurrent.CompletableFuture;
import java.util.function.Predicate;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import org.bukkit.Keyed;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.Registry;
import org.jetbrains.annotations.NotNull;
import static net.kyori.adventure.text.Component.translatable;
public class MaterialArgumentType implements CustomArgumentType.Converted<Material, NamespacedKey> {
private static final ComponentCommandExceptionType ERROR_INVALID = new ComponentCommandExceptionType(translatable("argument.id.invalid"));
private final Predicate<Material> check;
private MaterialArgumentType(Predicate<Material> check) {
this.check = check;
}
public static MaterialArgumentType item() {
return new MaterialArgumentType(Material::isItem);
}
public static MaterialArgumentType block() {
return new MaterialArgumentType(Material::isBlock);
}
@Override
public @NotNull Material convert(final @NotNull NamespacedKey nativeType) throws CommandSyntaxException {
final Material material = Registry.MATERIAL.get(nativeType);
if (material == null) {
throw ERROR_INVALID.create();
}
if (!this.check.test(material)) {
throw ERROR_INVALID.create();
}
return material;
}
static boolean matchesSubStr(String remaining, String candidate) {
for(int i = 0; !candidate.startsWith(remaining, i); ++i) {
i = candidate.indexOf('_', i);
if (i < 0) {
return false;
}
}
return true;
}
@Override
public @NotNull ArgumentType<NamespacedKey> getNativeType() {
return ArgumentTypes.namespacedKey();
}
@Override
public @NotNull <S> CompletableFuture<Suggestions> listSuggestions(final @NotNull CommandContext<S> context, final @NotNull SuggestionsBuilder builder) {
final Stream<Material> stream = StreamSupport.stream(Registry.MATERIAL.spliterator(), false);
final String remaining = builder.getRemaining();
boolean containsColon = remaining.indexOf(':') > -1;
stream.filter(this.check)
.map(Keyed::key)
.forEach(key -> {
final String keyAsString = key.asString();
if (containsColon) {
if (matchesSubStr(remaining, keyAsString)) {
builder.suggest(keyAsString);
}
} else if (matchesSubStr(remaining, key.namespace()) || "minecraft".equals(key.namespace()) && matchesSubStr(remaining, key.value())) {
builder.suggest(keyAsString);
}
});
return builder.buildFuture();
}
}