Skip to content

Commit

Permalink
Initial refactoring and piston command system implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
DarkArc committed Jan 5, 2020
1 parent c5e240c commit 78cc5ae
Show file tree
Hide file tree
Showing 60 changed files with 631 additions and 284 deletions.
65 changes: 65 additions & 0 deletions src/main/java/com/sk89q/commandbook/BukkitCommandInspector.java
@@ -0,0 +1,65 @@
package com.sk89q.commandbook;

import com.sk89q.bukkit.util.CommandInspector;
import com.sk89q.worldedit.WorldEdit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.enginehub.piston.CommandManager;
import org.enginehub.piston.inject.InjectedValueStore;
import org.enginehub.piston.inject.Key;
import org.enginehub.piston.inject.MapBackedValueStore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Optional;

import static com.google.common.base.Preconditions.checkNotNull;
import static com.sk89q.worldedit.util.formatting.WorldEditText.reduceToText;

class BukkitCommandInspector implements CommandInspector {
private static final Logger logger = LoggerFactory.getLogger(com.sk89q.commandbook.BukkitCommandInspector.class);
private final CommandBook plugin;
private final CommandManager dispatcher;

BukkitCommandInspector(CommandBook plugin, CommandManager dispatcher) {
checkNotNull(plugin);
checkNotNull(dispatcher);
this.plugin = plugin;
this.dispatcher = dispatcher;
}

@Override
public String getShortText(Command command) {
Optional<org.enginehub.piston.Command> mapping = dispatcher.getCommand(command.getName());
if (mapping.isPresent()) {
return reduceToText(mapping.get().getDescription(), WorldEdit.getInstance().getConfiguration().defaultLocale);
} else {
logger.warn("BukkitCommandInspector doesn't know how about the command '" + command + "'");
return "Help text not available";
}
}

@Override
public String getFullText(Command command) {
Optional<org.enginehub.piston.Command> mapping = dispatcher.getCommand(command.getName());
if (mapping.isPresent()) {
return reduceToText(mapping.get().getFullHelp(), WorldEdit.getInstance().getConfiguration().defaultLocale);
} else {
logger.warn("BukkitCommandInspector doesn't know how about the command '" + command + "'");
return "Help text not available";
}
}

@Override
public boolean testPermission(CommandSender sender, Command command) {
Optional<org.enginehub.piston.Command> mapping = dispatcher.getCommand(command.getName());
if (mapping.isPresent()) {
InjectedValueStore store = MapBackedValueStore.create();
store.injectValue(Key.of(CommandSender.class), context -> Optional.of(sender));
return mapping.get().getCondition().satisfied(store);
} else {
logger.warn("BukkitCommandInspector doesn't know how about the command '" + command + "'");
return false;
}
}
}
90 changes: 34 additions & 56 deletions src/main/java/com/sk89q/commandbook/CommandBook.java
Expand Up @@ -19,13 +19,12 @@

package com.sk89q.commandbook;

import com.sk89q.bukkit.util.CommandsManagerRegistration;
import com.sk89q.commandbook.commands.CommandBookCommands;
import com.google.common.base.Joiner;
import com.sk89q.commandbook.component.session.SessionComponent;
import com.sk89q.commandbook.config.LegacyCommandBookConfigurationMigrator;
import com.sk89q.commandbook.session.SessionComponent;
import com.sk89q.minecraft.util.commands.*;
import com.sk89q.util.yaml.YAMLFormat;
import com.sk89q.util.yaml.YAMLProcessor;
import com.sk89q.worldedit.internal.command.CommandUtil;
import com.zachsthings.libcomponents.InjectComponent;
import com.zachsthings.libcomponents.InjectComponentAnnotationHandler;
import com.zachsthings.libcomponents.bukkit.BasePlugin;
Expand All @@ -37,18 +36,14 @@
import com.zachsthings.libcomponents.loader.ConfigListedComponentLoader;
import com.zachsthings.libcomponents.loader.JarFilesComponentLoader;
import com.zachsthings.libcomponents.loader.StaticComponentLoader;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.event.Listener;
import org.yaml.snakeyaml.error.YAMLException;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;

Expand All @@ -61,7 +56,7 @@ public final class CommandBook extends BasePlugin {

private static CommandBook instance;

private CommandsManager<CommandSender> commands;
private PlatformCommandManager commandManager = new PlatformCommandManager(this);

private Map<String, Integer> itemNames;
public boolean broadcastChanges;
Expand All @@ -87,33 +82,15 @@ public static void registerEvents(Listener listener) {
server().getPluginManager().registerEvents(listener, inst());
}

/**
* Called when the plugin is enabled. This is where configuration is loaded,
* and the plugin is setup.
*/
private void publishPistonCommands() {
commandManager.registerCommandsWith(this);
}

@Override
public void onEnable() {
super.onEnable();

// Register the commands that we want to use
final CommandBook plugin = this;
commands = new CommandsManager<CommandSender>() {
@Override
public boolean hasPermission(CommandSender player, String perm) {
return plugin.hasPermission(player, perm);
}
};

final CommandsManagerRegistration cmdRegister = new CommandsManagerRegistration(this, commands);
if (lowPriorityCommandRegistration) {
getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() {
@Override
public void run() {
cmdRegister.register(CommandBookCommands.CommandBookParentCommand.class);
}
}, 1L);
} else {
cmdRegister.register(CommandBookCommands.CommandBookParentCommand.class);
}
publishPistonCommands();
}

public void registerComponentLoaders() {
Expand Down Expand Up @@ -169,35 +146,36 @@ public ConfigurationFile createConfigurationNode(File file) {
componentManager.registerAnnotationHandler(InjectComponent.class, new InjectComponentAnnotationHandler(componentManager));
}

// FIXME: Backport to WorldEdit/common lib
private String rebuildArguments(String commandLabel, String[] args) {
int plSep = commandLabel.indexOf(":");
if (plSep >= 0 && plSep < commandLabel.length() + 1) {
commandLabel = commandLabel.substring(plSep + 1);
}

StringBuilder sb = new StringBuilder("/").append(commandLabel);
if (args.length > 0) {
sb.append(" ");
}

return Joiner.on(" ").appendTo(sb, args).toString();
}

/**
* Called on a command.
*/
@Override
public boolean onCommand(CommandSender sender, Command cmd,
String commandLabel, String[] args) {
try {
commands.execute(cmd.getName(), args, sender, sender);
} catch (CommandPermissionsException e) {
sender.sendMessage(ChatColor.RED + "You don't have permission.");
} catch (MissingNestedCommandException e) {
sender.sendMessage(ChatColor.RED + e.getUsage());
} catch (CommandUsageException e) {
sender.sendMessage(ChatColor.RED + e.getMessage());
sender.sendMessage(ChatColor.RED + e.getUsage());
} catch (WrappedCommandException e) {
if (e.getCause() instanceof NumberFormatException) {
sender.sendMessage(ChatColor.RED + "Number expected, string received instead.");
} else {
sender.sendMessage(ChatColor.RED + "An error has occurred. See console.");
e.printStackTrace();
}
} catch (CommandException e) {
sender.sendMessage(ChatColor.RED + e.getMessage());
}

public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
commandManager.handleCommand(sender, rebuildArguments(commandLabel, args));
return true;
}

@Override
public List<String> onTabComplete(CommandSender sender, Command cmd, String commandLabel, String[] args) {
String arguments = rebuildArguments(commandLabel, args);
return CommandUtil.fixSuggestions(arguments, commandManager.handleCommandSuggestion(sender, arguments));
}

/**
* Loads the configuration.
*/
Expand Down
143 changes: 143 additions & 0 deletions src/main/java/com/sk89q/commandbook/CommandBookCommands.java
@@ -0,0 +1,143 @@
// $Id$
/*
* Copyright (C) 2010, 2011 sk89q <http://www.sk89q.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

package com.sk89q.commandbook;

import com.sk89q.commandbook.util.PaginatedResult;
import com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.worldedit.command.util.CommandPermissions;
import com.sk89q.worldedit.command.util.CommandPermissionsConditionGenerator;
import com.sk89q.worldedit.internal.command.CommandRegistrationHandler;
import com.sk89q.worldedit.util.formatting.text.TextComponent;
import com.sk89q.worldedit.util.formatting.text.TranslatableComponent;
import com.sk89q.worldedit.util.formatting.text.adapter.bukkit.TextAdapter;
import com.sk89q.worldedit.util.formatting.text.format.TextColor;
import com.zachsthings.libcomponents.AbstractComponent;
import com.zachsthings.libcomponents.ComponentInformation;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.enginehub.piston.CommandManager;
import org.enginehub.piston.CommandManagerService;
import org.enginehub.piston.annotation.Command;
import org.enginehub.piston.annotation.CommandContainer;
import org.enginehub.piston.annotation.param.Arg;
import org.enginehub.piston.annotation.param.ArgFlag;
import org.enginehub.piston.part.SubCommandPart;

import java.io.IOException;
import java.util.Arrays;
import java.util.Map;
import java.util.logging.Level;
import java.util.stream.Collectors;

@CommandContainer(superTypes = CommandPermissionsConditionGenerator.Registration.class)
public class CommandBookCommands {
public static void register(CommandManagerService service, CommandManager commandManager, CommandRegistrationHandler registration) {
commandManager.register("cmdbook", builder -> {
builder.description(TextComponent.of("Commandbook Commands"));

CommandManager manager = service.newCommandManager();
registration.register(
manager,
CommandBookCommandsRegistration.builder(),
new CommandBookCommands()
);

builder.addPart(SubCommandPart.builder(TranslatableComponent.of("worldedit.argument.action"), TextComponent.of("Sub-command to run."))
.withCommands(manager.getAllCommands().collect(Collectors.toList()))
.required()
.build());
});
}

@Command(name = "version", desc = "CommandBook version information")
public void versionCmd(CommandSender sender) {
sender.sendMessage(ChatColor.YELLOW + "CommandBook " + CommandBook.inst().getDescription().getVersion());
sender.sendMessage(ChatColor.YELLOW + "http://www.sk89q.com");
}

@Command(name = "reload", desc = "Reload CommandBook's settings")
@CommandPermissions({"commandbook.reload"})
public void reloadCmd(CommandSender sender) {
try {
CommandBook.inst().getGlobalConfiguration().load();
} catch (IOException e) {
sender.sendMessage(ChatColor.RED + "Error reloading configuration: " + e.getMessage());
sender.sendMessage(ChatColor.RED + "See console for details!");
CommandBook.logger().log(Level.WARNING, "Error reloading configuration: " + e, e);
}

CommandBook.inst().loadConfiguration();
CommandBook.inst().getComponentManager().reloadComponents();

sender.sendMessage(ChatColor.YELLOW + "CommandBook's configuration has been reloaded.");
}

@Command(name = "save", desc = "Save CommandBook's settings")
@CommandPermissions({"commandbook.save"})
public void saveCmd(CommandSender sender) {
CommandBook.inst().getGlobalConfiguration().save();

sender.sendMessage(ChatColor.YELLOW + "CommandBook's configuration has been reloaded.");
}
@Command(name = "help", aliases = {"doc"}, desc = "Get documentation for a component")
@CommandPermissions("commandbook.component.help")
public void helpCmd(CommandSender sender,
@ArgFlag(name = 'p', desc = "Page of results to return", def = "1") int page,
@Arg(desc = "Component to disable", def = "") String componentName) {
if (componentName == null) {
try {
new PaginatedResult<AbstractComponent>("Name - Description") {
@Override
public String format(AbstractComponent entry) {
return entry.getInformation().friendlyName() + " - " + entry.getInformation().desc();
}
}.display(sender, CommandBook.inst().getComponentManager().getComponents(), page);
} catch (CommandException ignored) { }
} else {
AbstractComponent component = CommandBook.inst().getComponentManager().getComponent(componentName);
if (component == null) {
TextAdapter.sendComponent(
sender,
TextComponent.of("No such component: " + componentName).color(TextColor.RED)
);
return;
}

final ComponentInformation info = component.getInformation();
sender.sendMessage(ChatColor.YELLOW + info.friendlyName() + " - " + info.desc());
if (info.authors().length > 0 && info.authors()[0].length() > 0) {
sender.sendMessage(ChatColor.YELLOW + "Authors: " +
Arrays.toString(info.authors()).replaceAll("[(.*)]", "$1"));
}
Map<String, String> commands = component.getCommands();
if (commands.size() > 0) {
try {
new PaginatedResult<Map.Entry<String, String>>(" Command - Description") {
@Override
public String format(Map.Entry<String, String> entry) {
return " /" + entry.getKey() + " " + entry.getValue();
}
}.display(sender, commands.entrySet(), page);
} catch (CommandException ignored) { }
} else {
sender.sendMessage(ChatColor.YELLOW + "No commands");
}
}
}
}

0 comments on commit 78cc5ae

Please sign in to comment.