First attempt at integrating Piston as the only command system

This commit is contained in:
Kenzie Togami
2019-04-15 01:21:15 -07:00
parent da35b3c174
commit 267ccf2298
28 changed files with 493 additions and 389 deletions

View File

@ -39,7 +39,7 @@ import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.extension.input.ParserContext;
import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.extension.platform.Capability;
import com.sk89q.worldedit.extension.platform.CommandManager;
import com.sk89q.worldedit.extension.platform.PlatformCommandMananger;
import com.sk89q.worldedit.extension.platform.Platform;
import com.sk89q.worldedit.function.operation.Operations;
import com.sk89q.worldedit.function.pattern.BlockPattern;
@ -67,6 +67,7 @@ import com.sk89q.worldedit.util.formatting.component.CommandUsageBox;
import com.sk89q.worldedit.world.World;
import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockTypes;
import org.enginehub.piston.CommandManager;
import java.util.ArrayList;
import java.util.List;
@ -598,7 +599,10 @@ public class UtilityCommands {
}
public static void help(CommandContext args, WorldEdit we, Actor actor) {
CommandCallable callable = we.getPlatformManager().getCommandManager().getDispatcher();
CommandManager manager = we.getPlatformManager().getPlatformCommandMananger().getCommandManager();
// TODO this will be implemented as a special utility in the manager
/*
int page = 0;
final int perPage = actor instanceof Player ? 8 : 20; // More pages for console
@ -626,15 +630,15 @@ public class UtilityCommands {
for (int i = 0; i < effectiveLength; i++) {
String command = args.getString(i);
if (callable instanceof Dispatcher) {
if (manager instanceof Dispatcher) {
// Chop off the beginning / if we're are the root level
if (isRootLevel && command.length() > 1 && command.charAt(0) == '/') {
command = command.substring(1);
}
CommandMapping mapping = detectCommand((Dispatcher) callable, command, isRootLevel);
CommandMapping mapping = detectCommand((Dispatcher) manager, command, isRootLevel);
if (mapping != null) {
callable = mapping.getCallable();
manager = mapping.getCallable();
} else {
if (isRootLevel) {
actor.printError(String.format("The command '%s' could not be found.", args.getString(i)));
@ -656,12 +660,12 @@ public class UtilityCommands {
}
// Create the message
if (callable instanceof Dispatcher) {
Dispatcher dispatcher = (Dispatcher) callable;
if (manager instanceof Dispatcher) {
Dispatcher dispatcher = (Dispatcher) manager;
// Get a list of aliases
List<CommandMapping> aliases = new ArrayList<>(dispatcher.getCommands());
aliases.sort(new PrimaryAliasComparator(CommandManager.COMMAND_CLEAN_PATTERN));
aliases.sort(new PrimaryAliasComparator(PlatformCommandMananger.COMMAND_CLEAN_PATTERN));
// Calculate pagination
int offset = perPage * page;
@ -698,9 +702,10 @@ public class UtilityCommands {
actor.printRaw(ColorCodeBuilder.asColorCodes(box));
} else {
CommandUsageBox box = new CommandUsageBox(callable, Joiner.on(" ").join(visited));
CommandUsageBox box = new CommandUsageBox(manager, Joiner.on(" ").join(visited));
actor.printRaw(ColorCodeBuilder.asColorCodes(box));
}
*/
}
}

View File

@ -113,7 +113,7 @@ public class WorldEditCommands {
actor.checkPermission("worldedit.report.pastebin");
ActorCallbackPaste.pastebin(
we.getSupervisor(), actor, result, "WorldEdit report: %s.report",
WorldEdit.getInstance().getPlatformManager().getCommandManager().getExceptionConverter()
WorldEdit.getInstance().getPlatformManager().getPlatformCommandMananger().getExceptionConverter()
);
}
}

View File

@ -0,0 +1,31 @@
/*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldedit.command.argument;
import org.enginehub.piston.InjectedValueAccess;
/**
* Key-interface for {@link InjectedValueAccess} for the String arguments.
*/
public interface Arguments {
String get();
}

View File

@ -0,0 +1,87 @@
/*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldedit.command.argument;
import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.LocalSession;
import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.entity.Player;
import java.util.concurrent.locks.StampedLock;
/**
* Lazily-created {@link EditSession}.
*/
public class EditSessionHolder {
private final StampedLock lock = new StampedLock();
private final WorldEdit worldEdit;
private final Player player;
public EditSessionHolder(WorldEdit worldEdit, Player player) {
this.worldEdit = worldEdit;
this.player = player;
}
private EditSession session;
/**
* Get the session, but does not create it if it doesn't exist.
*/
public EditSession getSession() {
long stamp = lock.tryOptimisticRead();
EditSession result = session;
if (!lock.validate(stamp)) {
stamp = lock.readLock();
try {
result = session;
} finally {
lock.unlockRead(stamp);
}
}
return result;
}
public EditSession getOrCreateSession() {
// use the already-generated result if possible
EditSession result = getSession();
if (result != null) {
return result;
}
// otherwise, acquire write lock
long stamp = lock.writeLock();
try {
// check session field again -- maybe another writer hit it in between
result = session;
if (result != null) {
return result;
}
// now we can do the actual creation
LocalSession localSession = worldEdit.getSessionManager().get(player);
EditSession editSession = localSession.createEditSession(player);
editSession.enableStandardMode();
localSession.tellVersion(player);
return session = editSession;
} finally {
lock.unlockWrite(stamp);
}
}
}

View File

@ -94,7 +94,7 @@ public class SelectionCommand extends SimpleCommand<Operation> {
return operation;
} catch (IncompleteRegionException e) {
WorldEdit.getInstance().getPlatformManager().getCommandManager().getExceptionConverter().convert(e);
WorldEdit.getInstance().getPlatformManager().getPlatformCommandMananger().getExceptionConverter().convert(e);
return null;
}
} else {

View File

@ -77,7 +77,7 @@ public class ShapedBrushCommand extends SimpleCommand<Object> {
tool.setFill(null);
tool.setBrush(new OperationFactoryBrush(factory, regionFactory, session), permission);
} catch (MaxBrushRadiusException | InvalidToolBindException e) {
WorldEdit.getInstance().getPlatformManager().getCommandManager().getExceptionConverter().convert(e);
WorldEdit.getInstance().getPlatformManager().getPlatformCommandMananger().getExceptionConverter().convert(e);
}
player.print("Set brush to " + factory);

View File

@ -34,15 +34,11 @@ import static com.google.common.base.Preconditions.checkNotNull;
@NonnullByDefault
public class CommandPermissionsConditionGenerator implements CommandConditionGenerator {
private static final Key<Actor> ACTOR_KEY = Key.get(Actor.class);
@Override
public Command.Condition generateCondition(Method commandMethod) {
CommandPermissions annotation = commandMethod.getAnnotation(CommandPermissions.class);
checkNotNull(annotation, "Annotation is missing from commandMethod");
Set<String> permissions = ImmutableSet.copyOf(annotation.value());
return p -> p.injectedValue(ACTOR_KEY)
.map(actor -> permissions.stream().anyMatch(actor::hasPermission))
.orElse(false);
return new PermissionCondition(permissions);
}
}

View File

@ -22,9 +22,9 @@ package com.sk89q.worldedit.command.util;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.util.concurrent.FutureCallback;
import com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.util.command.parametric.ExceptionConverter;
import org.enginehub.piston.exception.CommandException;
import javax.annotation.Nullable;

View File

@ -0,0 +1,49 @@
/*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldedit.command.util;
import com.google.inject.Key;
import com.sk89q.worldedit.extension.platform.Actor;
import org.enginehub.piston.Command;
import org.enginehub.piston.CommandParameters;
import java.util.Set;
public final class PermissionCondition implements Command.Condition {
private static final Key<Actor> ACTOR_KEY = Key.get(Actor.class);
private final Set<String> permissions;
PermissionCondition(Set<String> permissions) {
this.permissions = permissions;
}
public Set<String> getPermissions() {
return permissions;
}
@Override
public boolean satisfied(CommandParameters parameters) {
return parameters.injectedValue(ACTOR_KEY)
.map(actor -> permissions.stream().anyMatch(actor::hasPermission))
.orElse(false);
}
}

View File

@ -50,12 +50,12 @@ public enum Capability {
USER_COMMANDS {
@Override
void initialize(PlatformManager platformManager, Platform platform) {
platformManager.getCommandManager().register(platform);
platformManager.getPlatformCommandMananger().register(platform);
}
@Override
void unload(PlatformManager platformManager, Platform platform) {
platformManager.getCommandManager().unregister();
platformManager.getPlatformCommandMananger().unregister();
}
},

View File

@ -1,96 +0,0 @@
/*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldedit.extension.platform;
import com.google.common.base.Splitter;
import com.google.inject.Key;
import com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.minecraft.util.commands.CommandLocals;
import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.LocalSession;
import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.util.command.CommandCallable;
import com.sk89q.worldedit.util.command.Description;
import org.enginehub.piston.CommandManager;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
/**
* Hack to get {@link CommandManager} working under {@link CommandCallable}.
*/
public class CommandManagerCallable implements CommandCallable {
private final WorldEdit worldEdit;
private final CommandManager manager;
private final Description description;
public CommandManagerCallable(WorldEdit worldEdit, CommandManager manager, Description description) {
this.worldEdit = worldEdit;
this.manager = manager;
this.description = description;
}
@Override
public Object call(String arguments, CommandLocals locals, String[] parentCommands) throws CommandException {
manager.injectValue(Key.get(Actor.class), access -> Optional.of(locals.get(Actor.class)));
manager.injectValue(Key.get(Player.class), access -> {
Actor actor = locals.get(Actor.class);
return actor instanceof Player ? Optional.of(((Player) actor)) : Optional.empty();
});
manager.injectValue(Key.get(LocalSession.class), access ->
access.injectedValue(Key.get(Player.class))
.map(worldEdit.getSessionManager()::get)
);
manager.injectValue(Key.get(EditSession.class), access ->
access.injectedValue(Key.get(Player.class))
.map(sender -> {
LocalSession session = worldEdit.getSessionManager().get(sender);
EditSession editSession = session.createEditSession(sender);
editSession.enableStandardMode();
session.tellVersion(sender);
return editSession;
})
);
return manager.execute(Splitter.on(' ').splitToList(arguments));
}
private Player getPlayer(CommandLocals locals) {
Actor actor = locals.get(Actor.class);
return actor instanceof Player ? (Player) actor : null;
}
@Override
public Description getDescription() {
return description;
}
@Override
public boolean testPermission(CommandLocals locals) {
return true;
}
@Override
public List<String> getSuggestions(String arguments, CommandLocals locals) throws CommandException {
return Collections.emptyList();
}
}

View File

@ -24,6 +24,7 @@ import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.util.command.Dispatcher;
import com.sk89q.worldedit.world.World;
import com.sk89q.worldedit.world.registry.Registries;
import org.enginehub.piston.CommandManager;
import java.util.List;
import java.util.Map;
@ -97,11 +98,11 @@ public interface Platform {
@Nullable World matchWorld(World world);
/**
* Register the commands contained within the given command dispatcher.
* Register the commands contained within the given command manager.
*
* @param dispatcher the dispatcher
* @param commandManager the command manager
*/
void registerCommands(Dispatcher dispatcher);
void registerCommands(CommandManager commandManager);
/**
* Register game hooks.

View File

@ -19,9 +19,8 @@
package com.sk89q.worldedit.extension.platform;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.sk89q.minecraft.util.commands.CommandException;
import com.google.inject.Key;
import com.sk89q.minecraft.util.commands.CommandLocals;
import com.sk89q.minecraft.util.commands.CommandPermissionsException;
import com.sk89q.minecraft.util.commands.WrappedCommandException;
@ -30,51 +29,25 @@ import com.sk89q.worldedit.LocalConfiguration;
import com.sk89q.worldedit.LocalSession;
import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.command.BiomeCommands;
import com.sk89q.worldedit.command.BrushCommands;
import com.sk89q.worldedit.command.ChunkCommands;
import com.sk89q.worldedit.command.ClipboardCommands;
import com.sk89q.worldedit.command.GeneralCommands;
import com.sk89q.worldedit.command.GenerationCommands;
import com.sk89q.worldedit.command.HistoryCommands;
import com.sk89q.worldedit.command.NavigationCommands;
import com.sk89q.worldedit.command.RegionCommands;
import com.sk89q.worldedit.command.BiomeCommandsRegistration;
import com.sk89q.worldedit.command.SchematicCommands;
import com.sk89q.worldedit.command.SchematicCommandsRegistration;
import com.sk89q.worldedit.command.ScriptingCommands;
import com.sk89q.worldedit.command.SelectionCommands;
import com.sk89q.worldedit.command.SnapshotCommands;
import com.sk89q.worldedit.command.SnapshotUtilCommands;
import com.sk89q.worldedit.command.SuperPickaxeCommands;
import com.sk89q.worldedit.command.ToolCommands;
import com.sk89q.worldedit.command.ToolUtilCommands;
import com.sk89q.worldedit.command.UtilityCommands;
import com.sk89q.worldedit.command.WorldEditCommands;
import com.sk89q.worldedit.command.argument.ReplaceParser;
import com.sk89q.worldedit.command.argument.TreeGeneratorParser;
import com.sk89q.worldedit.command.composition.ApplyCommand;
import com.sk89q.worldedit.command.composition.DeformCommand;
import com.sk89q.worldedit.command.composition.PaintCommand;
import com.sk89q.worldedit.command.composition.SelectionCommand;
import com.sk89q.worldedit.command.composition.ShapedBrushCommand;
import com.sk89q.worldedit.command.argument.Arguments;
import com.sk89q.worldedit.command.argument.EditSessionHolder;
import com.sk89q.worldedit.command.util.CommandPermissionsConditionGenerator;
import com.sk89q.worldedit.command.util.PermissionCondition;
import com.sk89q.worldedit.entity.Entity;
import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.event.platform.CommandEvent;
import com.sk89q.worldedit.event.platform.CommandSuggestionEvent;
import com.sk89q.worldedit.extent.Extent;
import com.sk89q.worldedit.function.factory.Deform;
import com.sk89q.worldedit.function.factory.Deform.Mode;
import com.sk89q.worldedit.internal.command.ActorAuthorizer;
import com.sk89q.worldedit.internal.command.CommandLoggingHandler;
import com.sk89q.worldedit.internal.command.UserCommandCompleter;
import com.sk89q.worldedit.internal.command.WorldEditBinding;
import com.sk89q.worldedit.internal.command.WorldEditExceptionConverter;
import com.sk89q.worldedit.session.request.Request;
import com.sk89q.worldedit.util.command.CommandCallable;
import com.sk89q.worldedit.util.command.Dispatcher;
import com.sk89q.worldedit.util.command.InvalidUsageException;
import com.sk89q.worldedit.util.command.SimpleDescription;
import com.sk89q.worldedit.util.command.composition.ProvidedValue;
import com.sk89q.worldedit.util.command.fluent.CommandGraph;
import com.sk89q.worldedit.util.command.parametric.ExceptionConverter;
import com.sk89q.worldedit.util.command.parametric.LegacyCommandsHandler;
import com.sk89q.worldedit.util.command.parametric.ParametricBuilder;
@ -84,35 +57,44 @@ import com.sk89q.worldedit.util.formatting.component.CommandUsageBox;
import com.sk89q.worldedit.util.logging.DynamicStreamHandler;
import com.sk89q.worldedit.util.logging.LogFormat;
import com.sk89q.worldedit.world.World;
import org.enginehub.piston.Command;
import org.enginehub.piston.CommandManager;
import org.enginehub.piston.DefaultCommandManagerService;
import org.enginehub.piston.exception.CommandException;
import org.enginehub.piston.exception.CommandExecutionException;
import org.enginehub.piston.exception.ConditionFailedException;
import org.enginehub.piston.exception.UsageException;
import org.enginehub.piston.part.SubCommandPart;
import org.enginehub.piston.util.ValueProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.util.Optional;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.sk89q.worldedit.util.command.composition.LegacyCommandAdapter.adapt;
/**
* Handles the registration and invocation of commands.
*
* <p>This class is primarily for internal usage.</p>
*/
public final class CommandManager {
public final class PlatformCommandMananger {
public static final Pattern COMMAND_CLEAN_PATTERN = Pattern.compile("^[/]+");
private static final Logger log = LoggerFactory.getLogger(CommandManager.class);
private static final Logger log = LoggerFactory.getLogger(PlatformCommandMananger.class);
private static final java.util.logging.Logger commandLog =
java.util.logging.Logger.getLogger(CommandManager.class.getCanonicalName() + ".CommandLog");
java.util.logging.Logger.getLogger(PlatformCommandMananger.class.getCanonicalName() + ".CommandLog");
private static final Pattern numberFormatExceptionPattern = Pattern.compile("^For input string: \"(.*)\"$");
private final WorldEdit worldEdit;
private final PlatformManager platformManager;
private final Dispatcher dispatcher;
private final CommandManager commandManager;
private final DynamicStreamHandler dynamicHandler = new DynamicStreamHandler();
private final ExceptionConverter exceptionConverter;
@ -121,12 +103,14 @@ public final class CommandManager {
*
* @param worldEdit the WorldEdit instance
*/
CommandManager(final WorldEdit worldEdit, PlatformManager platformManager) {
PlatformCommandMananger(final WorldEdit worldEdit, PlatformManager platformManager) {
checkNotNull(worldEdit);
checkNotNull(platformManager);
this.worldEdit = worldEdit;
this.platformManager = platformManager;
this.exceptionConverter = new WorldEditExceptionConverter(worldEdit);
this.commandManager = DefaultCommandManagerService.getInstance()
.newCommandManager();
// Register this instance for command events
worldEdit.getEventBus().register(this);
@ -140,12 +124,41 @@ public final class CommandManager {
builder.setDefaultCompleter(new UserCommandCompleter(platformManager));
builder.addBinding(new WorldEditBinding(worldEdit));
builder.addInvokeListener(new LegacyCommandsHandler());
builder.addInvokeListener(new CommandLoggingHandler(worldEdit, commandLog));
CommandPermissionsConditionGenerator permsGenerator =
new CommandPermissionsConditionGenerator();
commandManager.register("schematic", cmd -> {
cmd.aliases(ImmutableList.of("schem", "/schematic", "/schem"));
cmd.description("Schematic commands for saving/loading areas");
cmd.action(Command.Action.NULL_ACTION);
CommandManager manager = DefaultCommandManagerService.getInstance()
.newCommandManager();
SchematicCommandsRegistration.builder()
.commandManager(manager)
.containerInstance(new SchematicCommands(worldEdit))
.commandPermissionsConditionGenerator(
permsGenerator
).build();
cmd.addPart(SubCommandPart.builder("action", "Sub-command to run.")
.withCommands(manager.getAllCommands().collect(Collectors.toList()))
.required()
.build());
});
BiomeCommandsRegistration.builder()
.commandManager(commandManager)
.containerInstance(new BiomeCommands())
.commandPermissionsConditionGenerator(permsGenerator)
.build();
// Unported commands are below. Delete once they're added to the main manager above.
/*
dispatcher = new CommandGraph()
.builder(builder)
.commands()
.registerMethods(new BiomeCommands())
.registerMethods(new ChunkCommands(worldEdit))
.registerMethods(new ClipboardCommands(worldEdit))
.registerMethods(new GeneralCommands(worldEdit))
@ -164,7 +177,6 @@ public final class CommandManager {
.describeAs("WorldEdit commands")
.registerMethods(new WorldEditCommands(worldEdit))
.parent()
.register(schematicCommands(),"schematic", "schem", "/schematic", "/schem")
.group("snapshot", "snap")
.describeAs("Schematic commands for saving/loading areas")
.registerMethods(new SnapshotCommands(worldEdit))
@ -190,22 +202,7 @@ public final class CommandManager {
.parent()
.graph()
.getDispatcher();
}
private CommandCallable schematicCommands() {
SimpleDescription desc = new SimpleDescription();
desc.setDescription("Schematic commands for saving/loading areas");
desc.setPermissions(ImmutableList.of());
org.enginehub.piston.CommandManager manager = DefaultCommandManagerService.getInstance()
.newCommandManager();
SchematicCommandsRegistration.builder()
.commandManager(manager)
.containerInstance(new SchematicCommands(worldEdit))
.commandPermissionsConditionGenerator(
new CommandPermissionsConditionGenerator()
).build();
return new CommandManagerCallable(worldEdit, manager, desc);
*/
}
public ExceptionConverter getExceptionConverter() {
@ -238,7 +235,7 @@ public final class CommandManager {
dynamicHandler.setFormatter(new LogFormat(config.logFormat));
}
platform.registerCommands(dispatcher);
platform.registerCommands(commandManager);
}
void unregister() {
@ -258,10 +255,10 @@ public final class CommandManager {
String searchCmd = split[0].toLowerCase();
// Try to detect the command
if (!dispatcher.contains(searchCmd)) {
if (worldEdit.getConfiguration().noDoubleSlash && dispatcher.contains("/" + searchCmd)) {
if (!commandManager.containsCommand(searchCmd)) {
if (worldEdit.getConfiguration().noDoubleSlash && commandManager.containsCommand("/" + searchCmd)) {
split[0] = "/" + split[0];
} else if (searchCmd.length() >= 2 && searchCmd.charAt(0) == '/' && dispatcher.contains(searchCmd.substring(1))) {
} else if (searchCmd.length() >= 2 && searchCmd.charAt(0) == '/' && commandManager.containsCommand(searchCmd.substring(1))) {
split[0] = split[0].substring(1);
}
}
@ -277,7 +274,7 @@ public final class CommandManager {
String[] split = commandDetection(event.getArguments().split(" "));
// No command found!
if (!dispatcher.contains(split[0])) {
if (!commandManager.containsCommand(split[0])) {
return;
}
@ -291,9 +288,13 @@ public final class CommandManager {
}
LocalConfiguration config = worldEdit.getConfiguration();
CommandLocals locals = new CommandLocals();
locals.put(Actor.class, actor);
locals.put("arguments", event.getArguments());
commandManager.injectValue(Key.get(Actor.class), ValueProvider.constant(actor));
commandManager.injectValue(Key.get(Arguments.class), ValueProvider.constant(event::getArguments));
commandManager.injectValue(Key.get(EditSessionHolder.class),
context -> context.injectedValue(Key.get(Actor.class))
.filter(Player.class::isInstance)
.map(Player.class::cast)
.map(p -> new EditSessionHolder(worldEdit, p)));
long start = System.currentTimeMillis();
@ -303,7 +304,7 @@ public final class CommandManager {
// exceptions without writing a hook into every dispatcher, we need to unwrap these
// exceptions and rethrow their converted form, if their is one.
try {
dispatcher.call(Joiner.on(" ").join(split), locals, new String[0]);
commandManager.execute(ImmutableList.copyOf(split));
} catch (Throwable t) {
// Use the exception converter to convert the exception if any of its causes
// can be converted, otherwise throw the original exception
@ -315,21 +316,14 @@ public final class CommandManager {
throw t;
}
} catch (CommandPermissionsException e) {
actor.printError("You are not permitted to do that. Are you in the right mode?");
} catch (InvalidUsageException e) {
if (e.isFullHelpSuggested()) {
actor.printRaw(ColorCodeBuilder.asColorCodes(new CommandUsageBox(e.getCommand(), e.getCommandUsed("/", ""), locals)));
String message = e.getMessage();
if (message != null) {
actor.printError(message);
}
} else {
String message = e.getMessage();
actor.printError(message != null ? message : "The command was not used properly (no more help available).");
actor.printError("Usage: " + e.getSimpleUsageString("/"));
} catch (ConditionFailedException e) {
if (e.getCondition() instanceof PermissionCondition) {
actor.printError("You are not permitted to do that. Are you in the right mode?");
}
} catch (WrappedCommandException e) {
} catch (UsageException e) {
String message = e.getMessage();
actor.printError(message != null ? message : "The command was not used properly (no more help available).");
} catch (CommandExecutionException e) {
Throwable t = e.getCause();
actor.printError("Please report this error: [See console]");
actor.printRaw(t.getClass().getName() + ": " + t.getMessage());
@ -343,9 +337,11 @@ public final class CommandManager {
log.error("An unknown error occurred", e);
}
} finally {
EditSession editSession = locals.get(EditSession.class);
Optional<EditSession> editSessionOpt = commandManager.injectedValue(Key.get(EditSessionHolder.class))
.map(EditSessionHolder::getSession);
if (editSession != null) {
if (editSessionOpt.isPresent()) {
EditSession editSession = editSessionOpt.get();
session.remember(editSession);
editSession.flushSession();
@ -373,22 +369,21 @@ public final class CommandManager {
@Subscribe
public void handleCommandSuggestion(CommandSuggestionEvent event) {
try {
CommandLocals locals = new CommandLocals();
locals.put(Actor.class, event.getActor());
locals.put("arguments", event.getArguments());
event.setSuggestions(dispatcher.getSuggestions(event.getArguments(), locals));
commandManager.injectValue(Key.get(Actor.class), ValueProvider.constant(event.getActor()));
commandManager.injectValue(Key.get(Arguments.class), ValueProvider.constant(event::getArguments));
// TODO suggestions
} catch (CommandException e) {
event.getActor().printError(e.getMessage());
}
}
/**
* Get the command dispatcher instance.
* Get the command manager instance.
*
* @return the command dispatcher
* @return the command manager
*/
public Dispatcher getDispatcher() {
return dispatcher;
public CommandManager getCommandManager() {
return commandManager;
}
public static java.util.logging.Logger getLogger() {

View File

@ -68,7 +68,7 @@ public class PlatformManager {
private static final Logger logger = LoggerFactory.getLogger(PlatformManager.class);
private final WorldEdit worldEdit;
private final CommandManager commandManager;
private final PlatformCommandMananger platformCommandMananger;
private final List<Platform> platforms = new ArrayList<>();
private final Map<Capability, Platform> preferences = new EnumMap<>(Capability.class);
private @Nullable String firstSeenVersion;
@ -83,7 +83,7 @@ public class PlatformManager {
public PlatformManager(WorldEdit worldEdit) {
checkNotNull(worldEdit);
this.worldEdit = worldEdit;
this.commandManager = new CommandManager(worldEdit, this);
this.platformCommandMananger = new PlatformCommandMananger(worldEdit, this);
// Register this instance for events
worldEdit.getEventBus().register(this);
@ -277,8 +277,8 @@ public class PlatformManager {
*
* @return the command manager
*/
public CommandManager getCommandManager() {
return commandManager;
public PlatformCommandMananger getPlatformCommandMananger() {
return platformCommandMananger;
}
/**

View File

@ -19,8 +19,7 @@
package com.sk89q.worldedit.internal.command;
import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandException;
import com.google.inject.Key;
import com.sk89q.minecraft.util.commands.Logging;
import com.sk89q.worldedit.IncompleteRegionException;
import com.sk89q.worldedit.LocalSession;
@ -28,22 +27,22 @@ import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.math.Vector3;
import com.sk89q.worldedit.util.command.parametric.AbstractInvokeListener;
import com.sk89q.worldedit.util.command.parametric.InvokeHandler;
import com.sk89q.worldedit.util.command.parametric.ParameterData;
import com.sk89q.worldedit.util.command.parametric.ParameterException;
import org.enginehub.piston.CommandParameters;
import org.enginehub.piston.gen.CommandCallListener;
import java.io.Closeable;
import java.lang.reflect.Method;
import java.util.Optional;
import java.util.logging.Handler;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Logs called commands to a logger.
*/
public class CommandLoggingHandler extends AbstractInvokeListener implements InvokeHandler, Closeable {
public class CommandLoggingHandler implements CommandCallListener, AutoCloseable {
private final WorldEdit worldEdit;
private final Logger logger;
@ -62,93 +61,77 @@ public class CommandLoggingHandler extends AbstractInvokeListener implements Inv
}
@Override
public void preProcess(Object object, Method method, ParameterData[] parameters, CommandContext context) throws CommandException, ParameterException {
}
@Override
public void preInvoke(Object object, Method method, ParameterData[] parameters, Object[] args, CommandContext context) throws CommandException {
public void beforeCall(Method method, CommandParameters parameters) {
Logging loggingAnnotation = method.getAnnotation(Logging.class);
Logging.LogMode logMode;
StringBuilder builder = new StringBuilder();
if (loggingAnnotation == null) {
logMode = null;
} else {
logMode = loggingAnnotation.value();
}
Actor sender = context.getLocals().get(Actor.class);
Player player;
Optional<Player> playerOpt = parameters.injectedValue(Key.get(Actor.class))
.filter(Player.class::isInstance)
.map(Player.class::cast);
if (sender == null) {
if (!playerOpt.isPresent()) {
return;
}
if (sender instanceof Player) {
player = (Player) sender;
} else {
return;
}
Player player = playerOpt.get();
builder.append("WorldEdit: ").append(sender.getName());
if (sender.isPlayer()) {
builder.append(" (in \"").append(player.getWorld().getName()).append("\")");
}
builder.append("WorldEdit: ").append(player.getName());
builder.append(" (in \"").append(player.getWorld().getName()).append("\")");
builder.append(": ").append(context.getCommand());
if (context.argsLength() > 0) {
builder.append(" ").append(context.getJoinedStrings(0));
}
if (logMode != null && sender.isPlayer()) {
builder.append(": ").append(parameters.getMetadata().getCalledName());
builder.append(": ")
.append(Stream.concat(
Stream.of(parameters.getMetadata().getCalledName()),
parameters.getMetadata().getArguments().stream()
).collect(Collectors.joining(" ")));
if (logMode != null) {
Vector3 position = player.getLocation().toVector();
LocalSession session = worldEdit.getSessionManager().get(player);
switch (logMode) {
case PLACEMENT:
try {
position = session.getPlacementPosition(player).toVector3();
} catch (IncompleteRegionException e) {
case PLACEMENT:
try {
position = session.getPlacementPosition(player).toVector3();
} catch (IncompleteRegionException e) {
break;
}
/* FALL-THROUGH */
case POSITION:
builder.append(" - Position: ").append(position);
break;
}
/* FALL-THROUGH */
case POSITION:
builder.append(" - Position: ").append(position);
break;
case ALL:
builder.append(" - Position: ").append(position);
/* FALL-THROUGH */
case ALL:
builder.append(" - Position: ").append(position);
/* FALL-THROUGH */
case ORIENTATION_REGION:
builder.append(" - Orientation: ").append(player.getCardinalDirection().name());
/* FALL-THROUGH */
case ORIENTATION_REGION:
builder.append(" - Orientation: ").append(player.getCardinalDirection().name());
/* FALL-THROUGH */
case REGION:
try {
builder.append(" - Region: ")
case REGION:
try {
builder.append(" - Region: ")
.append(session.getSelection(player.getWorld()));
} catch (IncompleteRegionException e) {
} catch (IncompleteRegionException e) {
break;
}
break;
}
break;
}
}
logger.info(builder.toString());
}
@Override
public void postInvoke(Object object, Method method, ParameterData[] parameters, Object[] args, CommandContext context) throws CommandException {
}
@Override
public InvokeHandler createInvokeHandler() {
return this;
}
@Override
public void close() {
for (Handler h : logger.getHandlers()) {

View File

@ -21,7 +21,6 @@ package com.sk89q.worldedit.internal.command;
import static com.google.common.base.Preconditions.checkNotNull;
import com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.worldedit.DisallowedItemException;
import com.sk89q.worldedit.EmptyClipboardException;
import com.sk89q.worldedit.IncompleteRegionException;
@ -35,6 +34,7 @@ import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.command.InsufficientArgumentsException;
import com.sk89q.worldedit.command.tool.InvalidToolBindException;
import com.sk89q.worldedit.command.util.PermissionCondition;
import com.sk89q.worldedit.internal.expression.ExpressionException;
import com.sk89q.worldedit.regions.RegionOperationException;
import com.sk89q.worldedit.util.command.parametric.ExceptionConverterHelper;
@ -42,6 +42,8 @@ import com.sk89q.worldedit.util.command.parametric.ExceptionMatch;
import com.sk89q.worldedit.util.io.file.FileSelectionAbortedException;
import com.sk89q.worldedit.util.io.file.FilenameResolutionException;
import com.sk89q.worldedit.util.io.file.InvalidFilenameException;
import org.enginehub.piston.exception.CommandException;
import org.enginehub.piston.exception.ConditionFailedException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@ -65,99 +67,106 @@ public class WorldEditExceptionConverter extends ExceptionConverterHelper {
if (matcher.matches()) {
throw new CommandException("Number expected; string \"" + matcher.group(1)
+ "\" given.");
+ "\" given.", e, null);
} else {
throw new CommandException("Number expected; string given.");
throw new CommandException("Number expected; string given.", e, null);
}
}
@ExceptionMatch
public void convert(IncompleteRegionException e) throws CommandException {
throw new CommandException("Make a region selection first.");
throw new CommandException("Make a region selection first.", e, null);
}
@ExceptionMatch
public void convert(UnknownItemException e) throws CommandException {
throw new CommandException("Block name '" + e.getID() + "' was not recognized.");
throw new CommandException("Block name '" + e.getID() + "' was not recognized.", e, null);
}
@ExceptionMatch
public void convert(InvalidItemException e) throws CommandException {
throw new CommandException(e.getMessage());
throw new CommandException(e.getMessage(), e, null);
}
@ExceptionMatch
public void convert(DisallowedItemException e) throws CommandException {
throw new CommandException("Block '" + e.getID()
+ "' not allowed (see WorldEdit configuration).");
+ "' not allowed (see WorldEdit configuration).", e, null);
}
@ExceptionMatch
public void convert(MaxChangedBlocksException e) throws CommandException {
throw new CommandException("Max blocks changed in an operation reached ("
+ e.getBlockLimit() + ").");
+ e.getBlockLimit() + ").", e, null);
}
@ExceptionMatch
public void convert(MaxBrushRadiusException e) throws CommandException {
throw new CommandException("Maximum brush radius (in configuration): " + worldEdit.getConfiguration().maxBrushRadius);
throw new CommandException("Maximum brush radius (in configuration): " + worldEdit.getConfiguration().maxBrushRadius, e, null);
}
@ExceptionMatch
public void convert(MaxRadiusException e) throws CommandException {
throw new CommandException("Maximum radius (in configuration): " + worldEdit.getConfiguration().maxRadius);
throw new CommandException("Maximum radius (in configuration): " + worldEdit.getConfiguration().maxRadius, e, null);
}
@ExceptionMatch
public void convert(UnknownDirectionException e) throws CommandException {
throw new CommandException("Unknown direction: " + e.getDirection());
throw new CommandException("Unknown direction: " + e.getDirection(), e, null);
}
@ExceptionMatch
public void convert(InsufficientArgumentsException e) throws CommandException {
throw new CommandException(e.getMessage());
throw new CommandException(e.getMessage(), e, null);
}
@ExceptionMatch
public void convert(RegionOperationException e) throws CommandException {
throw new CommandException(e.getMessage());
throw new CommandException(e.getMessage(), e, null);
}
@ExceptionMatch
public void convert(ExpressionException e) throws CommandException {
throw new CommandException(e.getMessage());
throw new CommandException(e.getMessage(), e, null);
}
@ExceptionMatch
public void convert(EmptyClipboardException e) throws CommandException {
throw new CommandException("Your clipboard is empty. Use //copy first.");
throw new CommandException("Your clipboard is empty. Use //copy first.", e, null);
}
@ExceptionMatch
public void convert(InvalidFilenameException e) throws CommandException {
throw new CommandException("Filename '" + e.getFilename() + "' invalid: "
+ e.getMessage());
+ e.getMessage(), e, null);
}
@ExceptionMatch
public void convert(FilenameResolutionException e) throws CommandException {
throw new CommandException(
"File '" + e.getFilename() + "' resolution error: " + e.getMessage());
"File '" + e.getFilename() + "' resolution error: " + e.getMessage(), e, null);
}
@ExceptionMatch
public void convert(InvalidToolBindException e) throws CommandException {
throw new CommandException("Can't bind tool to " + e.getItemType().getName() + ": " + e.getMessage());
throw new CommandException("Can't bind tool to " + e.getItemType().getName() + ": " + e.getMessage(), e, null);
}
@ExceptionMatch
public void convert(FileSelectionAbortedException e) throws CommandException {
throw new CommandException("File selection aborted.");
throw new CommandException("File selection aborted.", e, null);
}
@ExceptionMatch
public void convert(WorldEditException e) throws CommandException {
throw new CommandException(e.getMessage(), e);
throw new CommandException(e.getMessage(), e, null);
}
@ExceptionMatch
public void convert(ConditionFailedException e) throws CommandException {
if (e.getCondition() instanceof PermissionCondition) {
throw new CommandException("You are not permitted to do that. Are you in the right mode?", e, null);
}
}
}

View File

@ -19,8 +19,9 @@
package com.sk89q.worldedit.util.command.parametric;
import com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.minecraft.util.commands.WrappedCommandException;
import org.enginehub.piston.exception.CommandException;
import org.enginehub.piston.exception.CommandExecutionException;
/**
* Used to convert a recognized {@link Throwable} into an appropriate
@ -29,7 +30,7 @@ import com.sk89q.minecraft.util.commands.WrappedCommandException;
* <p>Methods (when invoked by a {@link ParametricBuilder}-created command) may throw
* relevant exceptions that are not caught by the command manager, but translate
* into reasonable exceptions for an application. However, unknown exceptions are
* normally simply wrapped in a {@link WrappedCommandException} and bubbled up. Only
* normally simply wrapped in a {@link CommandExecutionException} and bubbled up. Only
* normal {@link CommandException}s will be printed correctly, so a converter translates
* one of these unknown exceptions into an appropriate {@link CommandException}.</p>
*

View File

@ -19,8 +19,9 @@
package com.sk89q.worldedit.util.command.parametric;
import com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.minecraft.util.commands.WrappedCommandException;
import org.enginehub.piston.exception.CommandException;
import org.enginehub.piston.exception.CommandExecutionException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
@ -75,9 +76,9 @@ public abstract class ExceptionConverterHelper implements ExceptionConverter {
if (e.getCause() instanceof CommandException) {
throw (CommandException) e.getCause();
}
throw new WrappedCommandException(e);
throw new CommandExecutionException(e, null);
} catch (IllegalArgumentException | IllegalAccessException e) {
throw new WrappedCommandException(e);
throw new CommandExecutionException(e, null);
}
}
}

View File

@ -22,7 +22,7 @@ package com.sk89q.worldedit.util.formatting.component;
import static com.google.common.base.Preconditions.checkNotNull;
import com.sk89q.minecraft.util.commands.CommandLocals;
import com.sk89q.worldedit.extension.platform.CommandManager;
import com.sk89q.worldedit.extension.platform.PlatformCommandMananger;
import com.sk89q.worldedit.util.command.CommandCallable;
import com.sk89q.worldedit.util.command.CommandMapping;
import com.sk89q.worldedit.util.command.Description;
@ -72,7 +72,7 @@ public class CommandUsageBox extends StyledFragment {
String prefix = !commandString.isEmpty() ? commandString + " " : "";
List<CommandMapping> list = new ArrayList<>(dispatcher.getCommands());
list.sort(new PrimaryAliasComparator(CommandManager.COMMAND_CLEAN_PATTERN));
list.sort(new PrimaryAliasComparator(PlatformCommandMananger.COMMAND_CLEAN_PATTERN));
for (CommandMapping mapping : list) {
if (locals == null || mapping.getCallable().testPermission(locals)) {