com.mojang.brigadier.tree.CommandNode Java Examples

The following examples show how to use com.mojang.brigadier.tree.CommandNode. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CommandDispatcherUsagesTest.java    From brigadier with MIT License 6 votes vote down vote up
@Test
public void testSmartUsage_root() throws Exception {
    final Map<CommandNode<Object>, String> results = subject.getSmartUsage(subject.getRoot(), source);
    assertThat(results, equalTo(ImmutableMap.builder()
        .put(get("a"), "a (1|2)")
        .put(get("b"), "b 1")
        .put(get("c"), "c")
        .put(get("e"), "e [1]")
        .put(get("f"), "f (1|2)")
        .put(get("g"), "g [1]")
        .put(get("h"), "h [1|2|3]")
        .put(get("i"), "i [1|2]")
        .put(get("j"), "j ...")
        .put(get("k"), "k -> h")
        .build()
    ));
}
 
Example #2
Source File: CommandDispatcher.java    From brigadier with MIT License 6 votes vote down vote up
private void getAllUsage(final CommandNode<S> node, final S source, final ArrayList<String> result, final String prefix, final boolean restricted) {
    if (restricted && !node.canUse(source)) {
        return;
    }

    if (node.getCommand() != null) {
        result.add(prefix);
    }

    if (node.getRedirect() != null) {
        final String redirect = node.getRedirect() == root ? "..." : "-> " + node.getRedirect().getUsageText();
        result.add(prefix.isEmpty() ? node.getUsageText() + ARGUMENT_SEPARATOR + redirect : prefix + ARGUMENT_SEPARATOR + redirect);
    } else if (!node.getChildren().isEmpty()) {
        for (final CommandNode<S> child : node.getChildren()) {
            getAllUsage(child, source, result, prefix.isEmpty() ? child.getUsageText() : prefix + ARGUMENT_SEPARATOR + child.getUsageText(), restricted);
        }
    }
}
 
Example #3
Source File: BrigadierRemover.java    From multiconnect with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
public boolean remove() {
    if (thisNode == null || parentNode == null) {
        return false;
    }

    Map<String, CommandNode<S>> parentChildren;
    Map<String, LiteralCommandNode<S>> parentLiterals;
    Map<String, ArgumentCommandNode<S, ?>> parentArguments;
    try {
        parentChildren = (Map<String, CommandNode<S>>) CHILDREN_FIELD.get(parentNode);
        parentLiterals = thisNode instanceof LiteralCommandNode ? (Map<String, LiteralCommandNode<S>>) LITERALS_FIELD.get(parentNode) : null;
        parentArguments = thisNode instanceof ArgumentCommandNode ? (Map<String, ArgumentCommandNode<S, ?>>) ARGUMENTS_FIELD.get(parentNode) : null;
    } catch (ReflectiveOperationException e) {
        throw new AssertionError(e);
    }

    parentChildren.remove(thisNode.getName());
    if (thisNode instanceof LiteralCommandNode) {
        parentLiterals.remove(thisNode.getName());
    } else if (thisNode instanceof ArgumentCommandNode) {
        parentArguments.remove(thisNode.getName());
    }

    return true;
}
 
Example #4
Source File: CommandDispatcher.java    From brigadier with MIT License 6 votes vote down vote up
/**
 * Finds a valid path to a given node on the command tree.
 *
 * <p>There may theoretically be multiple paths to a node on the tree, especially with the use of forking or redirecting.
 * As such, this method makes no guarantees about which path it finds. It will not look at forks or redirects,
 * and find the first instance of the target node on the tree.</p>
 *
 * <p>The only guarantee made is that for the same command tree and the same version of this library, the result of
 * this method will <b>always</b> be a valid input for {@link #findNode(Collection)}, which should return the same node
 * as provided to this method.</p>
 *
 * @param target the target node you are finding a path for
 * @return a path to the resulting node, or an empty list if it was not found
 */
public Collection<String> getPath(final CommandNode<S> target) {
    final List<List<CommandNode<S>>> nodes = new ArrayList<>();
    addPaths(root, nodes, new ArrayList<>());

    for (final List<CommandNode<S>> list : nodes) {
        if (list.get(list.size() - 1) == target) {
            final List<String> result = new ArrayList<>(list.size());
            for (final CommandNode<S> node : list) {
                if (node != root) {
                    result.add(node.getName());
                }
            }
            return result;
        }
    }

    return Collections.emptyList();
}
 
Example #5
Source File: CommandContextTest.java    From brigadier with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testEquals() throws Exception {
    final Object otherSource = new Object();
    final Command<Object> command = mock(Command.class);
    final Command<Object> otherCommand = mock(Command.class);
    final CommandNode<Object> rootNode = mock(CommandNode.class);
    final CommandNode<Object> otherRootNode = mock(CommandNode.class);
    final CommandNode<Object> node = mock(CommandNode.class);
    final CommandNode<Object> otherNode = mock(CommandNode.class);
    new EqualsTester()
        .addEqualityGroup(new CommandContextBuilder<>(dispatcher, source, rootNode, 0).build(""), new CommandContextBuilder<>(dispatcher, source, rootNode, 0).build(""))
        .addEqualityGroup(new CommandContextBuilder<>(dispatcher, source, otherRootNode, 0).build(""), new CommandContextBuilder<>(dispatcher, source, otherRootNode, 0).build(""))
        .addEqualityGroup(new CommandContextBuilder<>(dispatcher, otherSource, rootNode, 0).build(""), new CommandContextBuilder<>(dispatcher, otherSource, rootNode, 0).build(""))
        .addEqualityGroup(new CommandContextBuilder<>(dispatcher, source, rootNode, 0).withCommand(command).build(""), new CommandContextBuilder<>(dispatcher, source, rootNode, 0).withCommand(command).build(""))
        .addEqualityGroup(new CommandContextBuilder<>(dispatcher, source, rootNode, 0).withCommand(otherCommand).build(""), new CommandContextBuilder<>(dispatcher, source, rootNode, 0).withCommand(otherCommand).build(""))
        .addEqualityGroup(new CommandContextBuilder<>(dispatcher, source, rootNode, 0).withArgument("foo", new ParsedArgument<>(0, 1, 123)).build("123"), new CommandContextBuilder<>(dispatcher, source, rootNode, 0).withArgument("foo", new ParsedArgument<>(0, 1, 123)).build("123"))
        .addEqualityGroup(new CommandContextBuilder<>(dispatcher, source, rootNode, 0).withNode(node, StringRange.between(0, 3)).withNode(otherNode, StringRange.between(4, 6)).build("123 456"), new CommandContextBuilder<>(dispatcher, source, rootNode, 0).withNode(node, StringRange.between(0, 3)).withNode(otherNode, StringRange.between(4, 6)).build("123 456"))
        .addEqualityGroup(new CommandContextBuilder<>(dispatcher, source, rootNode, 0).withNode(otherNode, StringRange.between(0, 3)).withNode(node, StringRange.between(4, 6)).build("123 456"), new CommandContextBuilder<>(dispatcher, source, rootNode, 0).withNode(otherNode, StringRange.between(0, 3)).withNode(node, StringRange.between(4, 6)).build("123 456"))
        .testEquals();
}
 
Example #6
Source File: CommandAPIHandler.java    From 1.13-Command-API with Apache License 2.0 6 votes vote down vote up
/**
 * Unregisters a command from the NMS command graph.
 * 
 * @param commandName the name of the command to unregister
 * @param force       whether the unregistration system should attempt to remove
 *                    all instances of the command, regardless of whether they
 *                    have been registered by Minecraft, Bukkit or Spigot etc.
 */
protected void unregister(String commandName, boolean force) {
	try {
		if (CommandAPIMain.getConfiguration().hasVerboseOutput()) {
			CommandAPIMain.getLog().info("Unregistering command /" + commandName);
		}

		// Get the child nodes from the loaded dispatcher class
		Field children = getField(CommandNode.class, "children");
		Map<String, CommandNode<?>> commandNodeChildren = (Map<String, CommandNode<?>>) children
				.get(dispatcher.getRoot());

		if (force) {
			// Remove them by force
			List<String> keysToRemove = new ArrayList<>();
			commandNodeChildren.keySet().stream().filter(s -> s.contains(":"))
					.filter(s -> s.split(":")[1].equalsIgnoreCase(commandName)).forEach(keysToRemove::add);
			keysToRemove.forEach(commandNodeChildren::remove);
		}

		// Otherwise, just remove them normally
		commandNodeChildren.remove(commandName);
	} catch (SecurityException | IllegalArgumentException | IllegalAccessException e) {
		e.printStackTrace();
	}
}
 
Example #7
Source File: DispatcherTest.java    From Chimera with MIT License 5 votes vote down vote up
@Test
void register_commands() {
    CommandNode<CommandSender> a = Literal.of("a").build();
    var commands = Map.of("a", a);
    
    dispatcher.register(commands);
    
    assertSame(a, dispatcher.getRoot().getChild("a"));
}
 
Example #8
Source File: CommandHelper.java    From BoundingBoxOutlineReloaded with MIT License 5 votes vote down vote up
static boolean lastNodeIsLiteral(CommandContext<CommandSource> context, String literal) {
    CommandNode lastNode = getLastNode(context);
    if (lastNode instanceof LiteralCommandNode) {
        LiteralCommandNode literalCommandNode = (LiteralCommandNode) lastNode;
        return literalCommandNode.getLiteral().equals(literal);
    }
    return false;
}
 
Example #9
Source File: SpongeCommands.java    From BlueMap with MIT License 5 votes vote down vote up
@Override
public Text getUsage(CommandSource source) {
	CommandNode<CommandSource> node = dispatcher.getRoot().getChild(label);
	if (node == null) return Text.of("/" + label);
	
	List<Text> lines = new ArrayList<>();
	for (String usageString : dispatcher.getSmartUsage(node, source).values()) {
		lines.add(Text.of(TextColors.WHITE, "/" + label + " ", TextColors.GRAY, usageString));
	}
	
	return Text.joinWith(Text.NEW_LINE, lines);
}
 
Example #10
Source File: BukkitCommands.java    From BlueMap with MIT License 5 votes vote down vote up
public Collection<BukkitCommand> getRootCommands(){
	Collection<BukkitCommand> rootCommands = new ArrayList<>();
	
	for (CommandNode<CommandSender> node : this.dispatcher.getRoot().getChildren()) {
		rootCommands.add(new CommandProxy(node.getName()));
	}
	
	return rootCommands;
}
 
Example #11
Source File: SpreadPlayersCommand.java    From multiconnect with MIT License 5 votes vote down vote up
public static void register(CommandDispatcher<CommandSource> dispatcher) {
    CommandNode<CommandSource> respectTeams = argument("respectTeams", bool())
            .executes(ctx -> 0)
            .build();
    CommandNode<CommandSource> target = argument("target", entities())
            .executes(ctx -> 0)
            .redirect(respectTeams)
            .build();
    respectTeams.addChild(target);
    dispatcher.register(literal("spreadplayers")
        .then(argument("center", vec2())
            .then(argument("spreadDistance", doubleArg(0))
                .then(argument("maxRange", doubleArg(1))
                    .then(respectTeams)))));
}
 
Example #12
Source File: ScoreboardCommand.java    From multiconnect with MIT License 5 votes vote down vote up
private static CommandNode<CommandSource> addPlayerList(ArgumentBuilder<CommandSource, ?> parentBuilder) {
    CommandNode<CommandSource> parent = parentBuilder.executes(ctx -> 0).build();
    CommandNode<CommandSource> child = argument("player", entities())
            .executes(ctx -> 0)
            .redirect(parent)
            .build();
    parent.addChild(child);
    return parent;
}
 
Example #13
Source File: SpongeCommands.java    From BlueMap with MIT License 5 votes vote down vote up
public Collection<SpongeCommandProxy> getRootCommands(){
	Collection<SpongeCommandProxy> rootCommands = new ArrayList<>();
	
	for (CommandNode<CommandSource> node : this.dispatcher.getRoot().getChildren()) {
		rootCommands.add(new SpongeCommandProxy(node.getName()));
	}
	
	return rootCommands;
}
 
Example #14
Source File: CommandArgumentType.java    From multiconnect with MIT License 5 votes vote down vote up
@Override
public Collection<String> getExamples() {
    return dispatcher.getRoot().getChildren().stream()
            .filter(it -> it instanceof LiteralCommandNode)
            .map(CommandNode::getName)
            .collect(Collectors.toList());
}
 
Example #15
Source File: CarpetScriptServer.java    From fabric-carpet with MIT License 5 votes vote down vote up
public CarpetScriptServer(MinecraftServer server)
{
    this.server = server;
    ScriptHost.systemGlobals.clear();
    events = new CarpetEventServer(server);
    modules = new HashMap<>();
    tickStart = 0L;
    stopAll = false;
    holyMoly = server.getCommandManager().getDispatcher().getRoot().getChildren().stream().map(CommandNode::getName).collect(Collectors.toSet());
    globalHost = CarpetScriptHost.create(this, null, false, null);
}
 
Example #16
Source File: Nodes.java    From Chimera with MIT License 5 votes vote down vote up
public B optionally(CommandNode<T> node) {
    then(node);
    for (var child : node.getChildren()) {
        then(child);
    }

    return getThis();
}
 
Example #17
Source File: ArgumentBuilderTest.java    From brigadier with MIT License 5 votes vote down vote up
@Test
public void testArguments() throws Exception {
    final RequiredArgumentBuilder<Object, ?> argument = argument("bar", integer());

    builder.then(argument);

    assertThat(builder.getArguments(), hasSize(1));
    assertThat(builder.getArguments(), hasItem((CommandNode<Object>) argument.build()));
}
 
Example #18
Source File: CommandDispatcherUsagesTest.java    From brigadier with MIT License 5 votes vote down vote up
@Test
public void testSmartUsage_h() throws Exception {
    final Map<CommandNode<Object>, String> results = subject.getSmartUsage(get("h"), source);
    assertThat(results, equalTo(ImmutableMap.builder()
        .put(get("h 1"), "[1] i")
        .put(get("h 2"), "[2] i ii")
        .put(get("h 3"), "[3]")
        .build()
    ));
}
 
Example #19
Source File: MutableTest.java    From Chimera with MIT License 5 votes vote down vote up
@ParameterizedTest
@MethodSource("mutables")
void setCommand(Mutable<CommandSender> mutable) {
    Command command = val -> 0;
    
    mutable.setCommand(command);
    
    assertEquals(command, ((CommandNode<?>) mutable).getCommand());
    if (mutable instanceof Aliasable<?>) {
        assertEquals(command, ((Aliasable<CommandSender>) mutable).aliases().get(0).getCommand());
    }
}
 
Example #20
Source File: MutableTest.java    From Chimera with MIT License 5 votes vote down vote up
@ParameterizedTest
@MethodSource("mutables")
void setRedirect(Mutable<CommandSender> mutable) {
    var destination = Literal.of("child").build();
    
    mutable.setRedirect(destination);
    
    assertEquals(destination, ((CommandNode<?>) mutable).getRedirect());
    if (mutable instanceof Aliasable<?>) {
        assertEquals(destination, ((Aliasable<CommandSender>) mutable).aliases().get(0).getRedirect());
    }
}
 
Example #21
Source File: MutableTest.java    From Chimera with MIT License 5 votes vote down vote up
@ParameterizedTest
@MethodSource("mutables")
void optionally(Mutable<CommandSender> mutable) {
    var command = (CommandNode<?>) mutable;

    assertEquals(2, command.getChildren().size());
    assertNotNull(command.getChild("optional"));
    assertNotNull(command.getChild("optional child"));
}
 
Example #22
Source File: Commands.java    From Chimera with MIT License 5 votes vote down vote up
public static Map<String, CommandNode<CommandSender>> of(aot.generation.TellCommand source) {
    var commands = new HashMap<String, CommandNode<CommandSender>>();

    var command = new Argument<>("players", source.a, null, REQUIREMENT, aot.generation.TellCommand.suggestions);

    var command0 = new Literal<>("tell", aot.generation.TellCommand::b, REQUIREMENT);
    Literal.alias(command0, "t");
    command0.addChild(command);

    commands.put(command0.getName(), command0);
    return commands;
}
 
Example #23
Source File: CommandDispatcher.java    From brigadier with MIT License 5 votes vote down vote up
private void addPaths(final CommandNode<S> node, final List<List<CommandNode<S>>> result, final List<CommandNode<S>> parents) {
    final List<CommandNode<S>> current = new ArrayList<>(parents);
    current.add(node);
    result.add(current);

    for (final CommandNode<S> child : node.getChildren()) {
        addPaths(child, result, current);
    }
}
 
Example #24
Source File: RequiredArgumentBuilder.java    From brigadier with MIT License 5 votes vote down vote up
public ArgumentCommandNode<S, T> build() {
    final ArgumentCommandNode<S, T> result = new ArgumentCommandNode<>(getName(), getType(), getCommand(), getRequirement(), getRedirect(), getRedirectModifier(), isFork(), getSuggestionsProvider());

    for (final CommandNode<S> argument : getArguments()) {
        result.addChild(argument);
    }

    return result;
}
 
Example #25
Source File: LiteralArgumentBuilder.java    From brigadier with MIT License 5 votes vote down vote up
@Override
public LiteralCommandNode<S> build() {
    final LiteralCommandNode<S> result = new LiteralCommandNode<>(getLiteral(), getCommand(), getRequirement(), getRedirect(), getRedirectModifier(), isFork());

    for (final CommandNode<S> argument : getArguments()) {
        result.addChild(argument);
    }

    return result;
}
 
Example #26
Source File: CommandContextBuilder.java    From brigadier with MIT License 5 votes vote down vote up
public CommandContextBuilder<S> withNode(final CommandNode<S> node, final StringRange range) {
    nodes.add(new ParsedCommandNode<>(node, range));
    this.range = StringRange.encompassing(this.range, range);
    this.modifier = node.getRedirectModifier();
    this.forks = node.isFork();
    return this;
}
 
Example #27
Source File: CommandContextBuilder.java    From brigadier with MIT License 5 votes vote down vote up
public SuggestionContext<S> findSuggestionContext(final int cursor) {
    if (range.getStart() <= cursor) {
        if (range.getEnd() < cursor) {
            if (child != null) {
                return child.findSuggestionContext(cursor);
            } else if (!nodes.isEmpty()) {
                final ParsedCommandNode<S> last = nodes.get(nodes.size() - 1);
                return new SuggestionContext<>(last.getNode(), last.getRange().getEnd() + 1);
            } else {
                return new SuggestionContext<>(rootNode, range.getStart());
            }
        } else {
            CommandNode<S> prev = rootNode;
            for (final ParsedCommandNode<S> node : nodes) {
                final StringRange nodeRange = node.getRange();
                if (nodeRange.getStart() <= cursor && cursor <= nodeRange.getEnd()) {
                    return new SuggestionContext<>(prev, nodeRange.getStart());
                }
                prev = node.getNode();
            }
            if (prev == null) {
                throw new IllegalStateException("Can't find node before cursor");
            }
            return new SuggestionContext<>(prev, range.getStart());
        }
    }
    throw new IllegalStateException("Can't find node before cursor");
}
 
Example #28
Source File: ArgumentBuilder.java    From brigadier with MIT License 5 votes vote down vote up
public T forward(final CommandNode<S> target, final RedirectModifier<S> modifier, final boolean fork) {
    if (!arguments.getChildren().isEmpty()) {
        throw new IllegalStateException("Cannot forward a node with children");
    }
    this.target = target;
    this.modifier = modifier;
    this.forks = fork;
    return getThis();
}
 
Example #29
Source File: CommandContext.java    From brigadier with MIT License 5 votes vote down vote up
public CommandContext(final S source, final String input, final Map<String, ParsedArgument<S, ?>> arguments, final Command<S> command, final CommandNode<S> rootNode, final List<ParsedCommandNode<S>> nodes, final StringRange range, final CommandContext<S> child, final RedirectModifier<S> modifier, boolean forks) {
    this.source = source;
    this.input = input;
    this.arguments = arguments;
    this.command = command;
    this.rootNode = rootNode;
    this.nodes = nodes;
    this.range = range;
    this.child = child;
    this.modifier = modifier;
    this.forks = forks;
}
 
Example #30
Source File: ArgumentBuilder.java    From brigadier with MIT License 5 votes vote down vote up
public T then(final CommandNode<S> argument) {
    if (target != null) {
        throw new IllegalStateException("Cannot add children to a redirected node");
    }
    arguments.addChild(argument);
    return getThis();
}