Search in sources :

Example 1 with CommandCallable

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();
        }
    }
}
Also used : PluginContainer(org.spongepowered.api.plugin.PluginContainer) ImmutableCommandMapping(org.spongepowered.api.command.ImmutableCommandMapping) CommandMapping(org.spongepowered.api.command.CommandMapping) CommandException(org.spongepowered.api.command.CommandException) CommandNotFoundException(org.spongepowered.api.command.CommandNotFoundException) CommandCallable(org.spongepowered.api.command.CommandCallable)

Example 2 with CommandCallable

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();
    });
}
Also used : ConsoleSource(org.spongepowered.api.command.source.ConsoleSource) CommandCallable(org.spongepowered.api.command.CommandCallable) CommandMapping(org.spongepowered.api.command.CommandMapping) Collections2(com.google.common.collect.Collections2) ArgumentParseException(org.spongepowered.api.command.args.ArgumentParseException) CommandArgs(org.spongepowered.api.command.args.CommandArgs) GenericArguments(org.spongepowered.api.command.args.GenericArguments) TreeSet(java.util.TreeSet) PaginationList(org.spongepowered.api.service.pagination.PaginationList) CommandContext(org.spongepowered.api.command.args.CommandContext) Text(org.spongepowered.api.text.Text) StartsWithPredicate(org.spongepowered.api.util.StartsWithPredicate) PluginContainer(org.spongepowered.api.plugin.PluginContainer) TextColors(org.spongepowered.api.text.format.TextColors) Nullable(javax.annotation.Nullable) CommandResult(org.spongepowered.api.command.CommandResult) TextActions(org.spongepowered.api.text.action.TextActions) TranslationHelper.t(org.lanternpowered.server.text.translation.TranslationHelper.t) CommandSource(org.spongepowered.api.command.CommandSource) TextStyles(org.spongepowered.api.text.format.TextStyles) Collection(java.util.Collection) Sponge(org.spongepowered.api.Sponge) PaginationService(org.spongepowered.api.service.pagination.PaginationService) Field(java.lang.reflect.Field) CommandElement(org.spongepowered.api.command.args.CommandElement) Collectors(java.util.stream.Collectors) CommandSpec(org.spongepowered.api.command.spec.CommandSpec) CommandException(org.spongepowered.api.command.CommandException) List(java.util.List) Lantern(org.lanternpowered.server.game.Lantern) Optional(java.util.Optional) Comparator(java.util.Comparator) CommandContext(org.spongepowered.api.command.args.CommandContext) ArgumentParseException(org.spongepowered.api.command.args.ArgumentParseException) StartsWithPredicate(org.spongepowered.api.util.StartsWithPredicate) CommandCallable(org.spongepowered.api.command.CommandCallable) CommandSpec(org.spongepowered.api.command.spec.CommandSpec) TreeSet(java.util.TreeSet) CommandMapping(org.spongepowered.api.command.CommandMapping) PaginationList(org.spongepowered.api.service.pagination.PaginationList) List(java.util.List) CommandArgs(org.spongepowered.api.command.args.CommandArgs) Text(org.spongepowered.api.text.Text) CommandException(org.spongepowered.api.command.CommandException) CommandSource(org.spongepowered.api.command.CommandSource) CommandElement(org.spongepowered.api.command.args.CommandElement) ConsoleSource(org.spongepowered.api.command.source.ConsoleSource) Nullable(javax.annotation.Nullable)

Example 3 with CommandCallable

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();
    }
}
Also used : CommandPermissionException(org.spongepowered.api.command.CommandPermissionException) Player(org.spongepowered.api.entity.living.player.Player) CommandContext(org.spongepowered.api.command.args.CommandContext) ArgumentParseException(org.spongepowered.api.command.args.ArgumentParseException) CommandException(org.spongepowered.api.command.CommandException) CommandCallable(org.spongepowered.api.command.CommandCallable) Tuple(org.spongepowered.api.util.Tuple)

Aggregations

CommandCallable (org.spongepowered.api.command.CommandCallable)3 CommandException (org.spongepowered.api.command.CommandException)3 CommandMapping (org.spongepowered.api.command.CommandMapping)2 ArgumentParseException (org.spongepowered.api.command.args.ArgumentParseException)2 CommandContext (org.spongepowered.api.command.args.CommandContext)2 PluginContainer (org.spongepowered.api.plugin.PluginContainer)2 Collections2 (com.google.common.collect.Collections2)1 Field (java.lang.reflect.Field)1 Collection (java.util.Collection)1 Comparator (java.util.Comparator)1 List (java.util.List)1 Optional (java.util.Optional)1 TreeSet (java.util.TreeSet)1 Collectors (java.util.stream.Collectors)1 Nullable (javax.annotation.Nullable)1 Lantern (org.lanternpowered.server.game.Lantern)1 TranslationHelper.t (org.lanternpowered.server.text.translation.TranslationHelper.t)1 Sponge (org.spongepowered.api.Sponge)1 CommandNotFoundException (org.spongepowered.api.command.CommandNotFoundException)1 CommandPermissionException (org.spongepowered.api.command.CommandPermissionException)1