Search in sources :

Example 1 with CommandArgs

use of org.spongepowered.api.command.args.CommandArgs in project SpongeAPI by SpongePowered.

the class CommandSpec method getSuggestions.

@Override
public List<String> getSuggestions(CommandSource source, String arguments, @Nullable Location<World> targetPos) throws CommandException {
    CommandArgs args = new CommandArgs(arguments, getInputTokenizer().tokenize(arguments, true));
    CommandContext ctx = new CommandContext();
    if (targetPos != null) {
        ctx.putArg(CommandContext.TARGET_BLOCK_ARG, targetPos);
    }
    ctx.putArg(CommandContext.TAB_COMPLETION, true);
    return complete(source, args, ctx);
}
Also used : CommandArgs(org.spongepowered.api.command.args.CommandArgs) CommandContext(org.spongepowered.api.command.args.CommandContext)

Example 2 with CommandArgs

use of org.spongepowered.api.command.args.CommandArgs in project LanternServer by LanternPowered.

the class CommandTime method completeSpec.

@Override
public void completeSpec(PluginContainer pluginContainer, CommandSpec.Builder specBuilder) {
    final Map<String, Integer> presets = new HashMap<>();
    presets.put("day", 1000);
    presets.put("night", 13000);
    specBuilder.arguments(GenericArguments.flags().valueFlag(GenericArguments.world(CommandHelper.WORLD_KEY), "-world", "w").buildWith(GenericArguments.none())).child(CommandSpec.builder().arguments(new CommandElement(Text.of("value")) {

        @Nullable
        @Override
        protected Object parseValue(CommandSource source, CommandArgs args) throws ArgumentParseException {
            final String input = args.next().toLowerCase();
            // Try to use one of the presets first
            if (presets.containsKey(input)) {
                return presets.get(input);
            }
            try {
                return Integer.parseInt(input);
            } catch (NumberFormatException ex) {
                throw args.createError(t("Expected an integer or a valid preset, but input '%s' was not", input));
            }
        }

        @Override
        public List<String> complete(CommandSource src, CommandArgs args, CommandContext context) {
            final String prefix = args.nextIfPresent().orElse("");
            return presets.keySet().stream().filter(new StartsWithPredicate(prefix)).collect(ImmutableList.toImmutableList());
        }
    }).executor((src, args) -> {
        WorldProperties world = CommandHelper.getWorldProperties(src, args);
        int time = args.<Integer>getOne("value").get();
        world.setWorldTime(time);
        src.sendMessage(t("commands.time.set", time));
        return CommandResult.success();
    }).build(), "set").child(CommandSpec.builder().arguments(GenericArguments.integer(Text.of("value"))).executor((src, args) -> {
        WorldProperties world = CommandHelper.getWorldProperties(src, args);
        int time = args.<Integer>getOne("value").get();
        world.setWorldTime(world.getWorldTime() + time);
        src.sendMessage(t("commands.time.added", time));
        return CommandResult.success();
    }).build(), "add").child(CommandSpec.builder().arguments(GenericArguments2.enumValue(Text.of("value"), QueryType.class)).executor((src, args) -> {
        WorldProperties world = CommandHelper.getWorldProperties(src, args);
        QueryType queryType = args.<QueryType>getOne("value").get();
        int result;
        switch(queryType) {
            case DAYTIME:
                result = (int) (world.getWorldTime() % Integer.MAX_VALUE);
                break;
            case GAMETIME:
                result = (int) (world.getTotalTime() % Integer.MAX_VALUE);
                break;
            case DAY:
                result = (int) (world.getTotalTime() / 24000);
                break;
            default:
                throw new IllegalStateException("Unknown query type: " + queryType);
        }
        src.sendMessage(t("commands.time.query", result));
        return CommandResult.builder().successCount(1).queryResult(result).build();
    }).build(), "query");
}
Also used : CommandArgs(org.spongepowered.api.command.args.CommandArgs) CommandResult(org.spongepowered.api.command.CommandResult) CommandHelper.getWorld(org.lanternpowered.server.command.CommandHelper.getWorld) TranslationHelper.t(org.lanternpowered.server.text.translation.TranslationHelper.t) CommandSource(org.spongepowered.api.command.CommandSource) HashMap(java.util.HashMap) ArgumentParseException(org.spongepowered.api.command.args.ArgumentParseException) CommandArgs(org.spongepowered.api.command.args.CommandArgs) CommandElement(org.spongepowered.api.command.args.CommandElement) GenericArguments(org.spongepowered.api.command.args.GenericArguments) CommandSpec(org.spongepowered.api.command.spec.CommandSpec) List(java.util.List) ImmutableList(com.google.common.collect.ImmutableList) CommandContext(org.spongepowered.api.command.args.CommandContext) Text(org.spongepowered.api.text.Text) StartsWithPredicate(org.spongepowered.api.util.StartsWithPredicate) GenericArguments2(org.lanternpowered.server.command.element.GenericArguments2) Map(java.util.Map) WorldProperties(org.spongepowered.api.world.storage.WorldProperties) PluginContainer(org.spongepowered.api.plugin.PluginContainer) Nullable(javax.annotation.Nullable) CommandContext(org.spongepowered.api.command.args.CommandContext) HashMap(java.util.HashMap) StartsWithPredicate(org.spongepowered.api.util.StartsWithPredicate) CommandSource(org.spongepowered.api.command.CommandSource) CommandElement(org.spongepowered.api.command.args.CommandElement) WorldProperties(org.spongepowered.api.world.storage.WorldProperties)

Example 3 with CommandArgs

use of org.spongepowered.api.command.args.CommandArgs in project LanternServer by LanternPowered.

the class CommandGameRule method completeSpec.

@Override
public void completeSpec(PluginContainer pluginContainer, CommandSpec.Builder specBuilder) {
    final Collection<String> defaultRules = Sponge.getRegistry().getDefaultGameRules();
    final ThreadLocal<RuleType<?>> currentRule = new ThreadLocal<>();
    specBuilder.arguments(GenericArguments.flags().valueFlag(GenericArguments.world(CommandHelper.WORLD_KEY), "-world", "w").buildWith(GenericArguments.none()), new CommandElement(Text.of("rule")) {

        @Nullable
        @Override
        protected Object parseValue(CommandSource source, CommandArgs args) throws ArgumentParseException {
            RuleType<?> ruleType = RuleType.getOrCreate(args.next(), RuleDataTypes.STRING, "");
            currentRule.set(ruleType);
            return ruleType;
        }

        @Override
        public List<String> complete(CommandSource src, CommandArgs args, CommandContext context) {
            final String prefix = args.nextIfPresent().orElse("");
            return defaultRules.stream().filter(new StartsWithPredicate(prefix)).collect(ImmutableList.toImmutableList());
        }
    }, new CommandElement(Text.of("value")) {

        private final List<String> booleanRuleSuggestions = ImmutableList.of("true", "false");

        @Nullable
        @Override
        protected Object parseValue(CommandSource source, CommandArgs args) throws ArgumentParseException {
            RuleType<?> ruleType = currentRule.get();
            currentRule.remove();
            try {
                return ruleType.getDataType().parse(args.next());
            } catch (IllegalArgumentException e) {
                throw args.createError(t(e.getMessage()));
            }
        }

        @Override
        public List<String> complete(CommandSource src, CommandArgs args, CommandContext context) {
            RuleType<?> ruleType = context.<RuleType<?>>getOne("rule").get();
            if (ruleType.getDataType() == RuleDataTypes.BOOLEAN) {
                // match the first part of the string
                return this.booleanRuleSuggestions;
            }
            return Collections.emptyList();
        }
    }).executor((src, args) -> {
        WorldProperties world = CommandHelper.getWorldProperties(src, args);
        Object value = args.getOne("value").get();
        RuleType ruleType = args.<RuleType>getOne("rule").get();
        ((LanternWorldProperties) world).getRules().getOrCreateRule(ruleType).setValue(value);
        src.sendMessage(t("commands.gamerule.success", ruleType.getName(), ruleType.getDataType().serialize(value)));
        return CommandResult.success();
    });
}
Also used : CommandArgs(org.spongepowered.api.command.args.CommandArgs) CommandContext(org.spongepowered.api.command.args.CommandContext) RuleType(org.lanternpowered.server.world.rules.RuleType) StartsWithPredicate(org.spongepowered.api.util.StartsWithPredicate) CommandSource(org.spongepowered.api.command.CommandSource) CommandElement(org.spongepowered.api.command.args.CommandElement) List(java.util.List) ImmutableList(com.google.common.collect.ImmutableList) LanternWorldProperties(org.lanternpowered.server.world.LanternWorldProperties) LanternWorldProperties(org.lanternpowered.server.world.LanternWorldProperties) WorldProperties(org.spongepowered.api.world.storage.WorldProperties)

Example 4 with CommandArgs

use of org.spongepowered.api.command.args.CommandArgs 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 5 with CommandArgs

use of org.spongepowered.api.command.args.CommandArgs in project LanternServer by LanternPowered.

the class CommandListBans method completeSpec.

@Override
public void completeSpec(PluginContainer pluginContainer, CommandSpec.Builder specBuilder) {
    specBuilder.arguments(GenericArguments.optional(new CommandElement(Text.of("ips")) {

        private final List<String> choices = Arrays.asList("ips", "players");

        @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 start = args.nextIfPresent().orElse("").toLowerCase();
            return this.choices.stream().filter(new StartsWithPredicate(start)).collect(Collectors.toList());
        }
    })).executor((src, args) -> {
        final boolean showIpBans = "ips".equalsIgnoreCase(args.<String>getOne("ips").orElse(null));
        final BanService banService = Lantern.getGame().getServiceManager().provideUnchecked(BanService.class);
        List<String> entries;
        if (showIpBans) {
            entries = banService.getIpBans().stream().map(ban -> ban.getAddress().getHostAddress()).collect(Collectors.toList());
            src.sendMessage(t("commands.banlist.ips", entries.size()));
        } else {
            entries = banService.getProfileBans().stream().map(ban -> ban.getProfile().getName().orElse(ban.getProfile().getUniqueId().toString())).collect(Collectors.toList());
            src.sendMessage(t("commands.banlist.players", entries.size()));
        }
        src.sendMessage(Text.of(Joiner.on(", ").join(entries)));
        return CommandResult.success();
    });
}
Also used : CommandArgs(org.spongepowered.api.command.args.CommandArgs) CommandContext(org.spongepowered.api.command.args.CommandContext) ArgumentParseException(org.spongepowered.api.command.args.ArgumentParseException) StartsWithPredicate(org.spongepowered.api.util.StartsWithPredicate) CommandSource(org.spongepowered.api.command.CommandSource) CommandElement(org.spongepowered.api.command.args.CommandElement) List(java.util.List) BanService(org.spongepowered.api.service.ban.BanService) Nullable(javax.annotation.Nullable)

Aggregations

CommandArgs (org.spongepowered.api.command.args.CommandArgs)21 CommandContext (org.spongepowered.api.command.args.CommandContext)12 ArrayList (java.util.ArrayList)10 CommandSource (org.spongepowered.api.command.CommandSource)10 CommandElement (org.spongepowered.api.command.args.CommandElement)8 List (java.util.List)7 Test (org.junit.Test)7 Nullable (javax.annotation.Nullable)6 ArgumentParseException (org.spongepowered.api.command.args.ArgumentParseException)6 StartsWithPredicate (org.spongepowered.api.util.StartsWithPredicate)6 Text (org.spongepowered.api.text.Text)5 TranslationHelper.t (org.lanternpowered.server.text.translation.TranslationHelper.t)4 CommandResult (org.spongepowered.api.command.CommandResult)4 GenericArguments (org.spongepowered.api.command.args.GenericArguments)4 CommandSpec (org.spongepowered.api.command.spec.CommandSpec)4 PluginContainer (org.spongepowered.api.plugin.PluginContainer)4 ImmutableList (com.google.common.collect.ImmutableList)3 Collectors (java.util.stream.Collectors)3 CommandException (org.spongepowered.api.command.CommandException)3 HashMap (java.util.HashMap)2