use of org.spongepowered.api.command.args.CommandArgs in project LanternServer by LanternPowered.
the class CommandSetData method completeSpec.
@Override
public void completeSpec(PluginContainer pluginContainer, CommandSpec.Builder specBuilder) {
final ThreadLocal<Key<?>> currentKey = new ThreadLocal<>();
specBuilder.arguments(GenericArguments.playerOrSource(Text.of("player")), new PatternMatchingCommandElement(Text.of("key")) {
@Override
protected Iterable<String> getChoices(CommandSource source) {
return Sponge.getGame().getRegistry().getAllOf(Key.class).stream().map(Key::getId).collect(Collectors.toList());
}
@Override
protected Object getValue(String choice) throws IllegalArgumentException {
final Optional<Key> ret = Sponge.getGame().getRegistry().getType(Key.class, choice);
if (!ret.isPresent()) {
throw new IllegalArgumentException("Invalid input " + choice + " was found");
}
currentKey.set(ret.get());
return ret.get();
}
}, new CommandElement(Text.of("data")) {
@Nullable
@Override
protected Object parseValue(CommandSource source, CommandArgs args) throws ArgumentParseException {
args.next();
final String content = args.getRaw().substring(args.getRawPosition()).trim();
while (args.hasNext()) {
args.next();
}
final Object data;
try {
// Don't be too strict
data = JsonDataFormat.read(content, true).orElse(null);
} catch (IOException e) {
throw args.createError(t("Invalid json data: %s\nError: %s", content, e.getMessage()));
}
final Key key = currentKey.get();
final TypeToken<?> typeToken = key.getElementToken();
if (content.isEmpty()) {
return null;
}
final DataTypeSerializer dataTypeSerializer = Lantern.getGame().getDataManager().getTypeSerializer(typeToken).orElse(null);
if (dataTypeSerializer == null) {
throw args.createError(Text.of("Unable to deserialize the data key value: {}, " + "no supported deserializer exists.", key.getId()));
} else {
final DataTypeSerializerContext context = Lantern.getGame().getDataManager().getTypeSerializerContext();
try {
// Put it in a holder object, the command element separates iterable objects
return new ValueHolder(dataTypeSerializer.deserialize(typeToken, context, data));
} catch (InvalidDataException e) {
throw args.createError(t("Invalid data: %s", e.getMessage()));
}
}
}
@Override
public List<String> complete(CommandSource src, CommandArgs args, CommandContext context) {
return new ArrayList<>();
}
}).executor((src, args) -> {
final Player target = args.<Player>getOne("player").get();
final Key key = args.<Key>getOne("key").get();
final Object data = args.<ValueHolder>getOne("data").get().data;
target.offer(key, data);
src.sendMessage(t("Successfully offered the data for the key %s to the player %s", key.getId(), target.getName()));
return CommandResult.success();
});
}
use of org.spongepowered.api.command.args.CommandArgs in project LanternServer by LanternPowered.
the class CommandOp method completeSpec.
@Override
public void completeSpec(PluginContainer pluginContainer, CommandSpec.Builder specBuilder) {
specBuilder.arguments(new CommandElement(Text.of("player")) {
@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 prefix = args.nextIfPresent().orElse("");
final UserConfig<OpsEntry> config = Lantern.getGame().getOpsConfig();
return Lantern.getGame().getGameProfileManager().getCache().getProfiles().stream().filter(p -> p.getName().isPresent() && !config.getEntryByUUID(p.getUniqueId()).isPresent()).map(p -> p.getName().get()).filter(new StartsWithPredicate(prefix)).collect(ImmutableList.toImmutableList());
}
}, GenericArguments.optional(GenericArguments.integer(Text.of("level")))).executor((src, args) -> {
String playerName = args.<String>getOne("player").get();
UserConfig<OpsEntry> config = Lantern.getGame().getOpsConfig();
if (!(src instanceof ConsoleSource) && args.hasAny("level")) {
throw new CommandException(Text.of("Only the console may specify the op level."));
}
int opLevel = args.<Integer>getOne("level").orElse(Lantern.getGame().getGlobalConfig().getDefaultOpPermissionLevel());
Lantern.getGame().getGameProfileManager().get(playerName).whenComplete((profile, error) -> {
if (error != null) {
src.sendMessage(t("commands.op.failed", playerName));
} else {
src.sendMessage(t("commands.op.success", playerName));
config.addEntry(new OpsEntry(((LanternGameProfile) profile).withoutProperties(), opLevel));
}
});
return CommandResult.success();
});
}
use of org.spongepowered.api.command.args.CommandArgs in project Nucleus by NucleusPowered.
the class AbstractCommand method getSuggestions.
@Override
public List<String> getSuggestions(CommandSource source, String arguments, @Nullable Location<World> targetPosition) throws CommandException {
List<SingleArg> singleArgs = Lists.newArrayList(tokeniser.tokenize(arguments, false));
// If we end with a space - then we add another argument.
if (arguments.isEmpty() || arguments.endsWith(" ")) {
singleArgs.add(new SingleArg("", arguments.length() - 1, arguments.length() - 1));
}
final CommandArgs args = new CommandArgs(arguments, singleArgs);
final List<String> options = Lists.newArrayList();
CommandContext context = new CommandContext();
// We don't care for the value.
context.putArg(COMPLETION_ARG, true);
// Subcommand
Object state = args.getState();
options.addAll(this.dispatcher.getSuggestions(source, arguments, targetPosition));
args.setState(state);
options.addAll(this.argumentParser.complete(source, args, context));
return options.stream().distinct().collect(Collectors.toList());
}
use of org.spongepowered.api.command.args.CommandArgs in project Nucleus by NucleusPowered.
the class IfConditionElseArgumentTests method process.
private boolean process(BiPredicate<CommandSource, CommandContext> cond) throws Exception {
// Get the element
CommandSource source = Mockito.mock(CommandSource.class);
CommandArgs args = new CommandArgs("", Lists.newArrayList());
CommandContext context = new CommandContext();
new IfConditionElseArgument(new TrueArgument(), new FalseArgument(), cond).parse(source, args, context);
return context.<Boolean>getOne("key").orElseThrow(NullPointerException::new);
}
use of org.spongepowered.api.command.args.CommandArgs in project Nucleus by NucleusPowered.
the class NoCostArgumentTests method getNoCostArgument.
private CommandContext getNoCostArgument(CommandElement toWrap, CommandContext cc) throws ArgumentParseException {
CommandSource s = Mockito.mock(Player.class);
CommandArgs ca = new CommandArgs("", new ArrayList<>());
NoModifiersArgument<?> nca = new NoModifiersArgument<>(toWrap, (c, o) -> true);
nca.parse(s, ca, cc);
return cc;
}
Aggregations