use of org.spongepowered.api.command.CommandCallable in project SpongeAPI by SpongePowered.
the class SimpleDispatcher method process.
@Override
public CommandResult process(CommandSource source, String commandLine) throws CommandException {
final String[] argSplit = commandLine.split(" ", 2);
Optional<CommandMapping> cmdOptional = get(argSplit[0], source);
if (!cmdOptional.isPresent()) {
// TODO: Fix properly to use a SpongeTranslation??
throw new CommandNotFoundException(t("commands.generic.notFound"), argSplit[0]);
}
final String arguments = argSplit.length > 1 ? argSplit[1] : "";
CommandMapping mapping = cmdOptional.get();
Optional<PluginContainer> pluginOwner = Sponge.getCommandManager().getOwner(mapping);
if (pluginOwner.isPresent()) {
Sponge.getCauseStackManager().pushCause(pluginOwner.get());
}
final CommandCallable spec = mapping.getCallable();
try {
return spec.process(source, arguments);
} catch (CommandNotFoundException e) {
throw new CommandException(t("No such child command: %s", e.getCommand()));
} finally {
if (pluginOwner.isPresent()) {
Sponge.getCauseStackManager().popCause();
}
}
}
use of org.spongepowered.api.command.CommandCallable in project LanternServer by LanternPowered.
the class CommandHelp method completeSpec.
@Override
public void completeSpec(PluginContainer pluginContainer, CommandSpec.Builder specBuilder) {
final Comparator<CommandMapping> comparator = Comparator.comparing(CommandMapping::getPrimaryAlias);
specBuilder.arguments(GenericArguments.optional(new CommandElement(Text.of("command")) {
@Nullable
@Override
protected Object parseValue(CommandSource source, CommandArgs args) throws ArgumentParseException {
return args.next();
}
@Override
public List<String> complete(CommandSource src, CommandArgs args, CommandContext context) {
final String nextArg = args.nextIfPresent().orElse("");
return Lantern.getGame().getCommandManager().getAliases().stream().filter(new StartsWithPredicate(nextArg)).collect(Collectors.toList());
}
})).description(Text.of("View a list of all commands")).extendedDescription(Text.of("View a list of all commands. Hover over\n" + " a command to view its description. Click\n" + " a command to insert it into your chat bar.")).executor((src, args) -> {
Optional<String> command = args.getOne("command");
if (command.isPresent()) {
Optional<? extends CommandMapping> mapping = Sponge.getCommandManager().get(command.get());
if (mapping.isPresent()) {
CommandCallable callable = mapping.get().getCallable();
Optional<? extends Text> desc;
// command name in the usage message
if (callable instanceof CommandSpec) {
Text.Builder builder = Text.builder();
callable.getShortDescription(src).ifPresent(des -> builder.append(des, Text.NEW_LINE));
builder.append(t("commands.generic.usage", t("/%s %s", command.get(), callable.getUsage(src))));
Text extendedDescription;
try {
// TODO: Why is there no method :(
extendedDescription = (Text) extendedDescriptionField.get(callable);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
if (extendedDescription != null) {
builder.append(Text.NEW_LINE, extendedDescription);
}
src.sendMessage(builder.build());
} else if ((desc = callable.getHelp(src)).isPresent()) {
src.sendMessage(desc.get());
} else {
src.sendMessage(t("commands.generic.usage", t("/%s %s", command.get(), callable.getUsage(src))));
}
return CommandResult.success();
}
throw new CommandException(Text.of("No such command: ", command.get()));
}
Lantern.getGame().getScheduler().submitAsyncTask(() -> {
TreeSet<CommandMapping> commands = new TreeSet<>(comparator);
commands.addAll(Collections2.filter(Sponge.getCommandManager().getAll().values(), input -> input.getCallable().testPermission(src)));
final Text title = Text.builder("Available commands:").color(TextColors.DARK_GREEN).build();
final List<Text> lines = commands.stream().map(c -> getDescription(src, c)).collect(Collectors.toList());
// Console sources cannot see/use the pagination
if (!(src instanceof ConsoleSource)) {
Sponge.getGame().getServiceManager().provide(PaginationService.class).get().builder().title(title).padding(Text.of(TextColors.DARK_GREEN, "=")).contents(lines).sendTo(src);
} else {
src.sendMessage(title);
src.sendMessages(lines);
}
return null;
});
return CommandResult.success();
});
}
use of org.spongepowered.api.command.CommandCallable in project Nucleus by NucleusPowered.
the class AbstractCommand method process.
private CommandResult process(CommandSource source, String command, String arguments, CommandArgs args) throws CommandException {
// Phase one: child command processing. Keep track of all thrown arguments.
List<Tuple<String, CommandException>> thrown = Lists.newArrayList();
final CommandContext context = new CommandContext();
T castedSource;
try {
// If we have a child command to execute, then we execute it.
if (args.hasNext() && this.dispatcher.containsAlias(args.peek())) {
Object state = args.getState();
String next = args.next();
try {
// If this works, then we're A-OK.
CommandCallable callable = this.dispatcher.get(next.toLowerCase()).get().getCallable();
if (callable instanceof AbstractCommand) {
return ((AbstractCommand) callable).process(source, command + " " + next, arguments, args);
}
return callable.process(source, arguments);
} catch (NucleusCommandException e) {
// Didn't work out. Let's move on.
thrown.addAll(e.getExceptions());
if (!e.isAllowFallback()) {
throw e;
}
} catch (CommandException e) {
// If the Exception is _not_ of right type, wrap it and add it. This shouldn't happen though.
thrown.add(Tuple.of(command + " " + next, e));
} finally {
args.setState(state);
}
}
// Phase one: test for what is required
if (requiresEconomy && !plugin.getEconHelper().economyServiceExists()) {
source.sendMessage(NucleusPlugin.getNucleus().getMessageProvider().getTextMessageWithFormat("command.economyrequired"));
return CommandResult.empty();
}
// Phase two: source type - test to see if the person in question can execute this command.
castedSource = checkSourceType(source);
// Phase three - test the permission.
if (!testPermissionOnSubject(castedSource)) {
throw new CommandPermissionException();
}
if (!this.hasExecutor) {
if (thrown.isEmpty()) {
// OK, we just process the usage command instead.
return this.usageCommand.process(source, "", args.nextIfPresent().map(String::toLowerCase).orElse(null));
} else {
throw new NucleusCommandException(thrown);
}
}
// Phase four - create the context and parse the arguments.
this.argumentParser.parse(source, args, context);
if (args.hasNext()) {
thrown.add(Tuple.of(command, new NucleusArgumentParseException(Text.of(TextColors.RED, "Too many arguments"), args.getRaw(), args.getRawPosition(), Text.of(getSimpleUsage(source)), getChildrenUsage(source).orElse(null), true)));
throw new NucleusCommandException(thrown, allowFallback(source, args, context));
}
} catch (NucleusCommandException nce) {
throw nce;
} catch (ArgumentParseException ape) {
// get the command to get the usage/subs from.
thrown.add(Tuple.of(command, NucleusArgumentParseException.from(ape, Text.of(getSimpleUsage(source)), getChildrenUsage(source).orElse(null))));
throw new NucleusCommandException(thrown, allowFallback(source, args, context));
} catch (CommandException ex) {
// Errors at this point are expected, so we'll run with it - no need for debug mode checks.
thrown.add(Tuple.of(command, ex));
throw new NucleusCommandException(thrown, allowFallback(source, args, context));
} catch (Throwable throwable) {
String m;
if (throwable.getMessage() == null) {
m = "null";
} else {
m = throwable.getMessage();
}
thrown.add(Tuple.of(command, new CommandException(Nucleus.getNucleus().getMessageProvider().getTextMessageWithFormat("command.exception.unexpected", m), throwable)));
// this is on demand, so we should throw it.
throwable.printStackTrace();
throw new NucleusCommandException(thrown, allowFallback(source, args, context));
}
try {
commandTimings.startTimingIfSync();
ContinueMode mode = preProcessChecks(castedSource, context);
if (!mode.cont) {
return mode.returnType;
}
if (castedSource instanceof Player) {
@SuppressWarnings("unchecked") ContinueMode cm = runChecks((Player) castedSource, context);
if (!cm.cont) {
return cm.returnType;
}
}
// If we're running async...
if (isAsync) {
// Create an executor that runs the command async.
plugin.getLogger().debug("Running " + this.getClass().getName() + " in async mode.");
Sponge.getScheduler().createAsyncExecutor(plugin).execute(() -> onExecute(castedSource, context));
// Tell Sponge we're done.
return CommandResult.success();
}
return onExecute(castedSource, context);
} finally {
commandTimings.stopTimingIfSync();
}
}
Aggregations