Compare commits

..

2 commits

Author SHA1 Message Date
boq
e5de081185 Remove unused generic 2018-09-26 12:49:39 +02:00
boq
2bffe75ac9 Implement calculation of suggestions for any text position 2018-09-26 12:49:31 +02:00
32 changed files with 113 additions and 703 deletions

View file

@ -1,51 +0,0 @@
name: $(Rev:r)
trigger:
branches:
include:
- '*'
exclude:
- master
pr:
branches:
include:
- '*'
jobs:
- job: 'Build'
displayName: 'Build for testing'
pool: 'MC-Build-1ES-Azure-Pipeline-Linux'
container: adoptopenjdk/openjdk8:latest
workspace:
clean: all
steps:
- task: Gradle@2
displayName: Build and Test
inputs:
workingDirectory: ''
gradleWrapperFile: 'gradlew'
gradleOptions: '-Xmx3072m'
options: '-PbuildNumber=0'
javaHomeOption: 'JDKVersion'
jdkUserInputPath: '/usr/java/openjdk-8'
testResultsFiles: '**/TEST-*.xml'
tasks: 'build test publish'
# This is a workaround for ComponentGovernanceComponentDetection@0 not recognizing the generated `.pom` file(s)
- task: Bash@3
displayName: Copy pom for component governance
inputs:
targetType: 'inline'
script: |
pompath=`find build/repo -name *.pom`
cp "${pompath}" build/pom.xml
- task: ComponentGovernanceComponentDetection@0
inputs:
scanType: 'Register'
verbosity: 'Verbose'
alertWarningLevel: 'High'

View file

@ -1,87 +0,0 @@
name: $(Rev:r)
trigger:
branches:
include:
- master
pr: none
variables:
rConnection: 'mc-java-sc'
storageAccount: 'librariesminecraftnet'
storageAccountContainer: 'librariesminecraftnet'
keyVault: 'mc-java-vault'
jobs:
- job: 'Build'
displayName: 'Build for release'
pool: 'MC-Build-1ES-Azure-Pipeline-Linux'
container: adoptopenjdk/openjdk8:latest
workspace:
clean: all
steps:
- task: Gradle@2
displayName: Build and Test
inputs:
workingDirectory: ''
gradleWrapperFile: 'gradlew'
gradleOptions: '-Xmx3072m'
options: '-PbuildNumber=$(Build.BuildNumber)'
javaHomeOption: 'JDKVersion'
jdkUserInputPath: '/usr/java/openjdk-8'
testResultsFiles: '**/TEST-*.xml'
tasks: 'build test publish report'
# This is a workaround for ComponentGovernanceComponentDetection@0 not recognizing the generated `.pom` file(s)
- task: Bash@3
displayName: Copy pom for component governance
inputs:
targetType: 'inline'
script: |
pompath=`find build/repo -name *.pom`
cp "${pompath}" build/pom.xml
- task: ComponentGovernanceComponentDetection@0
inputs:
scanType: 'Register'
verbosity: 'Verbose'
alertWarningLevel: 'High'
- publish: 'build/repo/'
artifact: repo
- job: 'Publish'
displayName: 'Publish release'
dependsOn: Build
condition: eq(variables['Build.SourceBranch'], 'refs/heads/master')
pool: 'MC-Build-1ES-Azure-Pipeline-Linux'
workspace:
clean: all
steps:
- download: current
artifact: repo
- task: AzureKeyVault@1
displayName: 'Fetching secrets'
name: secrets
inputs:
azureSubscription: '$(rConnection)'
KeyVaultName: '$(keyVault)'
SecretsFilter: 'access-key-prod-librariesminecraftnet'
RunAsPreJob: false
- task: AzureCLI@2
displayName: Azure CLI
inputs:
azureSubscription: '$(rConnection)'
scriptType: 'bash'
scriptLocation: 'inlineScript'
inlineScript: |
az storage blob upload-batch -s '$(Pipeline.Workspace)/repo' -d $(storageAccountContainer) --account-name $(storageAccount) --account-key $(access-key-prod-librariesminecraftnet)

View file

@ -1,22 +0,0 @@
name: pr-check
on: [ pull_request ]
jobs:
build:
name: Build and test
runs-on: ubuntu-latest
container:
image: adoptopenjdk/openjdk8:latest
steps:
- uses: actions/checkout@v3
- name: Build with Gradle
uses: gradle/gradle-build-action@v2
with:
arguments: build test
- name: Publish Test Report
uses: mikepenz/action-junit-report@v3
if: always()
with:
report_paths: '**/build/test-results/test/TEST-*.xml'

18
LICENSE
View file

@ -2,20 +2,8 @@ MIT License
Copyright (c) Microsoft Corporation. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the Software), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View file

@ -1,5 +1,4 @@
# Brigadier [![Latest release](https://img.shields.io/github/release/Mojang/brigadier.svg)](https://github.com/Mojang/brigadier/releases/latest) [![License](https://img.shields.io/github/license/Mojang/brigadier.svg)](https://github.com/Mojang/brigadier/blob/master/LICENSE)
# Brigadier
Brigadier is a command parser & dispatcher, designed and developed for Minecraft: Java Edition and now freely available for use elsewhere under the MIT license.
# Installation
@ -38,7 +37,7 @@ And then use this library (change `(the latest version)` to the latest version!)
```
# Contributing
Contributions are welcome! :D
Contributions are suspended until we have a process in place to handle them.
Most contributions will require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to,
and actually do, grant us the rights to use your contribution. For details, visit https://cla.microsoft.com.
@ -50,20 +49,20 @@ contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additio
# Usage
At the heart of Brigadier, you need a `CommandDispatcher<S>`, where `<S>` is any custom object you choose to identify a "command source".
A command dispatcher holds a "command tree", which is a series of `CommandNode`s that represent the various possible syntax options that form a valid command.
A command dispatcher holds a "command tree", which are a series of `CommandNode` which represent the various possible syntax that form a valid command.
## Registering a new command
Before we can start parsing and dispatching commands, we need to build up our command tree. Every registration is an append operation,
so you can freely extend existing commands in a project without needing access to the source code that created them.
Command registration also encourages the use of a builder pattern to keep code cruft to a minimum.
Command registration also encourages use of a builder pattern to keep code cruft to a minimum.
A "command" is a fairly loose term, but typically it means an exit point of the command tree.
Every node can have an `executes` function attached to it, which signifies that if the input stops here then this function will be called with the context so far.
Consider the following example:
```java
CommandDispatcher<CommandSourceStack> dispatcher = new CommandDispatcher<>();
CommandDispatcher<CommandSourceStack> dispatcher = new CommandDispatcher();
dispatcher.register(
literal("foo")
@ -95,12 +94,12 @@ Argument types will be asked to parse input as much as they can, and then store
For example, an integer argument would parse "123" and store it as `123` (`int`), but throw an error if the input were `onetwothree`.
When a command is actually run, it can access these arguments in the context provided to the registered function.
When a command is actually ran, it can access these arguments in the context provided to the registered function.
## Parsing user input
So, we've registered some commands and now we're ready to take in user input. If you're in a rush, you can just call `dispatcher.execute("foo 123", source)` and call it a day.
The result of `execute` is an integer that was returned from an evaluated command. The meaning of this integer depends on the command, and will typically not be useful to programmers.
The result of `execute` is an integer returned by the command it evaluated. Its meaning varies depending on command, and typically will not be useful to programmers.
The `source` is an object of `<S>`, your own custom class to track users/players/etc. It will be provided to the command so that it has some context on what's happening.
@ -126,10 +125,9 @@ It also contains a map of parse exceptions for each command node it encountered.
the reason why is inside this exception map.
## Displaying usage info
There are two forms of "usage strings" provided by this library, both require a target node.
There's two forms of "usage strings" provided by this library, both require a target node.
`getAllUsage(node, source, restricted)` will return a list of all possible commands (executable end-points) under the target node and their human readable path. If `restricted`, it will ignore commands that `source` does not have access to. This will look like [`foo`, `foo <bar>`].
`getAllUsage(node, source, restricted)` will return a list of all possible commands (executable end-points) under the target node and their human readable path. If `restricted`, it will ignore commands that `source` does not have access to. This will look like [`foo`, `foo <bar>`]
`getSmartUsage(node, source)` will return a map of the child nodes to their "smart usage" human readable path. This tries to squash future-nodes together and show optional & typed information, and can look like `foo (<bar>)`.
`getSmartUsage(node, source)` will return a map of the child nodes to their "smart usage" human readable path. This tries to squash future-nodes together and show optional & typed information, and can look like `foo (<bar>)`
[![GitHub forks](https://img.shields.io/github/forks/Mojang/brigadier.svg?style=social&label=Fork)](https://github.com/Mojang/brigadier/fork) [![GitHub stars](https://img.shields.io/github/stars/Mojang/brigadier.svg?style=social&label=Stars)](https://github.com/Mojang/brigadier/stargazers)

View file

@ -1,4 +1,6 @@
import groovy.io.FileType
import com.amazonaws.auth.STSAssumeRoleSessionCredentialsProvider
import com.amazonaws.services.s3.AmazonS3Client
apply plugin: 'java-library'
apply plugin: 'maven-publish'
@ -6,6 +8,10 @@ apply plugin: 'maven-publish'
group = 'com.mojang'
version = project.hasProperty('buildNumber') ? "${project.majorMinor}.${project.buildNumber}" : "${project.majorMinor}.0-SNAPSHOT"
task wrapper(type: Wrapper) {
gradleVersion = '4.0'
}
buildscript {
repositories {
mavenCentral()
@ -13,6 +19,10 @@ buildscript {
url "https://libraries.minecraft.net"
}
}
dependencies {
classpath 'com.amazonaws:aws-java-sdk:1.11.33'
}
}
repositories {
@ -23,13 +33,13 @@ repositories {
}
dependencies {
testCompile 'com.google.guava:guava:26.0-jre'
testCompile 'junit:junit-dep:4.11'
testCompile 'org.hamcrest:hamcrest-library:1.3'
testCompile 'org.mockito:mockito-core:1.10.19'
testCompile 'com.google.guava:guava-testlib:26.0-jre'
testCompile 'org.openjdk.jmh:jmh-core:1.21'
annotationProcessor 'org.openjdk.jmh:jmh-generator-annprocess:1.21'
api 'com.google.guava:guava:21.0'
testCompile 'junit:junit-dep:4.10'
testCompile 'org.hamcrest:hamcrest-library:1.2.1'
testCompile 'org.mockito:mockito-core:1.8.5'
testCompile 'com.google.guava:guava-testlib:21.0'
testCompile 'org.openjdk.jmh:jmh-core:1.19'
testCompile 'org.openjdk.jmh:jmh-generator-annprocess:1.19'
}
task sourcesJar(type: Jar) {
@ -80,12 +90,18 @@ publishing {
task report {
doLast {
println "##vso[build.updatebuildnumber]${project.version}"
println "##teamcity[buildNumber '${project.version}']"
}
}
def publishDir = file("$buildDir/repo")
def uploadFile(s3, bucket, path, filename) {
println "Uploading $filename to $bucket as $path"
s3.putObject(bucket, path, filename)
}
clean.doLast {
delete publishDir
}
@ -102,13 +118,14 @@ if (version.endsWith("SNAPSHOT")) {
}
publish.doLast {
def AWSRoleARN = (System.getenv("AWS_ROLE_ARN") != null && System.getenv("AWS_ROLE_ARN") != "" ? System.getenv("AWS_ROLE_ARN") : null)
if (AWSRoleARN == null) throw new GradleException("AWS Role has not been configured, use the `AWS_ROLE_ARN` environment variable")
def auth = new STSAssumeRoleSessionCredentialsProvider.Builder(AWSRoleARN, "JavaBrigadierPublish").build()
def s3 = new AmazonS3Client(auth)
publishDir.eachFileRecurse {
if (!it.isFile()) {
return
}
// Remove junk files
if (it.name.contains(".xml") || it.name.contains(".md5")) {
it.delete()
if (!it.name.contains(".xml") && !it.name.contains(".md5") && it.isFile()) {
def relPath = publishDir.toPath().relativize(it.toPath()).toFile().toString().replaceAll('\\\\', '/')
uploadFile(s3, "minecraft-libraries", relPath, it)
}
}
}

View file

@ -1 +1 @@
majorMinor: 1.1
majorMinor: 1.0

Binary file not shown.

View file

@ -1,6 +1,6 @@
#Sat Oct 06 16:17:40 EEST 2018
#Wed Jun 21 14:07:34 CEST 2017
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.10.2-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-4.0-bin.zip

0
gradlew vendored Executable file → Normal file
View file

View file

@ -1,2 +1 @@
rootProject.name = 'brigadier'
enableFeaturePreview('STABLE_PUBLISHING')
rootProject.name = 'brigadier'

View file

@ -3,6 +3,9 @@
package com.mojang.brigadier;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.context.CommandContextBuilder;
@ -18,9 +21,7 @@ import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
@ -231,6 +232,7 @@ public class CommandDispatcher<S> {
if (child != null) {
forked |= context.isForked();
if (child.hasNodes()) {
foundCommand = true;
final RedirectModifier<S> modifier = context.getRedirectModifier();
if (modifier == null) {
if (next == null) {
@ -247,8 +249,6 @@ public class CommandDispatcher<S> {
for (final S source : results) {
next.add(child.copyFor(source));
}
} else {
foundCommand = true;
}
} catch (final CommandSyntaxException ex) {
consumer.onCommandComplete(context, false, 0);
@ -450,7 +450,7 @@ public class CommandDispatcher<S> {
* @return array of full usage strings under the target node
*/
public String[] getAllUsage(final CommandNode<S> node, final S source, final boolean restricted) {
final ArrayList<String> result = new ArrayList<>();
final ArrayList<String> result = Lists.newArrayList();
getAllUsage(node, source, result, "", restricted);
return result.toArray(new String[result.size()]);
}
@ -496,7 +496,7 @@ public class CommandDispatcher<S> {
* @return array of full usage strings under the target node
*/
public Map<CommandNode<S>, String> getSmartUsage(final CommandNode<S> node, final S source) {
final Map<CommandNode<S>, String> result = new LinkedHashMap<>();
final Map<CommandNode<S>, String> result = Maps.newLinkedHashMap();
final boolean optional = node.getCommand() != null;
for (final CommandNode<S> child : node.getChildren()) {
@ -530,7 +530,7 @@ public class CommandDispatcher<S> {
return self + ARGUMENT_SEPARATOR + usage;
}
} else if (children.size() > 1) {
final Set<String> childUsage = new LinkedHashSet<>();
final Set<String> childUsage = Sets.newLinkedHashSet();
for (final CommandNode<S> child : children) {
final String usage = getSmartUsage(child, source, childOptional, true);
if (usage != null) {
@ -590,13 +590,12 @@ public class CommandDispatcher<S> {
final String fullInput = parse.getReader().getString();
final String truncatedInput = fullInput.substring(0, cursor);
final String truncatedInputLowerCase = truncatedInput.toLowerCase(Locale.ROOT);
@SuppressWarnings("unchecked") final CompletableFuture<Suggestions>[] futures = new CompletableFuture[parent.getChildren().size()];
int i = 0;
for (final CommandNode<S> node : parent.getChildren()) {
CompletableFuture<Suggestions> future = Suggestions.empty();
try {
future = node.listSuggestions(context.build(truncatedInput), new SuggestionsBuilder(truncatedInput, truncatedInputLowerCase, start));
future = node.listSuggestions(context.build(truncatedInput), new SuggestionsBuilder(truncatedInput, start));
} catch (final CommandSyntaxException ignored) {
}
futures[i++] = future;
@ -604,7 +603,7 @@ public class CommandDispatcher<S> {
final CompletableFuture<Suggestions> result = new CompletableFuture<>();
CompletableFuture.allOf(futures).thenRun(() -> {
final List<Suggestions> suggestions = new ArrayList<>();
final List<Suggestions> suggestions = Lists.newArrayList();
for (final CompletableFuture<Suggestions> future : futures) {
suggestions.add(future.join());
}

View file

@ -6,6 +6,8 @@ package com.mojang.brigadier;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import java.util.Collection;
@FunctionalInterface
public interface SingleRedirectModifier<S> {
S apply(CommandContext<S> context) throws CommandSyntaxException;

View file

@ -7,8 +7,7 @@ import com.mojang.brigadier.exceptions.CommandSyntaxException;
public class StringReader implements ImmutableStringReader {
private static final char SYNTAX_ESCAPE = '\\';
private static final char SYNTAX_DOUBLE_QUOTE = '"';
private static final char SYNTAX_SINGLE_QUOTE = '\'';
private static final char SYNTAX_QUOTE = '"';
private final String string;
private int cursor;
@ -88,10 +87,6 @@ public class StringReader implements ImmutableStringReader {
return c >= '0' && c <= '9' || c == '.' || c == '-';
}
public static boolean isQuotedStringStart(char c) {
return c == SYNTAX_DOUBLE_QUOTE || c == SYNTAX_SINGLE_QUOTE;
}
public void skipWhitespace() {
while (canRead() && Character.isWhitespace(peek())) {
skip();
@ -115,23 +110,6 @@ public class StringReader implements ImmutableStringReader {
}
}
public long readLong() throws CommandSyntaxException {
final int start = cursor;
while (canRead() && isAllowedNumber(peek())) {
skip();
}
final String number = string.substring(start, cursor);
if (number.isEmpty()) {
throw CommandSyntaxException.BUILT_IN_EXCEPTIONS.readerExpectedLong().createWithContext(this);
}
try {
return Long.parseLong(number);
} catch (final NumberFormatException ex) {
cursor = start;
throw CommandSyntaxException.BUILT_IN_EXCEPTIONS.readerInvalidLong().createWithContext(this, number);
}
}
public double readDouble() throws CommandSyntaxException {
final int start = cursor;
while (canRead() && isAllowedNumber(peek())) {
@ -185,22 +163,16 @@ public class StringReader implements ImmutableStringReader {
public String readQuotedString() throws CommandSyntaxException {
if (!canRead()) {
return "";
}
final char next = peek();
if (!isQuotedStringStart(next)) {
} else if (peek() != SYNTAX_QUOTE) {
throw CommandSyntaxException.BUILT_IN_EXCEPTIONS.readerExpectedStartOfQuote().createWithContext(this);
}
skip();
return readStringUntil(next);
}
public String readStringUntil(char terminator) throws CommandSyntaxException {
final StringBuilder result = new StringBuilder();
boolean escaped = false;
while (canRead()) {
final char c = read();
if (escaped) {
if (c == terminator || c == SYNTAX_ESCAPE) {
if (c == SYNTAX_QUOTE || c == SYNTAX_ESCAPE) {
result.append(c);
escaped = false;
} else {
@ -209,7 +181,7 @@ public class StringReader implements ImmutableStringReader {
}
} else if (c == SYNTAX_ESCAPE) {
escaped = true;
} else if (c == terminator) {
} else if (c == SYNTAX_QUOTE) {
return result.toString();
} else {
result.append(c);
@ -220,15 +192,11 @@ public class StringReader implements ImmutableStringReader {
}
public String readString() throws CommandSyntaxException {
if (!canRead()) {
return "";
if (canRead() && peek() == SYNTAX_QUOTE) {
return readQuotedString();
} else {
return readUnquotedString();
}
final char next = peek();
if (isQuotedStringStart(next)) {
skip();
return readStringUntil(next);
}
return readUnquotedString();
}
public boolean readBoolean() throws CommandSyntaxException {

View file

@ -34,10 +34,10 @@ public class BoolArgumentType implements ArgumentType<Boolean> {
@Override
public <S> CompletableFuture<Suggestions> listSuggestions(final CommandContext<S> context, final SuggestionsBuilder builder) {
if ("true".startsWith(builder.getRemainingLowerCase())) {
if ("true".startsWith(builder.getRemaining().toLowerCase())) {
builder.suggest("true");
}
if ("false".startsWith(builder.getRemainingLowerCase())) {
if ("false".startsWith(builder.getRemaining().toLowerCase())) {
builder.suggest("false");
}
return builder.buildFuture();

View file

@ -1,92 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
package com.mojang.brigadier.arguments;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import java.util.Arrays;
import java.util.Collection;
public class LongArgumentType implements ArgumentType<Long> {
private static final Collection<String> EXAMPLES = Arrays.asList("0", "123", "-123");
private final long minimum;
private final long maximum;
private LongArgumentType(final long minimum, final long maximum) {
this.minimum = minimum;
this.maximum = maximum;
}
public static LongArgumentType longArg() {
return longArg(Long.MIN_VALUE);
}
public static LongArgumentType longArg(final long min) {
return longArg(min, Long.MAX_VALUE);
}
public static LongArgumentType longArg(final long min, final long max) {
return new LongArgumentType(min, max);
}
public static long getLong(final CommandContext<?> context, final String name) {
return context.getArgument(name, long.class);
}
public long getMinimum() {
return minimum;
}
public long getMaximum() {
return maximum;
}
@Override
public Long parse(final StringReader reader) throws CommandSyntaxException {
final int start = reader.getCursor();
final long result = reader.readLong();
if (result < minimum) {
reader.setCursor(start);
throw CommandSyntaxException.BUILT_IN_EXCEPTIONS.longTooLow().createWithContext(reader, result, minimum);
}
if (result > maximum) {
reader.setCursor(start);
throw CommandSyntaxException.BUILT_IN_EXCEPTIONS.longTooHigh().createWithContext(reader, result, maximum);
}
return result;
}
@Override
public boolean equals(final Object o) {
if (this == o) return true;
if (!(o instanceof LongArgumentType)) return false;
final LongArgumentType that = (LongArgumentType) o;
return maximum == that.maximum && minimum == that.minimum;
}
@Override
public int hashCode() {
return 31 * Long.hashCode(minimum) + Long.hashCode(maximum);
}
@Override
public String toString() {
if (minimum == Long.MIN_VALUE && maximum == Long.MAX_VALUE) {
return "longArg()";
} else if (maximum == Long.MAX_VALUE) {
return "longArg(" + minimum + ")";
} else {
return "longArg(" + minimum + ", " + maximum + ")";
}
}
@Override
public Collection<String> getExamples() {
return EXAMPLES;
}
}

View file

@ -4,7 +4,6 @@
package com.mojang.brigadier.builder;
import com.mojang.brigadier.Command;
import com.mojang.brigadier.Message;
import com.mojang.brigadier.RedirectModifier;
import com.mojang.brigadier.SingleRedirectModifier;
import com.mojang.brigadier.tree.CommandNode;
@ -21,7 +20,6 @@ public abstract class ArgumentBuilder<S, T extends ArgumentBuilder<S, T>> {
private CommandNode<S> target;
private RedirectModifier<S> modifier = null;
private boolean forks;
private Message description;
protected abstract T getThis();
@ -54,15 +52,6 @@ public abstract class ArgumentBuilder<S, T extends ArgumentBuilder<S, T>> {
return command;
}
public T describe(final Message description) {
this.description = description;
return getThis();
}
public Message getDescription() {
return description;
}
public T requires(final Predicate<S> requirement) {
this.requirement = requirement;
return getThis();

View file

@ -28,7 +28,7 @@ public class LiteralArgumentBuilder<S> extends ArgumentBuilder<S, LiteralArgumen
@Override
public LiteralCommandNode<S> build() {
final LiteralCommandNode<S> result = new LiteralCommandNode<>(getLiteral(), getCommand(), getRequirement(), getRedirect(), getRedirectModifier(), isFork(), getDescription());
final LiteralCommandNode<S> result = new LiteralCommandNode<>(getLiteral(), getCommand(), getRequirement(), getRedirect(), getRedirectModifier(), isFork());
for (final CommandNode<S> argument : getArguments()) {
result.addChild(argument);

View file

@ -45,7 +45,7 @@ public class RequiredArgumentBuilder<S, T> extends ArgumentBuilder<S, RequiredAr
}
public ArgumentCommandNode<S, T> build() {
final ArgumentCommandNode<S, T> result = new ArgumentCommandNode<>(getName(), getType(), getCommand(), getRequirement(), getRedirect(), getRedirectModifier(), isFork(), getSuggestionsProvider(), getDescription());
final ArgumentCommandNode<S, T> result = new ArgumentCommandNode<>(getName(), getType(), getCommand(), getRequirement(), getRedirect(), getRedirectModifier(), isFork(), getSuggestionsProvider());
for (final CommandNode<S> argument : getArguments()) {
result.addChild(argument);

View file

@ -3,29 +3,16 @@
package com.mojang.brigadier.context;
import com.google.common.collect.Iterables;
import com.google.common.primitives.Primitives;
import com.mojang.brigadier.Command;
import com.mojang.brigadier.RedirectModifier;
import com.mojang.brigadier.tree.CommandNode;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class CommandContext<S> {
private static final Map<Class<?>, Class<?>> PRIMITIVE_TO_WRAPPER = new HashMap<>();
static {
PRIMITIVE_TO_WRAPPER.put(boolean.class, Boolean.class);
PRIMITIVE_TO_WRAPPER.put(byte.class, Byte.class);
PRIMITIVE_TO_WRAPPER.put(short.class, Short.class);
PRIMITIVE_TO_WRAPPER.put(char.class, Character.class);
PRIMITIVE_TO_WRAPPER.put(int.class, Integer.class);
PRIMITIVE_TO_WRAPPER.put(long.class, Long.class);
PRIMITIVE_TO_WRAPPER.put(float.class, Float.class);
PRIMITIVE_TO_WRAPPER.put(double.class, Double.class);
}
private final S source;
private final String input;
private final Command<S> command;
@ -86,7 +73,7 @@ public class CommandContext<S> {
}
final Object result = argument.getResult();
if (PRIMITIVE_TO_WRAPPER.getOrDefault(clazz, clazz).isAssignableFrom(result.getClass())) {
if (Primitives.wrap(clazz).isAssignableFrom(result.getClass())) {
return (V) result;
} else {
throw new IllegalArgumentException("Argument '" + name + "' is defined as " + result.getClass().getSimpleName() + ", not " + clazz);
@ -102,7 +89,7 @@ public class CommandContext<S> {
if (!arguments.equals(that.arguments)) return false;
if (!rootNode.equals(that.rootNode)) return false;
if (nodes.size() != that.nodes.size() || !nodes.equals(that.nodes)) return false;
if (!Iterables.elementsEqual(nodes, that.nodes)) return false;
if (command != null ? !command.equals(that.command) : that.command != null) return false;
if (!source.equals(that.source)) return false;
if (child != null ? !child.equals(that.child) : that.child != null) return false;

View file

@ -3,20 +3,21 @@
package com.mojang.brigadier.context;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.mojang.brigadier.Command;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.RedirectModifier;
import com.mojang.brigadier.tree.CommandNode;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class CommandContextBuilder<S> {
private final Map<String, ParsedArgument<S, ?>> arguments = new LinkedHashMap<>();
private final Map<String, ParsedArgument<S, ?>> arguments = Maps.newLinkedHashMap();
private final CommandNode<S> rootNode;
private final List<ParsedCommandNode<S>> nodes = new ArrayList<>();
private final List<ParsedCommandNode<S>> nodes = Lists.newArrayList();
private final CommandDispatcher<S> dispatcher;
private S source;
private Command<S> command;
@ -121,7 +122,7 @@ public class CommandContextBuilder<S> {
if (child != null) {
return child.findSuggestionContext(cursor);
} else if (!nodes.isEmpty()) {
final ParsedCommandNode<S> last = nodes.get(nodes.size() - 1);
final ParsedCommandNode<S> last = Iterables.getLast(nodes);
return new SuggestionContext<>(last.getNode(), last.getRange().getEnd() + 1);
} else {
return new SuggestionContext<>(rootNode, range.getStart());

View file

@ -16,10 +16,6 @@ public interface BuiltInExceptionProvider {
Dynamic2CommandExceptionType integerTooHigh();
Dynamic2CommandExceptionType longTooLow();
Dynamic2CommandExceptionType longTooHigh();
DynamicCommandExceptionType literalIncorrect();
SimpleCommandExceptionType readerExpectedStartOfQuote();
@ -34,10 +30,6 @@ public interface BuiltInExceptionProvider {
SimpleCommandExceptionType readerExpectedInt();
DynamicCommandExceptionType readerInvalidLong();
SimpleCommandExceptionType readerExpectedLong();
DynamicCommandExceptionType readerInvalidDouble();
SimpleCommandExceptionType readerExpectedDouble();

View file

@ -15,9 +15,6 @@ public class BuiltInExceptions implements BuiltInExceptionProvider {
private static final Dynamic2CommandExceptionType INTEGER_TOO_SMALL = new Dynamic2CommandExceptionType((found, min) -> new LiteralMessage("Integer must not be less than " + min + ", found " + found));
private static final Dynamic2CommandExceptionType INTEGER_TOO_BIG = new Dynamic2CommandExceptionType((found, max) -> new LiteralMessage("Integer must not be more than " + max + ", found " + found));
private static final Dynamic2CommandExceptionType LONG_TOO_SMALL = new Dynamic2CommandExceptionType((found, min) -> new LiteralMessage("Long must not be less than " + min + ", found " + found));
private static final Dynamic2CommandExceptionType LONG_TOO_BIG = new Dynamic2CommandExceptionType((found, max) -> new LiteralMessage("Long must not be more than " + max + ", found " + found));
private static final DynamicCommandExceptionType LITERAL_INCORRECT = new DynamicCommandExceptionType(expected -> new LiteralMessage("Expected literal " + expected));
private static final SimpleCommandExceptionType READER_EXPECTED_START_OF_QUOTE = new SimpleCommandExceptionType(new LiteralMessage("Expected quote to start a string"));
@ -26,8 +23,6 @@ public class BuiltInExceptions implements BuiltInExceptionProvider {
private static final DynamicCommandExceptionType READER_INVALID_BOOL = new DynamicCommandExceptionType(value -> new LiteralMessage("Invalid bool, expected true or false but found '" + value + "'"));
private static final DynamicCommandExceptionType READER_INVALID_INT = new DynamicCommandExceptionType(value -> new LiteralMessage("Invalid integer '" + value + "'"));
private static final SimpleCommandExceptionType READER_EXPECTED_INT = new SimpleCommandExceptionType(new LiteralMessage("Expected integer"));
private static final DynamicCommandExceptionType READER_INVALID_LONG = new DynamicCommandExceptionType(value -> new LiteralMessage("Invalid long '" + value + "'"));
private static final SimpleCommandExceptionType READER_EXPECTED_LONG = new SimpleCommandExceptionType((new LiteralMessage("Expected long")));
private static final DynamicCommandExceptionType READER_INVALID_DOUBLE = new DynamicCommandExceptionType(value -> new LiteralMessage("Invalid double '" + value + "'"));
private static final SimpleCommandExceptionType READER_EXPECTED_DOUBLE = new SimpleCommandExceptionType(new LiteralMessage("Expected double"));
private static final DynamicCommandExceptionType READER_INVALID_FLOAT = new DynamicCommandExceptionType(value -> new LiteralMessage("Invalid float '" + value + "'"));
@ -70,16 +65,6 @@ public class BuiltInExceptions implements BuiltInExceptionProvider {
return INTEGER_TOO_BIG;
}
@Override
public Dynamic2CommandExceptionType longTooLow() {
return LONG_TOO_SMALL;
}
@Override
public Dynamic2CommandExceptionType longTooHigh() {
return LONG_TOO_BIG;
}
@Override
public DynamicCommandExceptionType literalIncorrect() {
return LITERAL_INCORRECT;
@ -115,16 +100,6 @@ public class BuiltInExceptions implements BuiltInExceptionProvider {
return READER_EXPECTED_INT;
}
@Override
public DynamicCommandExceptionType readerInvalidLong() {
return READER_INVALID_LONG;
}
@Override
public SimpleCommandExceptionType readerExpectedLong() {
return READER_EXPECTED_LONG;
}
@Override
public DynamicCommandExceptionType readerInvalidDouble() {
return READER_INVALID_DOUBLE;

View file

@ -3,9 +3,10 @@
package com.mojang.brigadier.suggestion;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.mojang.brigadier.context.StringRange;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
@ -14,7 +15,7 @@ import java.util.Set;
import java.util.concurrent.CompletableFuture;
public class Suggestions {
private static final Suggestions EMPTY = new Suggestions(StringRange.at(0), new ArrayList<>());
private static final Suggestions EMPTY = new Suggestions(StringRange.at(0), Lists.newArrayList());
private final StringRange range;
private final List<Suggestion> suggestions;
@ -91,11 +92,11 @@ public class Suggestions {
end = Math.max(suggestion.getRange().getEnd(), end);
}
final StringRange range = new StringRange(start, end);
final Set<Suggestion> texts = new HashSet<>();
final Set<Suggestion> texts = Sets.newHashSet();
for (final Suggestion suggestion : suggestions) {
texts.add(suggestion.expand(command, range));
}
final List<Suggestion> sorted = new ArrayList<>(texts);
final List<Suggestion> sorted = Lists.newArrayList(texts);
sorted.sort((a, b) -> a.compareToIgnoreCase(b));
return new Suggestions(range, sorted);
}

View file

@ -8,27 +8,18 @@ import com.mojang.brigadier.context.StringRange;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.CompletableFuture;
public class SuggestionsBuilder {
private final String input;
private final String inputLowerCase;
private final int start;
private final String remaining;
private final String remainingLowerCase;
private final List<Suggestion> result = new ArrayList<>();
public SuggestionsBuilder(final String input, final String inputLowerCase, final int start) {
public SuggestionsBuilder(final String input, final int start) {
this.input = input;
this.inputLowerCase = inputLowerCase;
this.start = start;
this.remaining = input.substring(start);
this.remainingLowerCase = inputLowerCase.substring(start);
}
public SuggestionsBuilder(final String input, final int start) {
this(input, input.toLowerCase(Locale.ROOT), start);
}
public String getInput() {
@ -43,10 +34,6 @@ public class SuggestionsBuilder {
return remaining;
}
public String getRemainingLowerCase() {
return remainingLowerCase;
}
public Suggestions build() {
return Suggestions.create(input, result);
}
@ -87,10 +74,10 @@ public class SuggestionsBuilder {
}
public SuggestionsBuilder createOffset(final int start) {
return new SuggestionsBuilder(input, inputLowerCase, start);
return new SuggestionsBuilder(input, start);
}
public SuggestionsBuilder restart() {
return createOffset(start);
return new SuggestionsBuilder(input, start);
}
}

View file

@ -4,7 +4,6 @@
package com.mojang.brigadier.tree;
import com.mojang.brigadier.Command;
import com.mojang.brigadier.Message;
import com.mojang.brigadier.RedirectModifier;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.arguments.ArgumentType;
@ -30,11 +29,7 @@ public class ArgumentCommandNode<S, T> extends CommandNode<S> {
private final SuggestionProvider<S> customSuggestions;
public ArgumentCommandNode(final String name, final ArgumentType<T> type, final Command<S> command, final Predicate<S> requirement, final CommandNode<S> redirect, final RedirectModifier<S> modifier, final boolean forks, final SuggestionProvider<S> customSuggestions) {
this(name, type, command, requirement, redirect, modifier, forks, customSuggestions, null);
}
public ArgumentCommandNode(final String name, final ArgumentType<T> type, final Command<S> command, final Predicate<S> requirement, final CommandNode<S> redirect, final RedirectModifier<S> modifier, final boolean forks, final SuggestionProvider<S> customSuggestions, final Message description) {
super(command, requirement, redirect, modifier, forks, description);
super(command, requirement, redirect, modifier, forks);
this.name = name;
this.type = type;
this.customSuggestions = customSuggestions;

View file

@ -3,7 +3,13 @@
package com.mojang.brigadier.tree;
import com.mojang.brigadier.*;
import com.google.common.collect.ComparisonChain;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.mojang.brigadier.AmbiguityConsumer;
import com.mojang.brigadier.Command;
import com.mojang.brigadier.RedirectModifier;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.builder.ArgumentBuilder;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.context.CommandContextBuilder;
@ -13,45 +19,35 @@ import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public abstract class CommandNode<S> implements Comparable<CommandNode<S>> {
private final Map<String, CommandNode<S>> children = new LinkedHashMap<>();
private final Map<String, LiteralCommandNode<S>> literals = new LinkedHashMap<>();
private final Map<String, ArgumentCommandNode<S, ?>> arguments = new LinkedHashMap<>();
private Map<String, CommandNode<S>> children = Maps.newLinkedHashMap();
private Map<String, LiteralCommandNode<S>> literals = Maps.newLinkedHashMap();
private Map<String, ArgumentCommandNode<S, ?>> arguments = Maps.newLinkedHashMap();
private final Predicate<S> requirement;
private final CommandNode<S> redirect;
private final RedirectModifier<S> modifier;
private final boolean forks;
private Command<S> command;
private Message description;
protected CommandNode(final Command<S> command, final Predicate<S> requirement, final CommandNode<S> redirect, final RedirectModifier<S> modifier, final boolean forks) {
this(command, requirement, redirect, modifier, forks, null);
}
protected CommandNode(final Command<S> command, final Predicate<S> requirement, final CommandNode<S> redirect, final RedirectModifier<S> modifier, final boolean forks, final Message description) {
this.command = command;
this.requirement = requirement;
this.redirect = redirect;
this.modifier = modifier;
this.forks = forks;
this.description = description;
}
public Command<S> getCommand() {
return command;
}
public Message getDescription() {
return description;
}
public Collection<CommandNode<S>> getChildren() {
return children.values();
}
@ -94,10 +90,12 @@ public abstract class CommandNode<S> implements Comparable<CommandNode<S>> {
arguments.put(node.getName(), (ArgumentCommandNode<S, ?>) node);
}
}
children = children.entrySet().stream().sorted(Map.Entry.comparingByValue()).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
}
public void findAmbiguities(final AmbiguityConsumer<S> consumer) {
Set<String> matches = new HashSet<>();
Set<String> matches = Sets.newHashSet();
for (final CommandNode<S> child : children.values()) {
for (final CommandNode<S> sibling : children.values()) {
@ -113,7 +111,7 @@ public abstract class CommandNode<S> implements Comparable<CommandNode<S>> {
if (matches.size() > 0) {
consumer.ambiguous(this, child, sibling, matches);
matches = new HashSet<>();
matches = Sets.newHashSet();
}
}
@ -178,11 +176,11 @@ public abstract class CommandNode<S> implements Comparable<CommandNode<S>> {
@Override
public int compareTo(final CommandNode<S> o) {
if (this instanceof LiteralCommandNode == o instanceof LiteralCommandNode) {
return getSortedKey().compareTo(o.getSortedKey());
}
return (o instanceof LiteralCommandNode) ? 1 : -1;
return ComparisonChain
.start()
.compareTrueFirst(this instanceof LiteralCommandNode, o instanceof LiteralCommandNode)
.compare(getSortedKey(), o.getSortedKey())
.result();
}
public boolean isFork() {

View file

@ -4,7 +4,6 @@
package com.mojang.brigadier.tree;
import com.mojang.brigadier.Command;
import com.mojang.brigadier.Message;
import com.mojang.brigadier.RedirectModifier;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
@ -17,22 +16,15 @@ import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import java.util.Collection;
import java.util.Collections;
import java.util.Locale;
import java.util.concurrent.CompletableFuture;
import java.util.function.Predicate;
public class LiteralCommandNode<S> extends CommandNode<S> {
private final String literal;
private final String literalLowerCase;
public LiteralCommandNode(final String literal, final Command<S> command, final Predicate<S> requirement, final CommandNode<S> redirect, final RedirectModifier<S> modifier, final boolean forks) {
this(literal, command, requirement, redirect, modifier, forks, null);
}
public LiteralCommandNode(final String literal, final Command<S> command, final Predicate<S> requirement, final CommandNode<S> redirect, final RedirectModifier<S> modifier, final boolean forks, final Message description) {
super(command, requirement, redirect, modifier, forks, description);
super(command, requirement, redirect, modifier, forks);
this.literal = literal;
this.literalLowerCase = literal.toLowerCase(Locale.ROOT);
}
public String getLiteral() {
@ -74,7 +66,7 @@ public class LiteralCommandNode<S> extends CommandNode<S> {
@Override
public CompletableFuture<Suggestions> listSuggestions(final CommandContext<S> context, final SuggestionsBuilder builder) {
if (literalLowerCase.startsWith(builder.getRemainingLowerCase())) {
if (literal.toLowerCase().startsWith(builder.getRemaining().toLowerCase())) {
return builder.suggest(literal).buildFuture();
} else {
return Suggestions.empty();

View file

@ -17,7 +17,7 @@ import java.util.concurrent.CompletableFuture;
public class RootCommandNode<S> extends CommandNode<S> {
public RootCommandNode() {
super(null, c -> true, null, s -> Collections.singleton(s.getSource()), false, null);
super(null, c -> true, null, s -> Collections.singleton(s.getSource()), false);
}
@Override

View file

@ -4,7 +4,6 @@
package com.mojang.brigadier;
import com.google.common.collect.Lists;
import com.mojang.brigadier.arguments.IntegerArgumentType;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.context.CommandContextBuilder;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
@ -15,9 +14,6 @@ import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import java.util.Collections;
import java.util.concurrent.atomic.AtomicBoolean;
import static com.mojang.brigadier.arguments.IntegerArgumentType.integer;
import static com.mojang.brigadier.builder.LiteralArgumentBuilder.literal;
import static com.mojang.brigadier.builder.RequiredArgumentBuilder.argument;
@ -330,37 +326,6 @@ public class CommandDispatcherTest {
verify(command).run(argThat(hasProperty("source", is(source2))));
}
@Test
public void testIncompleteRedirectShouldThrow() {
final LiteralCommandNode<Object> foo = subject.register(literal("foo")
.then(literal("bar")
.then(argument("value", integer()).executes(context -> IntegerArgumentType.getInteger(context, "value"))))
.then(literal("awa").executes(context -> 2)));
final LiteralCommandNode<Object> baz = subject.register(literal("baz").redirect(foo));
try {
int result = subject.execute("baz bar", source);
fail("Should have thrown an exception");
} catch (CommandSyntaxException e) {
assertThat(e.getType(), is(CommandSyntaxException.BUILT_IN_EXCEPTIONS.dispatcherUnknownCommand()));
}
}
@Test
public void testRedirectModifierEmptyResult() {
final LiteralCommandNode<Object> foo = subject.register(literal("foo")
.then(literal("bar")
.then(argument("value", integer()).executes(context -> IntegerArgumentType.getInteger(context, "value"))))
.then(literal("awa").executes(context -> 2)));
final RedirectModifier<Object> emptyModifier = context -> Collections.emptyList();
final LiteralCommandNode<Object> baz = subject.register(literal("baz").fork(foo, emptyModifier));
try {
int result = subject.execute("baz bar 100", source);
assertThat(result, is(0)); // No commands executed, so result is 0
} catch (CommandSyntaxException e) {
fail("Should not throw an exception");
}
}
@Test
public void testExecuteOrphanedSubcommand() throws Exception {
subject.register(literal("foo").then(

View file

@ -156,30 +156,6 @@ public class StringReaderTest {
assertThat(reader.getRemaining(), equalTo(""));
}
@Test
public void readSingleQuotedString() throws Exception {
final StringReader reader = new StringReader("'hello world'");
assertThat(reader.readQuotedString(), equalTo("hello world"));
assertThat(reader.getRead(), equalTo("'hello world'"));
assertThat(reader.getRemaining(), equalTo(""));
}
@Test
public void readMixedQuotedString_doubleInsideSingle() throws Exception {
final StringReader reader = new StringReader("'hello \"world\"'");
assertThat(reader.readQuotedString(), equalTo("hello \"world\""));
assertThat(reader.getRead(), equalTo("'hello \"world\"'"));
assertThat(reader.getRemaining(), equalTo(""));
}
@Test
public void readMixedQuotedString_singleInsideDouble() throws Exception {
final StringReader reader = new StringReader("\"hello 'world'\"");
assertThat(reader.readQuotedString(), equalTo("hello 'world'"));
assertThat(reader.getRead(), equalTo("\"hello 'world'\""));
assertThat(reader.getRemaining(), equalTo(""));
}
@Test
public void readQuotedString_empty() throws Exception {
final StringReader reader = new StringReader("");
@ -266,40 +242,6 @@ public class StringReaderTest {
}
}
@Test
public void readQuotedString_invalidQuoteEscape() throws Exception {
try {
new StringReader("'hello\\\"\'world").readQuotedString();
} catch (final CommandSyntaxException ex) {
assertThat(ex.getType(), is(CommandSyntaxException.BUILT_IN_EXCEPTIONS.readerInvalidEscape()));
assertThat(ex.getCursor(), is(7));
}
}
@Test
public void readString_noQuotes() throws Exception {
final StringReader reader = new StringReader("hello world");
assertThat(reader.readString(), equalTo("hello"));
assertThat(reader.getRead(), equalTo("hello"));
assertThat(reader.getRemaining(), equalTo(" world"));
}
@Test
public void readString_singleQuotes() throws Exception {
final StringReader reader = new StringReader("'hello world'");
assertThat(reader.readString(), equalTo("hello world"));
assertThat(reader.getRead(), equalTo("'hello world'"));
assertThat(reader.getRemaining(), equalTo(""));
}
@Test
public void readString_doubleQuotes() throws Exception {
final StringReader reader = new StringReader("\"hello world\"");
assertThat(reader.readString(), equalTo("hello world"));
assertThat(reader.getRead(), equalTo("\"hello world\""));
assertThat(reader.getRemaining(), equalTo(""));
}
@Test
public void readInt() throws Exception {
final StringReader reader = new StringReader("1234567890");
@ -352,58 +294,6 @@ public class StringReaderTest {
assertThat(reader.getRemaining(), equalTo("foo bar"));
}
@Test
public void readLong() throws Exception {
final StringReader reader = new StringReader("1234567890");
assertThat(reader.readLong(), is(1234567890L));
assertThat(reader.getRead(), equalTo("1234567890"));
assertThat(reader.getRemaining(), equalTo(""));
}
@Test
public void readLong_negative() throws Exception {
final StringReader reader = new StringReader("-1234567890");
assertThat(reader.readLong(), is(-1234567890L));
assertThat(reader.getRead(), equalTo("-1234567890"));
assertThat(reader.getRemaining(), equalTo(""));
}
@Test
public void readLong_invalid() throws Exception {
try {
new StringReader("12.34").readLong();
} catch (final CommandSyntaxException ex) {
assertThat(ex.getType(), is(CommandSyntaxException.BUILT_IN_EXCEPTIONS.readerInvalidLong()));
assertThat(ex.getCursor(), is(0));
}
}
@Test
public void readLong_none() throws Exception {
try {
new StringReader("").readLong();
} catch (final CommandSyntaxException ex) {
assertThat(ex.getType(), is(CommandSyntaxException.BUILT_IN_EXCEPTIONS.readerExpectedLong()));
assertThat(ex.getCursor(), is(0));
}
}
@Test
public void readLong_withRemaining() throws Exception {
final StringReader reader = new StringReader("1234567890 foo bar");
assertThat(reader.readLong(), is(1234567890L));
assertThat(reader.getRead(), equalTo("1234567890"));
assertThat(reader.getRemaining(), equalTo(" foo bar"));
}
@Test
public void readLong_withRemainingImmediate() throws Exception {
final StringReader reader = new StringReader("1234567890foo bar");
assertThat(reader.readLong(), is(1234567890L));
assertThat(reader.getRead(), equalTo("1234567890"));
assertThat(reader.getRemaining(), equalTo("foo bar"));
}
@Test
public void readDouble() throws Exception {
final StringReader reader = new StringReader("123");

View file

@ -1,81 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
package com.mojang.brigadier.arguments;
import com.google.common.testing.EqualsTester;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.context.CommandContextBuilder;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static com.mojang.brigadier.arguments.LongArgumentType.longArg;
import static org.hamcrest.Matchers.hasToString;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
@RunWith(MockitoJUnitRunner.class)
public class LongArgumentTypeTest {
private LongArgumentType type;
@Mock
private CommandContextBuilder<Object> context;
@Before
public void setUp() throws Exception {
type = longArg(-100, 1_000_000_000_000L);
}
@Test
public void parse() throws Exception {
final StringReader reader = new StringReader("15");
assertThat(longArg().parse(reader), is(15L));
assertThat(reader.canRead(), is(false));
}
@Test
public void parse_tooSmall() throws Exception {
final StringReader reader = new StringReader("-5");
try {
longArg(0, 100).parse(reader);
fail();
} catch (final CommandSyntaxException ex) {
assertThat(ex.getType(), is(CommandSyntaxException.BUILT_IN_EXCEPTIONS.longTooLow()));
assertThat(ex.getCursor(), is(0));
}
}
@Test
public void parse_tooBig() throws Exception {
final StringReader reader = new StringReader("5");
try {
longArg(-100, 0).parse(reader);
fail();
} catch (final CommandSyntaxException ex) {
assertThat(ex.getType(), is(CommandSyntaxException.BUILT_IN_EXCEPTIONS.longTooHigh()));
assertThat(ex.getCursor(), is(0));
}
}
@Test
public void testEquals() throws Exception {
new EqualsTester()
.addEqualityGroup(longArg(), longArg())
.addEqualityGroup(longArg(-100, 100), longArg(-100, 100))
.addEqualityGroup(longArg(-100, 50), longArg(-100, 50))
.addEqualityGroup(longArg(-50, 100), longArg(-50, 100))
.testEquals();
}
@Test
public void testToString() throws Exception {
assertThat(longArg(), hasToString("longArg()"));
assertThat(longArg(-100), hasToString("longArg(-100)"));
assertThat(longArg(-100, 100), hasToString("longArg(-100, 100)"));
assertThat(longArg(Long.MIN_VALUE, 100), hasToString("longArg(-9223372036854775808, 100)"));
}
}