diff --git a/.gitignore b/.gitignore index a5b1113..b63da45 100644 --- a/.gitignore +++ b/.gitignore @@ -1,21 +1,42 @@ .gradle -**/build/ -!src/**/build/ +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ -# Ignore Gradle GUI config -gradle-app.setting +### IntelliJ IDEA ### +.idea/modules.xml +.idea/jarRepositories.xml +.idea/compiler.xml +.idea/libraries/ +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ -# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) -!gradle-wrapper.jar +### Eclipse ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ -# Avoid ignore Gradle wrappper properties -!gradle-wrapper.properties +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ -# Cache of project -.gradletasknamecache +### VS Code ### +.vscode/ -# Eclipse Gradle plugin generated files -# Eclipse Core -.project -# JDT-specific (Eclipse Java Development Tools) -.classpath +### Mac OS ### +.DS_Store \ No newline at end of file diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..13566b8 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,8 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Editor-based HTTP Client requests +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/.idea/gradle.xml b/.idea/gradle.xml new file mode 100644 index 0000000..ff72d26 --- /dev/null +++ b/.idea/gradle.xml @@ -0,0 +1,20 @@ + + + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..fae6c8e --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..35eb1dd --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..bf3184c --- /dev/null +++ b/build.gradle @@ -0,0 +1,19 @@ +plugins { + id 'java' + id 'java-library' +} + +group = 'me.tofaa' +version = '1.0-SNAPSHOT' + +repositories { + mavenCentral() + maven { + url = "https://libraries.minecraft.net/" + } +} + +dependencies { + compileOnlyApi("com.mojang:brigadier:1.1.8") + compileOnlyApi("org.jetbrains:annotations:24.0.0") +} diff --git a/example-plugin/build.gradle b/example-plugin/build.gradle new file mode 100644 index 0000000..9fe78be --- /dev/null +++ b/example-plugin/build.gradle @@ -0,0 +1,27 @@ +plugins { + id 'java' + id 'xyz.jpenilla.run-paper' version '2.2.2' + id 'com.github.johnrengelman.shadow' version '7.0.0' +} + +group = 'me.tofaa' +version = '1.0-SNAPSHOT' + +repositories { + mavenCentral() + maven { + url = "https://repo.papermc.io/repository/maven-public/" + } +} + +dependencies { + implementation(project(":paper")) + compileOnly("io.papermc.paper:paper-api:1.20.4-R0.1-SNAPSHOT") +} + + +tasks { + runServer { + minecraftVersion("1.20.4") + } +} \ No newline at end of file diff --git a/example-plugin/src/main/java/me/tofaa/ExampleCommand.java b/example-plugin/src/main/java/me/tofaa/ExampleCommand.java new file mode 100644 index 0000000..665f5c0 --- /dev/null +++ b/example-plugin/src/main/java/me/tofaa/ExampleCommand.java @@ -0,0 +1,17 @@ +package me.tofaa; + +import me.tofaa.brigadierwrapper.paper.PaperCommand; +import net.kyori.adventure.text.minimessage.MiniMessage; + +public class ExampleCommand extends PaperCommand { + + public ExampleCommand() { + super("example", "silly-command"); + addSyntax((context) -> { + context.getSource().getBukkitSender().sendMessage("Woah!!!!"); + String arg = context.getArgument("message", String.class); + context.getSource().getBukkitSender().sendMessage(MiniMessage.miniMessage().deserialize(arg)); + }, stringArg("message")); + } + +} diff --git a/example-plugin/src/main/java/me/tofaa/Main.java b/example-plugin/src/main/java/me/tofaa/Main.java new file mode 100644 index 0000000..805a2d6 --- /dev/null +++ b/example-plugin/src/main/java/me/tofaa/Main.java @@ -0,0 +1,14 @@ +package me.tofaa; + +import me.tofaa.brigadierwrapper.paper.PaperBrigadierWrapper; +import org.bukkit.plugin.java.JavaPlugin; + +public class Main extends JavaPlugin { + + + @Override + public void onEnable() { + PaperBrigadierWrapper.init(this); + PaperBrigadierWrapper.register(new ExampleCommand()); + } +} \ No newline at end of file diff --git a/example-plugin/src/main/resources/plugin.yml b/example-plugin/src/main/resources/plugin.yml new file mode 100644 index 0000000..06f0457 --- /dev/null +++ b/example-plugin/src/main/resources/plugin.yml @@ -0,0 +1,4 @@ +name: ExamplePlugin +version: 1.0 +api-version: "1.20" +main: me.tofaa.Main \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..249e583 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..57ec304 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Tue May 07 18:37:10 AZT 2024 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..1b6c787 --- /dev/null +++ b/gradlew @@ -0,0 +1,234 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..ac1b06f --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/paper/build.gradle b/paper/build.gradle new file mode 100644 index 0000000..a2d29bb --- /dev/null +++ b/paper/build.gradle @@ -0,0 +1,20 @@ +plugins { + id 'java' + id 'java-library' +} + +group = 'me.tofaa' +version = '1.0-SNAPSHOT' + +repositories { + mavenCentral() + maven { + url = "https://repo.papermc.io/repository/maven-public/" + } +} + +dependencies { + api(project(":")) + compileOnlyApi("io.papermc.paper:paper-api:1.20.4-R0.1-SNAPSHOT") + compileOnlyApi("io.papermc.paper:paper-mojangapi:1.20.4-R0.1-SNAPSHOT") +} \ No newline at end of file diff --git a/paper/src/main/java/me/tofaa/brigadierwrapper/paper/PaperBrigadierWrapper.java b/paper/src/main/java/me/tofaa/brigadierwrapper/paper/PaperBrigadierWrapper.java new file mode 100644 index 0000000..acd7885 --- /dev/null +++ b/paper/src/main/java/me/tofaa/brigadierwrapper/paper/PaperBrigadierWrapper.java @@ -0,0 +1,38 @@ +package me.tofaa.brigadierwrapper.paper; + +import com.destroystokyo.paper.event.brigadier.CommandRegisteredEvent; +import org.bukkit.Bukkit; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.plugin.java.JavaPlugin; +import org.jetbrains.annotations.NotNull; + +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; + +public final class PaperBrigadierWrapper { + + private PaperBrigadierWrapper() {} + + private static final Set COMMANDS = new HashSet<>(); + + public static void register(PaperCommand... commands) { + Collections.addAll(COMMANDS, commands); + } + + public static void init( + @NotNull JavaPlugin plugin + ) { + Bukkit.getServer().getPluginManager().registerEvents(new Listener() { + @EventHandler + public void onCmd(CommandRegisteredEvent event) { + for (PaperCommand command : COMMANDS) { + event.getRoot().addChild(command.build()); + COMMANDS.remove(command); + } + } + }, plugin); + } + +} diff --git a/paper/src/main/java/me/tofaa/brigadierwrapper/paper/PaperCommand.java b/paper/src/main/java/me/tofaa/brigadierwrapper/paper/PaperCommand.java new file mode 100644 index 0000000..f9590ee --- /dev/null +++ b/paper/src/main/java/me/tofaa/brigadierwrapper/paper/PaperCommand.java @@ -0,0 +1,59 @@ +package me.tofaa.brigadierwrapper.paper; + +import com.destroystokyo.paper.brigadier.BukkitBrigadierCommandSource; +import com.mojang.brigadier.StringReader; +import com.mojang.brigadier.arguments.ArgumentType; +import com.mojang.brigadier.exceptions.CommandSyntaxException; +import me.tofaa.brigadierwrapper.Command; +import me.tofaa.brigadierwrapper.element.ArgumentElement; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; + +import java.util.Collection; +import java.util.List; + +public class PaperCommand extends Command { + + public PaperCommand(@NotNull String name, @NotNull String... aliases) { + super(name, aliases); + } + + protected static ArgumentElement materialArg(String name) { + return new ArgumentElement<>(name, reader -> { + String materialName = reader.readString(); + Material material = Material.matchMaterial(materialName); + if (material == null) { + throw CommandSyntaxException.BUILT_IN_EXCEPTIONS.dispatcherUnknownArgument().createWithContext(reader); + } + return material; + }, (context, builder) -> { + for (Material material : Material.values()) { + builder.suggest(material.name()); + } + return builder.buildFuture(); + }); + } + + protected static ArgumentElement> playerArg(String name) { + return new ArgumentElement<>(name, reader -> { + String playerName = reader.readString(); + if (playerName.equals("@a")) { + return Bukkit.getOnlinePlayers(); + } + var player = Bukkit.getPlayer(playerName); + if (player == null) { + throw CommandSyntaxException.BUILT_IN_EXCEPTIONS.dispatcherUnknownArgument().createWithContext(reader); + } + return List.of(player); + }, (context, builder) -> { + builder.suggest("@a"); + for (Player player : Bukkit.getOnlinePlayers()) { + builder.suggest(player.getName()); + } + return builder.buildFuture(); + }); + } + +} diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..dc6e8bd --- /dev/null +++ b/settings.gradle @@ -0,0 +1,5 @@ +rootProject.name = 'BrigadierWrapper' +include 'paper' +include 'velocity' +include 'example-plugin' + diff --git a/src/main/java/me/tofaa/brigadierwrapper/Command.java b/src/main/java/me/tofaa/brigadierwrapper/Command.java new file mode 100644 index 0000000..7eb0f22 --- /dev/null +++ b/src/main/java/me/tofaa/brigadierwrapper/Command.java @@ -0,0 +1,133 @@ +package me.tofaa.brigadierwrapper; + +import com.mojang.brigadier.arguments.*; +import com.mojang.brigadier.suggestion.SuggestionProvider; +import com.mojang.brigadier.tree.LiteralCommandNode; +import me.tofaa.brigadierwrapper.element.ArgumentElement; +import me.tofaa.brigadierwrapper.element.CommandElement; +import me.tofaa.brigadierwrapper.element.LiteralElement; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.function.Predicate; + +public abstract class Command { + + private final String name; + private final String[] aliases; + + private @Nullable Predicate condition; + private @Nullable CommandExecutor defaultExecutor; + + private final List> syntaxes = new ArrayList<>(); + private final List> subCommands = new ArrayList<>(); + + public Command(@NotNull String name, @NotNull String... aliases) { + this.name = name; + this.aliases = aliases; + } + + public Command(@NotNull String name) { + this(name, new String[0]); + } + + protected final void setCondition(@NotNull Predicate condition) { + this.condition = condition; + } + + protected final void setDefaultExecutor(@NotNull CommandExecutor executor) { + this.defaultExecutor = executor; + } + + @SafeVarargs + protected final void addConditionalSyntax(@Nullable Predicate condition, @NotNull CommandExecutor executor, + @NotNull CommandElement... elements) { + var syntax = new CommandSyntax<>(condition, executor, List.of(elements)); + this.syntaxes.add(syntax); + } + + @SafeVarargs + protected final void addSyntax(@NotNull CommandExecutor executor, @NotNull CommandElement... elements) { + this.addConditionalSyntax(null, executor, elements); + } + + protected final void addSubCommand(@NotNull Command command) { + this.subCommands.add(command); + } + + public final @NotNull LiteralCommandNode build() { + return Graph.create(this).build(); + } + + public final @NotNull String getName() { + return this.name; + } + + public final @NotNull String[] getAliases() { + return this.aliases; + } + + final @Nullable Predicate getCondition() { + return this.condition; + } + + final @Nullable CommandExecutor getDefaultExecutor() { + return this.defaultExecutor; + } + + final @NotNull Collection> getSyntaxes() { + return this.syntaxes; + } + + final @NotNull Collection> getSubCommands() { + return this.subCommands; + } + + protected static @NotNull LiteralElement literalArg(@NotNull String name) { + return new LiteralElement<>(name); + } + + protected static @NotNull ArgumentElement stringArg(@NotNull String name) { + return argument(name, StringArgumentType.string()); + } + + protected static @NotNull ArgumentElement integerArg(@NotNull String name) { + return argument(name, IntegerArgumentType.integer()); + } + + protected static @NotNull ArgumentElement integerArg(@NotNull String name, int min) { + return argument(name, IntegerArgumentType.integer(min)); + } + + protected static @NotNull ArgumentElement integerArg(@NotNull String name, int min, int max) { + return argument(name, IntegerArgumentType.integer(min, max)); + } + + protected static @NotNull ArgumentElement floatArg(@NotNull String name) { + return argument(name, FloatArgumentType.floatArg()); + } + + protected static @NotNull ArgumentElement floatArg(@NotNull String name, float min) { + return argument(name, FloatArgumentType.floatArg(min)); + } + + protected static @NotNull ArgumentElement floatArg(@NotNull String name, float min, float max) { + return argument(name, FloatArgumentType.floatArg(min, max)); + } + + protected static @NotNull ArgumentElement booleanArg(@NotNull String name) { + return argument(name, BoolArgumentType.bool()); + } + + protected static @NotNull ArgumentElement argument(@NotNull String name, @NotNull ArgumentType type, @Nullable SuggestionProvider suggestionProvider) { + return new ArgumentElement<>(name, type, suggestionProvider); + } + + protected static @NotNull ArgumentElement argument(@NotNull String name, @NotNull ArgumentType type) { + return argument(name, type, null); + } + +} \ No newline at end of file diff --git a/src/main/java/me/tofaa/brigadierwrapper/CommandExecutor.java b/src/main/java/me/tofaa/brigadierwrapper/CommandExecutor.java new file mode 100644 index 0000000..46d879f --- /dev/null +++ b/src/main/java/me/tofaa/brigadierwrapper/CommandExecutor.java @@ -0,0 +1,9 @@ +package me.tofaa.brigadierwrapper; + +import com.mojang.brigadier.context.CommandContext; +import org.jetbrains.annotations.NotNull; + +public interface CommandExecutor { + + void execute(@NotNull CommandContext context); +} diff --git a/src/main/java/me/tofaa/brigadierwrapper/CommandSyntax.java b/src/main/java/me/tofaa/brigadierwrapper/CommandSyntax.java new file mode 100644 index 0000000..1319b2a --- /dev/null +++ b/src/main/java/me/tofaa/brigadierwrapper/CommandSyntax.java @@ -0,0 +1,11 @@ +package me.tofaa.brigadierwrapper; + +import me.tofaa.brigadierwrapper.element.CommandElement; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.List; +import java.util.function.Predicate; + +public record CommandSyntax(@Nullable Predicate condition, @NotNull CommandExecutor executor, @NotNull List> elements) { +} diff --git a/src/main/java/me/tofaa/brigadierwrapper/ConversionNode.java b/src/main/java/me/tofaa/brigadierwrapper/ConversionNode.java new file mode 100644 index 0000000..aed4a3a --- /dev/null +++ b/src/main/java/me/tofaa/brigadierwrapper/ConversionNode.java @@ -0,0 +1,53 @@ +package me.tofaa.brigadierwrapper; + +import me.tofaa.brigadierwrapper.element.CommandElement; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import static me.tofaa.brigadierwrapper.Graph.commandToElement; + +record ConversionNode(@NotNull CommandElement element, @Nullable Execution execution, + @NotNull Map, ConversionNode> nextMap) { + + static @NotNull ConversionNode fromCommand(@NotNull Command command) { + ConversionNode root = new ConversionNode<>(commandToElement(command), Execution.fromCommand(command)); + + for (CommandSyntax syntax : command.getSyntaxes()) { + ConversionNode syntaxNode = root; + + for (CommandElement element : syntax.elements()) { + boolean last = element == syntax.elements().get(syntax.elements().size() - 1); + syntaxNode = syntaxNode.nextMap.computeIfAbsent(element, e -> { + Execution execution = last ? Execution.fromSyntax(syntax) : null; + return new ConversionNode<>(e, execution); + }); + } + } + + for (Command subCommand : command.getSubCommands()) { + root.nextMap.put(commandToElement(subCommand), fromCommand(subCommand)); + } + + return root; + } + + ConversionNode(@NotNull CommandElement element, @Nullable Execution execution) { + this(element, execution, new LinkedHashMap<>()); + } + + Node toNode() { + @SuppressWarnings("unchecked") // this is fine - we only put Node in to this array + Node[] nodes = (Node[]) new Node[this.nextMap.size()]; + + int i = 0; + for (ConversionNode entry : this.nextMap.values()) { + nodes[i++] = entry.toNode(); + } + + return new Node<>(this.element, this.execution, List.of(nodes)); + } +} \ No newline at end of file diff --git a/src/main/java/me/tofaa/brigadierwrapper/Execution.java b/src/main/java/me/tofaa/brigadierwrapper/Execution.java new file mode 100644 index 0000000..2529f94 --- /dev/null +++ b/src/main/java/me/tofaa/brigadierwrapper/Execution.java @@ -0,0 +1,60 @@ +package me.tofaa.brigadierwrapper; + + +import com.mojang.brigadier.builder.ArgumentBuilder; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.concurrent.Executor; +import java.util.concurrent.Executors; +import java.util.function.Predicate; + +record Execution(@NotNull Predicate predicate, @Nullable CommandExecutor defaultExecutor, @Nullable CommandExecutor executor, + @Nullable Predicate condition) implements Predicate { + + private static final Executor CACHED_EXECUTOR = Executors.newCachedThreadPool(); + + + static @NotNull Execution fromCommand(@NotNull Command command) { + CommandExecutor defaultExecutor = command.getDefaultExecutor(); + Predicate defaultCondition = command.getCondition(); + + CommandExecutor executor = defaultExecutor; + Predicate condition = defaultCondition; + for (CommandSyntax syntax : command.getSyntaxes()) { + if (!syntax.elements().isEmpty()) continue; + executor = syntax.executor(); + condition = syntax.condition(); + break; + } + + return new Execution<>(source -> defaultCondition == null || defaultCondition.test(source), defaultExecutor, executor, condition); + } + + static @NotNull Execution fromSyntax(@NotNull CommandSyntax syntax) { + CommandExecutor executor = syntax.executor(); + Predicate condition = syntax.condition(); + return new Execution<>(source -> condition == null || condition.test(source), null, executor, condition); + } + + @Override + public boolean test(@NotNull S source) { + return this.predicate.test(source); + } + + void addToBuilder(@NotNull ArgumentBuilder builder) { + if (this.condition != null) builder.requires(this.condition); + if (this.executor != null) { + builder.executes(convertExecutor(this.executor)); + } else if (this.defaultExecutor != null) { + builder.executes(convertExecutor(this.defaultExecutor)); + } + } + + private static com.mojang.brigadier.@NotNull Command convertExecutor(@NotNull CommandExecutor executor) { + return context -> { + CACHED_EXECUTOR.execute(() -> executor.execute(context)); + return 1; + }; + } +} diff --git a/src/main/java/me/tofaa/brigadierwrapper/Graph.java b/src/main/java/me/tofaa/brigadierwrapper/Graph.java new file mode 100644 index 0000000..a1cdd28 --- /dev/null +++ b/src/main/java/me/tofaa/brigadierwrapper/Graph.java @@ -0,0 +1,27 @@ +package me.tofaa.brigadierwrapper; + +import com.mojang.brigadier.tree.CommandNode; +import com.mojang.brigadier.tree.LiteralCommandNode; +import me.tofaa.brigadierwrapper.element.CommandElement; +import me.tofaa.brigadierwrapper.element.LiteralElement; +import org.jetbrains.annotations.NotNull; + +record Graph(@NotNull Node root) { + + + static @NotNull Graph create(@NotNull Command command) { + return new Graph<>(Node.command(command)); + } + + static @NotNull CommandElement commandToElement(@NotNull Command command) { + return new LiteralElement<>(command.getName()); + } + + @NotNull LiteralCommandNode build() { + CommandNode node = this.root.build(); + if (!(node instanceof LiteralCommandNode literalNode)) { + throw new IllegalStateException("Root node is somehow not a literal node. This should be impossible."); + } + return literalNode; + } +} \ No newline at end of file diff --git a/src/main/java/me/tofaa/brigadierwrapper/Node.java b/src/main/java/me/tofaa/brigadierwrapper/Node.java new file mode 100644 index 0000000..fcf1557 --- /dev/null +++ b/src/main/java/me/tofaa/brigadierwrapper/Node.java @@ -0,0 +1,28 @@ +package me.tofaa.brigadierwrapper; + +import com.mojang.brigadier.builder.ArgumentBuilder; +import com.mojang.brigadier.tree.CommandNode; +import me.tofaa.brigadierwrapper.element.CommandElement; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.List; + +record Node(@NotNull CommandElement element, @Nullable Execution execution, @NotNull List> children) { + + static @NotNull Node command(@NotNull Command command) { + return ConversionNode.fromCommand(command).toNode(); + } + + @NotNull + CommandNode build() { + ArgumentBuilder builder = this.element.toBuilder(); + if (this.execution != null) this.execution.addToBuilder(builder); + + for (Node child : this.children) { + builder.then(child.build()); + } + + return builder.build(); + } +} \ No newline at end of file diff --git a/src/main/java/me/tofaa/brigadierwrapper/element/ArgumentElement.java b/src/main/java/me/tofaa/brigadierwrapper/element/ArgumentElement.java new file mode 100644 index 0000000..0832003 --- /dev/null +++ b/src/main/java/me/tofaa/brigadierwrapper/element/ArgumentElement.java @@ -0,0 +1,20 @@ +package me.tofaa.brigadierwrapper.element; + + +import com.mojang.brigadier.arguments.ArgumentType; +import com.mojang.brigadier.builder.ArgumentBuilder; +import com.mojang.brigadier.builder.RequiredArgumentBuilder; +import com.mojang.brigadier.suggestion.SuggestionProvider; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public record ArgumentElement(@NotNull String name, @NotNull ArgumentType type, + @Nullable SuggestionProvider suggestionProvider) implements CommandElement { + + @Override + public @NotNull ArgumentBuilder toBuilder() { + var builder = RequiredArgumentBuilder.argument(this.name, this.type); + if (this.suggestionProvider != null) builder.suggests(this.suggestionProvider); + return builder; + } +} \ No newline at end of file diff --git a/src/main/java/me/tofaa/brigadierwrapper/element/CommandElement.java b/src/main/java/me/tofaa/brigadierwrapper/element/CommandElement.java new file mode 100644 index 0000000..cfddefb --- /dev/null +++ b/src/main/java/me/tofaa/brigadierwrapper/element/CommandElement.java @@ -0,0 +1,9 @@ +package me.tofaa.brigadierwrapper.element; + +import com.mojang.brigadier.builder.ArgumentBuilder; +import org.jetbrains.annotations.NotNull; + +public interface CommandElement { + + @NotNull ArgumentBuilder toBuilder(); +} \ No newline at end of file diff --git a/src/main/java/me/tofaa/brigadierwrapper/element/LiteralElement.java b/src/main/java/me/tofaa/brigadierwrapper/element/LiteralElement.java new file mode 100644 index 0000000..89f8ae2 --- /dev/null +++ b/src/main/java/me/tofaa/brigadierwrapper/element/LiteralElement.java @@ -0,0 +1,13 @@ +package me.tofaa.brigadierwrapper.element; + +import com.mojang.brigadier.builder.ArgumentBuilder; +import com.mojang.brigadier.builder.LiteralArgumentBuilder; +import org.jetbrains.annotations.NotNull; + +public record LiteralElement(@NotNull String name) implements CommandElement { + + @Override + public @NotNull ArgumentBuilder toBuilder() { + return LiteralArgumentBuilder.literal(this.name); + } +} \ No newline at end of file diff --git a/velocity/build.gradle b/velocity/build.gradle new file mode 100644 index 0000000..7fe6275 --- /dev/null +++ b/velocity/build.gradle @@ -0,0 +1,19 @@ +plugins { + id 'java' + id 'java-library' +} + +group = 'me.tofaa' +version = '1.0-SNAPSHOT' + +repositories { + mavenCentral() + maven { + url = "https://repo.papermc.io/repository/maven-public/" + } +} + +dependencies { + compileOnly("com.velocitypowered:velocity-api:3.3.0-SNAPSHOT") + api(project(":")) +} diff --git a/velocity/src/main/java/me/tofaa/brigadierwrapper/velocity/VelocityBrigadierWrapper.java b/velocity/src/main/java/me/tofaa/brigadierwrapper/velocity/VelocityBrigadierWrapper.java new file mode 100644 index 0000000..58a8e1d --- /dev/null +++ b/velocity/src/main/java/me/tofaa/brigadierwrapper/velocity/VelocityBrigadierWrapper.java @@ -0,0 +1,19 @@ +package me.tofaa.brigadierwrapper.velocity; + +import com.velocitypowered.api.command.BrigadierCommand; +import com.velocitypowered.api.proxy.ProxyServer; + +public final class VelocityBrigadierWrapper { + + private VelocityBrigadierWrapper() {} + + public static void registerCommands( + ProxyServer server, + VelocityCommand... commands + ) { + for (VelocityCommand command : commands) { + server.getCommandManager().register(new BrigadierCommand(command.build())); + } + } + +} diff --git a/velocity/src/main/java/me/tofaa/brigadierwrapper/velocity/VelocityCommand.java b/velocity/src/main/java/me/tofaa/brigadierwrapper/velocity/VelocityCommand.java new file mode 100644 index 0000000..9da8c25 --- /dev/null +++ b/velocity/src/main/java/me/tofaa/brigadierwrapper/velocity/VelocityCommand.java @@ -0,0 +1,61 @@ +package me.tofaa.brigadierwrapper.velocity; + +import com.mojang.brigadier.arguments.ArgumentType; +import com.mojang.brigadier.exceptions.CommandSyntaxException; +import com.mojang.brigadier.suggestion.SuggestionProvider; +import com.velocitypowered.api.command.CommandSource; +import com.velocitypowered.api.proxy.Player; +import com.velocitypowered.api.proxy.ProxyServer; +import com.velocitypowered.api.proxy.server.RegisteredServer; +import me.tofaa.brigadierwrapper.Command; +import me.tofaa.brigadierwrapper.element.ArgumentElement; +import org.jetbrains.annotations.NotNull; + +public class VelocityCommand extends Command { + + public VelocityCommand(@NotNull String name, @NotNull String... aliases) { + super(name, aliases); + } + + protected static ArgumentElement serverArg(ProxyServer server, String name, SuggestionProvider suggestionProvider) { + ArgumentType argumentType = reader -> { + String s = reader.readUnquotedString(); + RegisteredServer server1 = server.getServer(s).orElse(null); + if (server1 == null) { + throw CommandSyntaxException.BUILT_IN_EXCEPTIONS.dispatcherUnknownArgument().createWithContext(reader); + } + return server1; + }; + return new ArgumentElement<>(name, argumentType, suggestionProvider); + } + + protected static ArgumentElement serverArg(ProxyServer server, String name) { + return serverArg(server, name, (context, builder) -> { + for (RegisteredServer server1 : server.getAllServers()) { + builder.suggest(server1.getServerInfo().getName()); + } + return builder.buildFuture(); + }); + } + + protected static ArgumentElement sourceArg(ProxyServer server, String name, SuggestionProvider suggestionProvider) { + ArgumentType argumentType = reader -> { + String s = reader.readUnquotedString(); + CommandSource source = server.getPlayer(s).orElse(null); + if (source == null) { + throw CommandSyntaxException.BUILT_IN_EXCEPTIONS.dispatcherUnknownArgument().createWithContext(reader); + } + return source; + }; + return new ArgumentElement<>(name, argumentType, suggestionProvider); + } + + protected static ArgumentElement sourceArg(ProxyServer server, String name) { + return sourceArg(server, name, (context, builder) -> { + for (Player source : server.getAllPlayers()) { + builder.suggest(source.getUsername()); + } + return builder.buildFuture(); + }); + } +}