🎨 Change (improve) command context semantics

This commit is contained in:
Alexander Söderberg 2020-10-01 13:24:15 +02:00
parent ee59066733
commit 9d47a7c82d
No known key found for this signature in database
GPG key ID: C0207FF7EA146678
8 changed files with 33 additions and 30 deletions

View file

@ -62,9 +62,9 @@ class MethodCommandExecutionHandler<C> implements CommandExecutionHandler<C> {
final Argument argument = parameter.getAnnotation(Argument.class); final Argument argument = parameter.getAnnotation(Argument.class);
final CommandArgument<C, ?> commandArgument = this.commandArguments.get(argument.value()); final CommandArgument<C, ?> commandArgument = this.commandArguments.get(argument.value());
if (commandArgument.isRequired()) { if (commandArgument.isRequired()) {
arguments.add(commandContext.getRequired(argument.value())); arguments.add(commandContext.get(argument.value()));
} else { } else {
final Object optional = commandContext.get(argument.value()).orElse(null); final Object optional = commandContext.getOptional(argument.value()).orElse(null);
arguments.add(optional); arguments.add(optional);
} }
} else { } else {

View file

@ -411,7 +411,7 @@ public abstract class CommandManager<C> {
.through(new TypeToken<CommandPreprocessor<C>>() { .through(new TypeToken<CommandPreprocessor<C>>() {
}) })
.getResult(); .getResult();
return context.<String>get(AcceptingCommandPreprocessor.PROCESSED_INDICATOR_KEY).orElse("").isEmpty() return context.<String>getOptional(AcceptingCommandPreprocessor.PROCESSED_INDICATOR_KEY).orElse("").isEmpty()
? State.REJECTED ? State.REJECTED
: State.ACCEPTED; : State.ACCEPTED;
} }
@ -430,7 +430,7 @@ public abstract class CommandManager<C> {
.through(new TypeToken<CommandPostprocessor<C>>() { .through(new TypeToken<CommandPostprocessor<C>>() {
}) })
.getResult(); .getResult();
return context.<String>get(AcceptingCommandPostprocessor.PROCESSED_INDICATOR_KEY).orElse("").isEmpty() return context.<String>getOptional(AcceptingCommandPostprocessor.PROCESSED_INDICATOR_KEY).orElse("").isEmpty()
? State.REJECTED ? State.REJECTED
: State.ACCEPTED; : State.ACCEPTED;
} }

View file

@ -83,7 +83,8 @@ public final class CommandContext<C> {
} }
/** /**
* Store a value in the context map * Store a value in the context map. This will overwrite any existing
* value stored with the same key
* *
* @param key Key * @param key Key
* @param value Value * @param value Value
@ -94,13 +95,14 @@ public final class CommandContext<C> {
} }
/** /**
* Get a value from its key * Get a value from its key. Will return {@link Optional#empty()}
* if no value is stored with the given key
* *
* @param key Key * @param key Key
* @param <T> Value type * @param <T> Value type
* @return Value * @return Value
*/ */
public <T> @NonNull Optional<T> get(@NonNull final String key) { public <T> @NonNull Optional<T> getOptional(@NonNull final String key) {
final Object value = this.internalStorage.get(key); final Object value = this.internalStorage.get(key);
if (value != null) { if (value != null) {
@SuppressWarnings("ALL") final T castedValue = (T) value; @SuppressWarnings("ALL") final T castedValue = (T) value;
@ -111,7 +113,8 @@ public final class CommandContext<C> {
} }
/** /**
* Get a required argument from the context * Get a required argument from the context. This will thrown an exception
* if there's no value associated with the given key
* *
* @param key Argument key * @param key Argument key
* @param <T> Argument type * @param <T> Argument type
@ -119,7 +122,7 @@ public final class CommandContext<C> {
* @throws NullPointerException If no such argument is stored * @throws NullPointerException If no such argument is stored
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public <T> @NonNull T getRequired(@NonNull final String key) { public <T> @NonNull T get(@NonNull final String key) {
final Object value = this.internalStorage.get(key); final Object value = this.internalStorage.get(key);
if (value == null) { if (value == null) {
throw new NullPointerException("No such object stored in the context: " + key); throw new NullPointerException("No such object stored in the context: " + key);
@ -137,7 +140,7 @@ public final class CommandContext<C> {
*/ */
public <T> @NonNull T getOrDefault(@NonNull final String key, public <T> @NonNull T getOrDefault(@NonNull final String key,
@NonNull final T defaultValue) { @NonNull final T defaultValue) {
return this.<T>get(key).orElse(defaultValue); return this.<T>getOptional(key).orElse(defaultValue);
} }
/** /**

View file

@ -43,10 +43,10 @@ public class CommandPreProcessorTest {
.argument(EnumArgument.of(SampleEnum.class, "enum")) .argument(EnumArgument.of(SampleEnum.class, "enum"))
.handler( .handler(
commandContext -> System.out.printf("enum = %s | integer = %d\n", commandContext -> System.out.printf("enum = %s | integer = %d\n",
commandContext.<SampleEnum>get( commandContext.<SampleEnum>getOptional(
"enum").orElse( "enum").orElse(
SampleEnum.VALUE1), SampleEnum.VALUE1),
commandContext.<Integer>get( commandContext.<Integer>getOptional(
"int").orElseThrow( "int").orElseThrow(
() -> new NullPointerException( () -> new NullPointerException(
"int")))) "int"))))
@ -57,7 +57,7 @@ public class CommandPreProcessorTest {
@Test @Test
void testPreprocessing() { void testPreprocessing() {
Assertions.assertEquals(10, manager.executeCommand(new TestCommandSender(), "10 test value1") Assertions.assertEquals(10, manager.executeCommand(new TestCommandSender(), "10 test value1")
.join().getCommandContext().<Integer>get("int").orElse(0)); .join().getCommandContext().<Integer>getOptional("int").orElse(0));
manager.executeCommand(new TestCommandSender(), "aa test value1").join(); manager.executeCommand(new TestCommandSender(), "aa test value1").join();
} }

View file

@ -90,7 +90,7 @@ class CommandTreeTest {
Pair.of(Integer.class, Integer.class)) Pair.of(Integer.class, Integer.class))
.simple()) .simple())
.handler(c -> { .handler(c -> {
final Pair<Integer, Integer> pair = c.getRequired("pos"); final Pair<Integer, Integer> pair = c.get("pos");
System.out.printf("X: %d | Y: %d\n", pair.getFirst(), pair.getSecond()); System.out.printf("X: %d | Y: %d\n", pair.getFirst(), pair.getSecond());
}) })
.build()); .build());
@ -101,7 +101,7 @@ class CommandTreeTest {
pair -> new Vector2(pair.getFirst(), pair.getSecond())) pair -> new Vector2(pair.getFirst(), pair.getSecond()))
) )
.handler(c -> { .handler(c -> {
final Vector2 vector2 = c.getRequired("vec"); final Vector2 vector2 = c.get("vec");
System.out.printf("X: %f | Y: %f\n", vector2.getX(), vector2.getY()); System.out.printf("X: %f | Y: %f\n", vector2.getX(), vector2.getY());
}) })
.build()); .build());
@ -155,7 +155,7 @@ class CommandTreeTest {
manager.commandBuilder("default") manager.commandBuilder("default")
.argument(manager.argumentBuilder(Integer.class, "int").build()) .argument(manager.argumentBuilder(Integer.class, "int").build())
.handler(context -> { .handler(context -> {
final int number = context.getRequired("int"); final int number = context.get("int");
System.out.printf("Supplied number is: %d\n", number); System.out.printf("Supplied number is: %d\n", number);
}) })
.build() .build()

View file

@ -42,8 +42,8 @@ class StringArgumentTest {
.argument(StringArgument.of("message1", StringArgument.StringMode.QUOTED)) .argument(StringArgument.of("message1", StringArgument.StringMode.QUOTED))
.argument(StringArgument.of("message2")) .argument(StringArgument.of("message2"))
.handler(c -> { .handler(c -> {
final String message1 = c.getRequired("message1"); final String message1 = c.get("message1");
final String message2 = c.getRequired("message2"); final String message2 = c.get("message2");
storage[0] = message1; storage[0] = message1;
storage[1] = message2; storage[1] = message2;
}) })
@ -51,14 +51,14 @@ class StringArgumentTest {
manager.command(manager.commandBuilder("single") manager.command(manager.commandBuilder("single")
.argument(StringArgument.of("message")) .argument(StringArgument.of("message"))
.handler(c -> { .handler(c -> {
final String message = c.getRequired("message"); final String message = c.get("message");
storage[0] = message; storage[0] = message;
}) })
.build()); .build());
manager.command(manager.commandBuilder("greedy") manager.command(manager.commandBuilder("greedy")
.argument(StringArgument.of("message", StringArgument.StringMode.GREEDY)) .argument(StringArgument.of("message", StringArgument.StringMode.GREEDY))
.handler(c -> { .handler(c -> {
final String message = c.getRequired("message"); final String message = c.get("message");
storage[0] = message; storage[0] = message;
}) })
.build()); .build());

View file

@ -95,7 +95,7 @@ public class JLineCommandManager extends CommandManager<JLineCommandSender> impl
return ArgumentParseResult.success( return ArgumentParseResult.success(
stringBuilder.toString()); stringBuilder.toString());
})).build()) })).build())
.handler(commandContext -> commandContext.get("string") .handler(commandContext -> commandContext.getOptional("string")
.ifPresent( .ifPresent(
System.out::println)) System.out::println))
.build()) .build())

View file

@ -136,7 +136,7 @@ public final class BukkitTest extends JavaPlugin {
return suggestions; return suggestions;
}).build()) }).build())
.handler(c -> ((Player) c.getSender()) .handler(c -> ((Player) c.getSender())
.setGameMode(c.<GameMode>get("gamemode") .setGameMode(c.<GameMode>getOptional("gamemode")
.orElse(GameMode.SURVIVAL))) .orElse(GameMode.SURVIVAL)))
.build()) .build())
.command(mgr.commandBuilder("kenny", "k") .command(mgr.commandBuilder("kenny", "k")
@ -147,7 +147,7 @@ public final class BukkitTest extends JavaPlugin {
.handler(context -> { .handler(context -> {
context.getSender().sendMessage(String.format( context.getSender().sendMessage(String.format(
"Kenny sux %d%%", "Kenny sux %d%%",
context.<Integer>get("perc").orElse(PERC_MIN) context.<Integer>getOptional("perc").orElse(PERC_MIN)
)); ));
}) })
.build()) .build())
@ -168,15 +168,15 @@ public final class BukkitTest extends JavaPlugin {
} }
}).build()) }).build())
.handler(c -> c.getSender() .handler(c -> c.getSender()
.sendMessage(String.format("UUID: %s\n", c.<UUID>get("uuid").orElse(null)))) .sendMessage(String.format("UUID: %s\n", c.<UUID>getOptional("uuid").orElse(null))))
.build()) .build())
.command(mgr.commandBuilder("give") .command(mgr.commandBuilder("give")
.withSenderType(Player.class) .withSenderType(Player.class)
.argument(EnumArgument.of(Material.class, "material")) .argument(EnumArgument.of(Material.class, "material"))
.argument(IntegerArgument.of("amount")) .argument(IntegerArgument.of("amount"))
.handler(c -> { .handler(c -> {
final Material material = c.getRequired("material"); final Material material = c.get("material");
final int amount = c.getRequired("amount"); final int amount = c.get("amount");
final ItemStack itemStack = new ItemStack(material, amount); final ItemStack itemStack = new ItemStack(material, amount);
((Player) c.getSender()).getInventory().addItem(itemStack); ((Player) c.getSender()).getInventory().addItem(itemStack);
c.getSender().sendMessage("You've been given stuff, bro."); c.getSender().sendMessage("You've been given stuff, bro.");
@ -187,7 +187,7 @@ public final class BukkitTest extends JavaPlugin {
.build()) .build())
.argument(WorldArgument.of("world")) .argument(WorldArgument.of("world"))
.handler(c -> { .handler(c -> {
final World world = c.getRequired("world"); final World world = c.get("world");
((Player) c.getSender()).teleport(world.getSpawnLocation()); ((Player) c.getSender()).teleport(world.getSpawnLocation());
c.getSender().sendMessage("Teleported."); c.getSender().sendMessage("Teleported.");
}) })
@ -213,7 +213,7 @@ public final class BukkitTest extends JavaPlugin {
.argument(StringArgument.<CommandSender>newBuilder("query").greedy() .argument(StringArgument.<CommandSender>newBuilder("query").greedy()
.asOptionalWithDefault("") .asOptionalWithDefault("")
.build(), Description.of("Help Query")) .build(), Description.of("Help Query"))
.handler(c -> minecraftHelp.queryCommands(c.<String>get("query").orElse(""), .handler(c -> minecraftHelp.queryCommands(c.<String>getOptional("query").orElse(""),
c.getSender())).build()); c.getSender())).build());
this.registerTeleportCommand(mgr); this.registerTeleportCommand(mgr);
mgr.registerExceptionHandler(InvalidSyntaxException.class, (c, e) -> e.printStackTrace()); mgr.registerExceptionHandler(InvalidSyntaxException.class, (c, e) -> e.printStackTrace());
@ -236,8 +236,8 @@ public final class BukkitTest extends JavaPlugin {
.handler(context -> { .handler(context -> {
context.getSender().sendMessage(ChatColor.GOLD + "Teleporting!"); context.getSender().sendMessage(ChatColor.GOLD + "Teleporting!");
Bukkit.getScheduler().runTask(this, () -> { Bukkit.getScheduler().runTask(this, () -> {
final World world = context.getRequired("world"); final World world = context.get("world");
final Vector vector = context.getRequired("coords"); final Vector vector = context.get("coords");
((Player) context.getSender()).teleport(vector.toLocation(world)); ((Player) context.getSender()).teleport(vector.toLocation(world));
}); });
}) })