diff --git a/README.md b/README.md index 996961c..f05df8d 100644 --- a/README.md +++ b/README.md @@ -3,21 +3,20 @@ **Plugin page**: [https://www.spigotmc.org/resources/75164/](https://www.spigotmc.org/resources/75164/) ## About -View Distance Tweaks is a Spigot plugin that allows for dynamic per-world simulation distance and view distance. +View Distance Tweaks is a Spigot plugin that allows for dynamic per-world simulation distance and view distance. Now with +support for Minecraft 1.20.4 with PaperMC! ## Building -1. Install dependency NabConfiguration to maven local -```bash -git clone https://github.com/froobynooby/nab-configuration -cd nab-configuration -./gradlew clean install -``` -2. Clone ViewDistanceTweaks and build +1. Clone ViewDistanceTweaks and build ```bash git clone https://github.com/froobynooby/ViewDistanceTweaks cd ViewDistanceTweaks -./gradlew clean build +./gradlew clean shadowJar ``` +2. Find jar in `build/libs/ViewDistanceTweaks-x.x.x.jar` + +## Setup -3. Find jar in `ViewDistanceTweaks/build/libs` \ No newline at end of file +Place the .jar file into your plugins folder, then run the server, you will need to change the config file to set enabled +to true. \ No newline at end of file diff --git a/build.gradle b/build.gradle index 4493b72..e599e74 100644 --- a/build.gradle +++ b/build.gradle @@ -1,25 +1,25 @@ plugins { - id 'com.github.johnrengelman.shadow' version '5.2.0' + id 'com.github.johnrengelman.shadow' version '8.0.0' id 'java' } group 'com.froobworld' -version '1.5.7' -jar.enabled = false; +version '1.6.0' +jar.enabled = false -sourceCompatibility = 1.8 +sourceCompatibility = 17 repositories { mavenLocal(); mavenCentral() maven { - url "https://hub.spigotmc.org/nexus/content/repositories/snapshots" + url = "https://hub.spigotmc.org/nexus/content/repositories/snapshots" } maven { - url "https://oss.sonatype.org/content/groups/public/" + url = "https://oss.sonatype.org/content/groups/public/" } maven { - url "https://papermc.io/repo/repository/maven-public/" + url = "https://papermc.io/repo/repository/maven-public/" } maven { url = 'https://repo.extendedclip.com/content/repositories/placeholderapi/' @@ -27,13 +27,13 @@ repositories { } dependencies { - testCompile group: 'junit', name: 'junit', version: '4.12' - compileOnly 'com.destroystokyo.paper:paper-api:1.15.2-R0.1-SNAPSHOT' - compileOnly 'me.clip:placeholderapi:2.10.9' - compileOnly 'io.netty:netty-all:4.1.74.Final' - compile 'org.jooq:joor-java-8:0.9.14' - compile 'com.froobworld:nab-configuration:1.0.2' - compile 'org.bstats:bstats-bukkit:3.0.0' + testImplementation "org.junit.jupiter:junit-jupiter:5.9.3" + implementation "io.papermc.paper:paper-api:1.20.4-R0.1-SNAPSHOT" + implementation 'me.clip:placeholderapi:2.10.9' + implementation 'io.netty:netty-all:4.1.95.Final' + + implementation 'org.jooq:joor-java-8:0.9.14' + implementation 'org.bstats:bstats-bukkit:3.0.2' } processResources { diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index 87b738c..7f93135 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 44e7c4d..3fa8f86 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,7 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-5.2.1-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.4-bin.zip +networkTimeout=10000 +validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew index af6708f..1aa94a4 100755 --- a/gradlew +++ b/gradlew @@ -1,78 +1,127 @@ -#!/usr/bin/env sh +#!/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 UN*X -## +# +# 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/HEAD/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 -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi +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 -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null - -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$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"' +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" +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 - ;; - MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; +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" + JAVACMD=$JAVA_HOME/jre/sh/java else - JAVACMD="$JAVA_HOME/bin/java" + JAVACMD=$JAVA_HOME/bin/java fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME @@ -81,92 +130,120 @@ 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. + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + 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 fi # Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac fi -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -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" ) -# For Cygwin, switch paths to Windows format before running java -if $cygwin ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" + 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 - i=$((i+1)) + # 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 - case $i in - (0) set -- ;; - (1) set -- "$args0" ;; - (2) set -- "$args0" "$args1" ;; - (3) set -- "$args0" "$args1" "$args2" ;; - (4) set -- "$args0" "$args1" "$args2" "$args3" ;; - (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac fi -# Escape application args -save () { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=$(save "$@") - -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" -# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong -if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then - cd "$(dirname "$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"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" fi +# 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 index 6d57edc..6689b85 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -1,84 +1,92 @@ -@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 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" - -@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 init - -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 init - -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 - -:init -@rem Get command-line arguments, handling Windows variants - -if not "%OS%" == "Windows_NT" goto win9xME_args - -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 - -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* - -: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 %CMD_LINE_ARGS% - -: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 +@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=. +@rem This is normally unused +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% equ 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% equ 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! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle index 935091c..01e0b6b 100644 --- a/settings.gradle +++ b/settings.gradle @@ -1,2 +1 @@ rootProject.name = 'ViewDistanceTweaks' - diff --git a/src/main/java/com/froobworld/nabconfiguration/ConfigEntries.java b/src/main/java/com/froobworld/nabconfiguration/ConfigEntries.java new file mode 100644 index 0000000..c09a290 --- /dev/null +++ b/src/main/java/com/froobworld/nabconfiguration/ConfigEntries.java @@ -0,0 +1,52 @@ +package com.froobworld.nabconfiguration; + +import java.util.ArrayList; +import java.util.List; + +public final class ConfigEntries { + + + public static ConfigEntry doubleEntry() { + return new ConfigEntry<>(o -> ((Number) o).doubleValue()); + } + + public static ConfigEntry floatEntry() { + return new ConfigEntry<>(o -> ((Number) o).floatValue()); + } + + public static ConfigEntry longEntry() { + return new ConfigEntry<>(o -> ((Number) o).longValue()); + } + + public static ConfigEntry integerEntry() { + return new ConfigEntry<>(o -> ((Number) o).intValue()); + } + + public static ConfigEntry shortEntry() { + return new ConfigEntry<>(o -> ((Number) o).shortValue()); + } + + public static ConfigEntry byteEntry() { + return new ConfigEntry<>(o -> ((Number) o).byteValue()); + } + + public static > ConfigEntry enumEntry(Class e) { + return enumEntry(e, false); + } + + public static > ConfigEntry enumEntry(Class e, boolean caseSensitive) { + return new ConfigEntry<>(o -> { + for (E value : e.getEnumConstants()) { + if (caseSensitive ? value.name().equals(o.toString()) : value.name().equalsIgnoreCase(o.toString())) { + return value; + } + } + return null; + }); + } + + public static ConfigEntry> stringListEntry() { + return new ConfigEntry<>(o -> o == null ? new ArrayList<>() : (List) o); + } + +} diff --git a/src/main/java/com/froobworld/nabconfiguration/ConfigEntry.java b/src/main/java/com/froobworld/nabconfiguration/ConfigEntry.java new file mode 100644 index 0000000..ec29142 --- /dev/null +++ b/src/main/java/com/froobworld/nabconfiguration/ConfigEntry.java @@ -0,0 +1,27 @@ +package com.froobworld.nabconfiguration; + +import java.util.function.Function; +import java.util.function.Supplier; + +public class ConfigEntry implements Supplier { + private final Function mappingFunction; + private T value; + + public ConfigEntry() { + this(object -> (T) object); + } + + public ConfigEntry(Function mappingFunction) { + this.mappingFunction = mappingFunction; + } + + + @Override + public T get() { + return value; + } + + void setValue(Object value) { + this.value = mappingFunction.apply(value); + } +} diff --git a/src/main/java/com/froobworld/nabconfiguration/ConfigEntryMap.java b/src/main/java/com/froobworld/nabconfiguration/ConfigEntryMap.java new file mode 100644 index 0000000..ccfa990 --- /dev/null +++ b/src/main/java/com/froobworld/nabconfiguration/ConfigEntryMap.java @@ -0,0 +1,44 @@ +package com.froobworld.nabconfiguration; + +import java.util.HashMap; +import java.util.Map; +import java.util.function.Function; +import java.util.function.Supplier; + +public class ConfigEntryMap { + private final Function keyMappingFunction; + private final Map> entryMap = new HashMap<>(); + private final Supplier> emptyConfigEntrySupplier; + private ConfigEntry def; + private final boolean ignoreCase; + + public ConfigEntryMap(Function keyMappingFunction, Supplier> emptyConfigEntrySupplier, boolean ignoreCase) { + this.keyMappingFunction = keyMappingFunction; + this.emptyConfigEntrySupplier = emptyConfigEntrySupplier; + this.def = emptyConfigEntrySupplier.get(); + this.ignoreCase = ignoreCase; + } + + void clear() { + entryMap.clear(); + def = emptyConfigEntrySupplier.get(); + } + + public ConfigEntry of(K key) { + String mappedKey = keyMappingFunction.apply(key); + mappedKey = ignoreCase ? mappedKey.toLowerCase() : mappedKey; + return entryMap.getOrDefault(mappedKey, def); + } + + void setDefault(Object def) { + this.def.setValue(def); + } + + void put(String key, Object value) { + key = ignoreCase ? key.toLowerCase() : key; + ConfigEntry configEntry = emptyConfigEntrySupplier.get(); + configEntry.setValue(value); + entryMap.put(key, configEntry); + } + +} diff --git a/src/main/java/com/froobworld/nabconfiguration/ConfigSection.java b/src/main/java/com/froobworld/nabconfiguration/ConfigSection.java new file mode 100644 index 0000000..0864d69 --- /dev/null +++ b/src/main/java/com/froobworld/nabconfiguration/ConfigSection.java @@ -0,0 +1,3 @@ +package com.froobworld.nabconfiguration; + +public abstract class ConfigSection {} diff --git a/src/main/java/com/froobworld/nabconfiguration/ConfigSectionMap.java b/src/main/java/com/froobworld/nabconfiguration/ConfigSectionMap.java new file mode 100644 index 0000000..5c74461 --- /dev/null +++ b/src/main/java/com/froobworld/nabconfiguration/ConfigSectionMap.java @@ -0,0 +1,44 @@ +package com.froobworld.nabconfiguration; + +import java.util.HashMap; +import java.util.Map; +import java.util.function.Function; + +public class ConfigSectionMap { + private final Function keyMappingFunction; + private final Map sectionMap = new HashMap<>(); + private final Class entryType; + private final boolean ignoreCase; + private C defaultSection; + + public ConfigSectionMap(Function keyMappingFunction, Class entryType, boolean ignoreCase) { + this.keyMappingFunction = keyMappingFunction; + this.entryType = entryType; + this.ignoreCase = ignoreCase; + } + + void clear() { + sectionMap.clear(); + defaultSection = null; + } + + void setDefaultSection(C defaultSection) { + this.defaultSection = defaultSection; + } + + void put(String key, C configSection) { + key = ignoreCase ? key.toLowerCase() : key; + sectionMap.put(key, configSection); + } + + public C of(K key) { + String mappedKey = keyMappingFunction.apply(key); + mappedKey = ignoreCase ? mappedKey.toLowerCase() : mappedKey; + return sectionMap.getOrDefault(mappedKey, defaultSection); + } + + Class entryType() { + return entryType; + } + +} diff --git a/src/main/java/com/froobworld/nabconfiguration/ConfigSectionPopulator.java b/src/main/java/com/froobworld/nabconfiguration/ConfigSectionPopulator.java new file mode 100644 index 0000000..8b7c303 --- /dev/null +++ b/src/main/java/com/froobworld/nabconfiguration/ConfigSectionPopulator.java @@ -0,0 +1,79 @@ +package com.froobworld.nabconfiguration; + +import com.froobworld.nabconfiguration.annotations.Entry; +import com.froobworld.nabconfiguration.annotations.EntryMap; +import com.froobworld.nabconfiguration.annotations.Section; +import com.froobworld.nabconfiguration.annotations.SectionMap; +import com.froobworld.nabconfiguration.utils.InstantFallbackConfigurationSection; +import org.bukkit.configuration.file.YamlConfiguration; + +import java.io.File; +import java.lang.reflect.Field; + +public class ConfigSectionPopulator { + private InstantFallbackConfigurationSection configurationSection; + private ConfigSection workConfigSection; + + public ConfigSectionPopulator(File configFile, ConfigSection configSection) { + this(new InstantFallbackConfigurationSection(YamlConfiguration.loadConfiguration(configFile)), configSection); + } + + private ConfigSectionPopulator(InstantFallbackConfigurationSection configurationSection, ConfigSection workingConfigSection) { + this.configurationSection = configurationSection; + this.workConfigSection = workingConfigSection; + } + + public void populate() throws Exception { + + for (Field field : workConfigSection.getClass().getDeclaredFields()) { + field.setAccessible(true); + { + Section sectionAnnotation = field.getAnnotation(Section.class); + if (sectionAnnotation != null) { + ConfigSection subConfigSection = (ConfigSection) field.get(workConfigSection); + new ConfigSectionPopulator(configurationSection.getSection(sectionAnnotation.key(), null), subConfigSection).populate(); + } + } + + { + SectionMap sectionMapAnnotation = field.getAnnotation(SectionMap.class); + if (sectionMapAnnotation != null) { + ConfigSectionMap configSectionMap = (ConfigSectionMap) field.get(workConfigSection); + configSectionMap.clear(); + InstantFallbackConfigurationSection mapSection = configurationSection.getSection(sectionMapAnnotation.key(), null); + + ConfigSection defaultEntry = (ConfigSection) configSectionMap.entryType().getConstructor().newInstance(); + new ConfigSectionPopulator(mapSection.getSection(sectionMapAnnotation.defaultKey(), null), defaultEntry).populate(); + configSectionMap.setDefaultSection(defaultEntry); + + for (String key : mapSection.getKeys(false)) { + ConfigSection newEntry = (ConfigSection) configSectionMap.entryType().getConstructor().newInstance(); + new ConfigSectionPopulator(mapSection.getSection(key, sectionMapAnnotation.defaultKey()), newEntry).populate(); + configSectionMap.put(key, newEntry); + } + } + } + { + Entry entryAnnotation = field.getAnnotation(Entry.class); + if (entryAnnotation != null) { + ConfigEntry configEntry = (ConfigEntry) field.get(workConfigSection); + configEntry.setValue(configurationSection.get(entryAnnotation.key())); + } + } + { + EntryMap entryMapAnnotation = field.getAnnotation(EntryMap.class); + if (entryMapAnnotation != null) { + ConfigEntryMap configEntryMap = (ConfigEntryMap) field.get(workConfigSection); + configEntryMap.clear(); + InstantFallbackConfigurationSection mapSection = configurationSection.getSection(entryMapAnnotation.key(), null); + + configEntryMap.setDefault(mapSection.get(entryMapAnnotation.defaultKey())); + for (String key : mapSection.getKeys(false)) { + configEntryMap.put(key, mapSection.get(key)); + } + } + } + } + } + +} diff --git a/src/main/java/com/froobworld/nabconfiguration/NabConfiguration.java b/src/main/java/com/froobworld/nabconfiguration/NabConfiguration.java new file mode 100644 index 0000000..da59b52 --- /dev/null +++ b/src/main/java/com/froobworld/nabconfiguration/NabConfiguration.java @@ -0,0 +1,72 @@ +package com.froobworld.nabconfiguration; + +import com.froobworld.nabconfiguration.patcher.ConfigPatchLoader; +import org.yaml.snakeyaml.Yaml; + +import java.io.*; +import java.nio.file.Files; +import java.util.List; +import java.util.Map; +import java.util.function.Function; +import java.util.function.Supplier; +import java.util.stream.Collectors; + +public class NabConfiguration extends ConfigSection { + private final Yaml yaml = new Yaml(); + private final File configFile; + private final Supplier copyStreamSupplier; + private final Function patchStreamSupplier; + private final int currentVersion; + + public NabConfiguration(File configFile, Supplier copyStreamSupplier, Function patchStreamSupplier, int currentVersion) { + this.configFile = configFile; + this.copyStreamSupplier = copyStreamSupplier; + this.patchStreamSupplier = patchStreamSupplier; + this.currentVersion = currentVersion; + } + + + public void load() throws Exception { + init(); + new ConfigSectionPopulator(configFile, this).populate(); + } + + private void init() throws IOException { + if (!configFile.exists()) { + configFile.getParentFile().mkdirs(); + Files.copy(copyStreamSupplier.get(), configFile.toPath()); + } + for (;;) { + int version = -1; + try (FileReader reader = new FileReader(configFile)) { + version = (int) ((Map) yaml.load(reader)).get("version"); + } catch (Exception ex) { + throw new IllegalStateException("Could not find version while initialising " + configFile.getName() + ".", ex); + } + if (version < currentVersion) { + try (InputStream inputStream = patchStreamSupplier.apply(version)) { + ConfigPatchLoader.parse(inputStream).patchFile(configFile); + updateVersion(version + 1); + } + } else { + break; + } + } + } + + private void updateVersion(int newVersion) throws IOException { + try (BufferedReader reader = new BufferedReader(new FileReader(configFile))) { + List lines = reader.lines() + .map(line -> { + return line.startsWith("version: ") ? "version: " + newVersion : line; + }) + .collect(Collectors.toList()); + try (PrintWriter writer = new PrintWriter(new FileWriter(configFile))) { + for (String line : lines) { + writer.println(line); + } + } + } + } + +} diff --git a/src/main/java/com/froobworld/nabconfiguration/annotations/Entry.java b/src/main/java/com/froobworld/nabconfiguration/annotations/Entry.java new file mode 100644 index 0000000..ef2de25 --- /dev/null +++ b/src/main/java/com/froobworld/nabconfiguration/annotations/Entry.java @@ -0,0 +1,14 @@ +package com.froobworld.nabconfiguration.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(value = RetentionPolicy.RUNTIME) +@Target(value = ElementType.FIELD) +public @interface Entry { + + String key(); + +} diff --git a/src/main/java/com/froobworld/nabconfiguration/annotations/EntryMap.java b/src/main/java/com/froobworld/nabconfiguration/annotations/EntryMap.java new file mode 100644 index 0000000..013fc43 --- /dev/null +++ b/src/main/java/com/froobworld/nabconfiguration/annotations/EntryMap.java @@ -0,0 +1,16 @@ +package com.froobworld.nabconfiguration.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(value = RetentionPolicy.RUNTIME) +@Target(value = ElementType.FIELD) +public @interface EntryMap { + + String key(); + + String defaultKey(); + +} diff --git a/src/main/java/com/froobworld/nabconfiguration/annotations/Section.java b/src/main/java/com/froobworld/nabconfiguration/annotations/Section.java new file mode 100644 index 0000000..c78ef31 --- /dev/null +++ b/src/main/java/com/froobworld/nabconfiguration/annotations/Section.java @@ -0,0 +1,14 @@ +package com.froobworld.nabconfiguration.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(value = RetentionPolicy.RUNTIME) +@Target(value = ElementType.FIELD) +public @interface Section { + + String key(); + +} diff --git a/src/main/java/com/froobworld/nabconfiguration/annotations/SectionMap.java b/src/main/java/com/froobworld/nabconfiguration/annotations/SectionMap.java new file mode 100644 index 0000000..51afc89 --- /dev/null +++ b/src/main/java/com/froobworld/nabconfiguration/annotations/SectionMap.java @@ -0,0 +1,16 @@ +package com.froobworld.nabconfiguration.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(value = RetentionPolicy.RUNTIME) +@Target(value = ElementType.FIELD) +public @interface SectionMap { + + String key(); + + String defaultKey(); + +} diff --git a/src/main/java/com/froobworld/nabconfiguration/patcher/ConfigPatch.java b/src/main/java/com/froobworld/nabconfiguration/patcher/ConfigPatch.java new file mode 100644 index 0000000..d4a09f9 --- /dev/null +++ b/src/main/java/com/froobworld/nabconfiguration/patcher/ConfigPatch.java @@ -0,0 +1,30 @@ +package com.froobworld.nabconfiguration.patcher; + +import com.froobworld.nabconfiguration.patcher.jobs.PatchJob; +import com.froobworld.nabconfiguration.patcher.structure.YamlFile; +import com.froobworld.nabconfiguration.patcher.structure.parser.YamlFileParser; + +import java.io.*; +import java.util.List; + +public class ConfigPatch { + private List patchJobs; + + ConfigPatch(List patchJobs) { + this.patchJobs = patchJobs; + } + + public void patchFile(File file) throws IOException { + YamlFile yamlFile = YamlFileParser.parse(file); + for (PatchJob patchJob : patchJobs) { + patchJob.modify(yamlFile); + } + + try (PrintWriter writer = new PrintWriter(file)) { + for (String line : yamlFile.toLines()) { + writer.println(line); + } + } + } + +} diff --git a/src/main/java/com/froobworld/nabconfiguration/patcher/ConfigPatchLoader.java b/src/main/java/com/froobworld/nabconfiguration/patcher/ConfigPatchLoader.java new file mode 100644 index 0000000..3784de0 --- /dev/null +++ b/src/main/java/com/froobworld/nabconfiguration/patcher/ConfigPatchLoader.java @@ -0,0 +1,58 @@ +package com.froobworld.nabconfiguration.patcher; + +import com.froobworld.nabconfiguration.patcher.jobs.*; + +import java.io.*; +import java.util.*; +import java.util.function.Function; +import java.util.regex.Pattern; + +public class ConfigPatchLoader { + private static final Pattern PATCH_HEADER_PATTERN = Pattern.compile("\\[[a-z-]+\\]"); + + private static final Map> PATCH_JOBS = new HashMap<>(); + static { + PATCH_JOBS.put("add-field", AddFieldJob::new); + PATCH_JOBS.put("add-section", AddSectionJob::new); + PATCH_JOBS.put("comment", CommentJob::new); + PATCH_JOBS.put("comment-out", CommentOutJob::new); + PATCH_JOBS.put("header", HeaderJob::new); + PATCH_JOBS.put("move", MoveJob::new); + } + + public static ConfigPatch parse(InputStream inputStream) throws IOException { + List patchJobs = new ArrayList<>(); + + try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) { + Function currentJobFunction = null; + StringBuilder currentProperties = new StringBuilder(); + + for (Iterator it = reader.lines().iterator(); it.hasNext(); ) { + String line = it.next(); + if (PATCH_HEADER_PATTERN.matcher(line).matches()) { + if (currentJobFunction != null) { + Properties properties = new Properties(); + properties.load(new StringReader(currentProperties.toString())); + patchJobs.add(currentJobFunction.apply(properties)); + } + + currentJobFunction = PATCH_JOBS.get(getPatchJobType(line)); + currentProperties = new StringBuilder(); + } else { + currentProperties.append(line).append("\n"); + } + } + if (currentJobFunction != null) { + Properties properties = new Properties(); + properties.load(new StringReader(currentProperties.toString())); + patchJobs.add(currentJobFunction.apply(properties)); + } + } + return new ConfigPatch(patchJobs); + } + + private static String getPatchJobType(String line) { + return line.replace("[", "").replace("]", ""); + } + +} diff --git a/src/main/java/com/froobworld/nabconfiguration/patcher/jobs/AddFieldJob.java b/src/main/java/com/froobworld/nabconfiguration/patcher/jobs/AddFieldJob.java new file mode 100644 index 0000000..12b8195 --- /dev/null +++ b/src/main/java/com/froobworld/nabconfiguration/patcher/jobs/AddFieldJob.java @@ -0,0 +1,80 @@ +package com.froobworld.nabconfiguration.patcher.jobs; + +import com.froobworld.nabconfiguration.patcher.structure.YamlElement; +import com.froobworld.nabconfiguration.patcher.structure.YamlField; +import com.froobworld.nabconfiguration.patcher.structure.YamlFile; +import com.froobworld.nabconfiguration.patcher.structure.YamlSection; + +import java.util.*; +import java.util.regex.Pattern; + +public class AddFieldJob implements PatchJob { + private String key; + private String value; + private List comment; + private List body; + private String before; + + public AddFieldJob(Properties properties) { + this.key = properties.getProperty("key"); + String valueString = properties.getProperty("value"); + this.value = valueString == null ? "" : (" " + valueString); + String commentString = properties.getProperty("comment"); + this.comment = commentString == null ? Collections.emptyList() : Arrays.asList(commentString.split("\n")); + String bodyString = properties.getProperty("body"); + this.body = bodyString == null ? Collections.emptyList() : Arrays.asList(bodyString.split("\n")); + this.before = properties.getProperty("before"); + } + + @Override + public void modify(YamlFile yamlFile) { + String[] splitKey = key.split(Pattern.quote(".")); + List elementList = yamlFile.getElements(); + for (int i = 0; i < splitKey.length; i++) { + String currentKey = splitKey[i]; + Optional nextElement = elementList.stream() + .filter(element -> { + if (element instanceof YamlField) { + return ((YamlField) element).getKey().equals(currentKey); + } else if (element instanceof YamlSection) { + return ((YamlSection) element).getKey().equals(currentKey); + } + return false; + }) + .findFirst(); + if (i == splitKey.length - 1) { + if (nextElement.isPresent()) { + throw new IllegalArgumentException("Tried to add field with key " + key + ", but element already exists."); + } else { + YamlField field = new YamlField(currentKey, comment, value, body); + if (before == null) { + elementList.add(field); + } else { + int index = 0; + for (YamlElement element : elementList) { + if (element instanceof YamlField) { + if (((YamlField) element).getKey().equals(before)) { + break; + } + index++; + } else if (element instanceof YamlSection) { + if (((YamlSection) element).getKey().equals(before)) { + break; + } + index++; + } + } + elementList.add(index, field); + } + } + } else { + if (nextElement.isPresent() && nextElement.get() instanceof YamlSection) { + elementList = ((YamlSection) nextElement.get()).elements(); + } else { + throw new IllegalArgumentException("Tried to add field with key " + key + ", but a section named " + currentKey + " does not exist."); + } + } + } + } + +} diff --git a/src/main/java/com/froobworld/nabconfiguration/patcher/jobs/AddSectionJob.java b/src/main/java/com/froobworld/nabconfiguration/patcher/jobs/AddSectionJob.java new file mode 100644 index 0000000..4626389 --- /dev/null +++ b/src/main/java/com/froobworld/nabconfiguration/patcher/jobs/AddSectionJob.java @@ -0,0 +1,92 @@ +package com.froobworld.nabconfiguration.patcher.jobs; + +import com.froobworld.nabconfiguration.patcher.structure.YamlElement; +import com.froobworld.nabconfiguration.patcher.structure.YamlField; +import com.froobworld.nabconfiguration.patcher.structure.YamlFile; +import com.froobworld.nabconfiguration.patcher.structure.YamlSection; +import com.froobworld.nabconfiguration.utils.YamlUtils; + +import java.util.*; +import java.util.regex.Pattern; + +public class AddSectionJob implements PatchJob { + private String key; + private String value; + private List comment; + private String before; + + public AddSectionJob(Properties properties) { + this.key = properties.getProperty("key"); + String valueString = properties.getProperty("value"); + this.value = valueString == null ? "" : valueString; + String commentString = properties.getProperty("comment"); + this.comment = commentString == null ? Collections.emptyList() : Arrays.asList(commentString.split("\n")); + this.before = properties.getProperty("before"); + } + + + @Override + public void modify(YamlFile yamlFile) { + String keyFirstPart = key.replaceAll("\\.[^.]+(?!.+)", ""); + String keyLastPart = keyFirstPart.equals(key) ? null : key.replace(keyFirstPart, "").replace(".",""); + List matchedKeys = YamlUtils.getMatchingKeys(keyFirstPart, yamlFile); + if (keyLastPart == null) { + matchedKeys.add(new YamlUtils.WildcardString(keyFirstPart, new ArrayList<>())); + } + for (YamlUtils.WildcardString matchedKey : matchedKeys) { + String key = matchedKey.string + (keyLastPart == null ? "" : ("." + keyLastPart)); + String before = this.before; + for (int i = 0; i < matchedKey.wildcardMatches.size(); i++) { + before = before == null ? null : before.replace("{" + i + "}", matchedKey.wildcardMatches.get(i)); + } + String[] splitKey = key.split(Pattern.quote(".")); + List elementList = yamlFile.getElements(); + for (int i = 0; i < splitKey.length; i++) { + String currentKey = splitKey[i]; + Optional nextElement = elementList.stream() + .filter(element -> { + if (element instanceof YamlField) { + return ((YamlField) element).getKey().equals(currentKey); + } else if (element instanceof YamlSection) { + return ((YamlSection) element).getKey().equals(currentKey); + } + return false; + }) + .findFirst(); + if (i == splitKey.length - 1) { + if (nextElement.isPresent()) { + throw new IllegalArgumentException("Tried to add section with key " + key + ", but element already exists."); + } else { + YamlSection section = new YamlSection(currentKey, comment, value, new ArrayList<>()); + if (before == null) { + elementList.add(section); + } else { + int index = 0; + for (YamlElement element : elementList) { + if (element instanceof YamlField) { + if (((YamlField) element).getKey().equals(before)) { + break; + } + index++; + } else if (element instanceof YamlSection) { + if (((YamlSection) element).getKey().equals(before)) { + break; + } + index++; + } + } + elementList.add(index, section); + } + } + } else { + if (nextElement.isPresent() && nextElement.get() instanceof YamlSection) { + elementList = ((YamlSection) nextElement.get()).elements(); + } else { + throw new IllegalArgumentException("Tried to add section with key " + key + ", but a section named " + currentKey + " does not exist."); + } + } + } + } + } + +} diff --git a/src/main/java/com/froobworld/nabconfiguration/patcher/jobs/CommentJob.java b/src/main/java/com/froobworld/nabconfiguration/patcher/jobs/CommentJob.java new file mode 100644 index 0000000..536aad4 --- /dev/null +++ b/src/main/java/com/froobworld/nabconfiguration/patcher/jobs/CommentJob.java @@ -0,0 +1,57 @@ +package com.froobworld.nabconfiguration.patcher.jobs; + +import com.froobworld.nabconfiguration.patcher.structure.YamlElement; +import com.froobworld.nabconfiguration.patcher.structure.YamlField; +import com.froobworld.nabconfiguration.patcher.structure.YamlFile; +import com.froobworld.nabconfiguration.patcher.structure.YamlSection; + +import java.util.*; +import java.util.regex.Pattern; + +public class CommentJob implements PatchJob { + private String key; + private List comment; + + public CommentJob(Properties properties) { + this.key = properties.getProperty("key"); + String commentString = properties.getProperty("comment"); + this.comment = commentString == null ? Collections.emptyList() : Arrays.asList(commentString.split("\n")); + } + + + @Override + public void modify(YamlFile yamlFile) { + String[] splitKey = key.split(Pattern.quote(".")); + List elementList = yamlFile.getElements(); + for (int i = 0; i < splitKey.length; i++) { + String currentKey = splitKey[i]; + Optional nextElement = elementList.stream() + .filter(element -> { + if (element instanceof YamlField) { + return ((YamlField) element).getKey().equals(currentKey); + } else if (element instanceof YamlSection) { + return ((YamlSection) element).getKey().equals(currentKey); + } + return false; + }) + .findFirst(); + if (i == splitKey.length - 1) { + if (nextElement.isPresent()) { + if (nextElement.get() instanceof YamlField) { + ((YamlField) nextElement.get()).setComment(comment); + } else if (nextElement.get() instanceof YamlSection) { + ((YamlSection) nextElement.get()).setComment(comment); + } + } else { + throw new IllegalArgumentException("Tried to add comment to element with key " + key + ", but element does not exist."); + } + } else { + if (nextElement.isPresent() && nextElement.get() instanceof YamlSection) { + elementList = ((YamlSection) nextElement.get()).elements(); + } else { + throw new IllegalArgumentException("Tried to add comment to element with key " + key + ", but a section named " + currentKey + " does not exist."); + } + } + } + } +} diff --git a/src/main/java/com/froobworld/nabconfiguration/patcher/jobs/CommentOutJob.java b/src/main/java/com/froobworld/nabconfiguration/patcher/jobs/CommentOutJob.java new file mode 100644 index 0000000..7d8d1e0 --- /dev/null +++ b/src/main/java/com/froobworld/nabconfiguration/patcher/jobs/CommentOutJob.java @@ -0,0 +1,62 @@ +package com.froobworld.nabconfiguration.patcher.jobs; + +import com.froobworld.nabconfiguration.patcher.structure.YamlElement; +import com.froobworld.nabconfiguration.patcher.structure.YamlField; +import com.froobworld.nabconfiguration.patcher.structure.YamlFile; +import com.froobworld.nabconfiguration.patcher.structure.YamlSection; +import com.froobworld.nabconfiguration.utils.YamlUtils; + +import java.util.*; +import java.util.regex.Pattern; + +public class CommentOutJob implements PatchJob { + private String key; + + public CommentOutJob(Properties properties) { + this.key = properties.getProperty("key"); + } + + + @Override + public void modify(YamlFile yamlFile) { + String[] splitKey = key.split(Pattern.quote(".")); + List elementList = yamlFile.getElements(); + for (int i = 0; i < splitKey.length; i++) { + String currentKey = splitKey[i]; + Optional nextElement = elementList.stream() + .filter(element -> { + if (element instanceof YamlField) { + return ((YamlField) element).getKey().equals(currentKey); + } else if (element instanceof YamlSection) { + return ((YamlSection) element).getKey().equals(currentKey); + } + return false; + }) + .findFirst(); + if (i == splitKey.length - 1) { + if (nextElement.isPresent()) { + for (ListIterator iterator = elementList.listIterator(); iterator.hasNext();) { + YamlElement next = iterator.next(); + if (next instanceof YamlField) { + if (((YamlField) next).getKey().equals(currentKey)) { + iterator.set(YamlUtils.commentOut(next)); + } + } else if (next instanceof YamlSection) { + if (((YamlSection) next).getKey().equals(currentKey)) { + iterator.set(YamlUtils.commentOut(next)); + } + } + } + } else { + throw new IllegalArgumentException("Tried to add comment to element with key " + key + ", but element does not exist."); + } + } else { + if (nextElement.isPresent() && nextElement.get() instanceof YamlSection) { + elementList = ((YamlSection) nextElement.get()).elements(); + } else { + throw new IllegalArgumentException("Tried to add comment to element with key " + key + ", but a section named " + currentKey + " does not exist."); + } + } + } + } +} diff --git a/src/main/java/com/froobworld/nabconfiguration/patcher/jobs/HeaderJob.java b/src/main/java/com/froobworld/nabconfiguration/patcher/jobs/HeaderJob.java new file mode 100644 index 0000000..dba37dd --- /dev/null +++ b/src/main/java/com/froobworld/nabconfiguration/patcher/jobs/HeaderJob.java @@ -0,0 +1,21 @@ +package com.froobworld.nabconfiguration.patcher.jobs; + +import com.froobworld.nabconfiguration.patcher.structure.YamlFile; + +import java.util.Arrays; +import java.util.List; +import java.util.Properties; + +public class HeaderJob implements PatchJob { + private List header; + + public HeaderJob(Properties properties) { + this.header = Arrays.asList(properties.getProperty("header").split("\n")); + } + + + @Override + public void modify(YamlFile yamlFile) { + yamlFile.setHeader(header); + } +} diff --git a/src/main/java/com/froobworld/nabconfiguration/patcher/jobs/MoveJob.java b/src/main/java/com/froobworld/nabconfiguration/patcher/jobs/MoveJob.java new file mode 100644 index 0000000..f81c27e --- /dev/null +++ b/src/main/java/com/froobworld/nabconfiguration/patcher/jobs/MoveJob.java @@ -0,0 +1,116 @@ +package com.froobworld.nabconfiguration.patcher.jobs; + +import com.froobworld.nabconfiguration.patcher.structure.YamlElement; +import com.froobworld.nabconfiguration.patcher.structure.YamlField; +import com.froobworld.nabconfiguration.patcher.structure.YamlFile; +import com.froobworld.nabconfiguration.patcher.structure.YamlSection; +import com.froobworld.nabconfiguration.utils.YamlUtils; + +import java.util.*; +import java.util.regex.Pattern; + +public class MoveJob implements PatchJob { + private String fromKey; + private String toKey; + private String before; + + public MoveJob(Properties properties) { + fromKey = properties.getProperty("from"); + toKey = properties.getProperty("to"); + before = properties.getProperty("before"); + } + + + @Override + public void modify(YamlFile yamlFile) { + for (YamlUtils.WildcardString matchedKey : YamlUtils.getMatchingKeys(fromKey, yamlFile)) { + String[] fromKeySplit = matchedKey.string.split(Pattern.quote(".")); + + String toKey = this.toKey; + String before = this.before; + for (int i = 0; i < matchedKey.wildcardMatches.size(); i++) { + toKey = toKey.replace("{" + i + "}", matchedKey.wildcardMatches.get(i)); + before = before == null ? null : before.replace("{" + i + "}", matchedKey.wildcardMatches.get(i)); + } + String[] toKeySplit = toKey.split(Pattern.quote(".")); + + String finalFromKey = fromKeySplit[fromKeySplit.length - 1]; + String finalToKey = toKeySplit[toKeySplit.length - 1]; + List fromDestination = yamlFile.getElements(); + List toDestination = yamlFile.getElements(); + for (int i = 0; i < fromKeySplit.length - 1; i++) { + String nextKey = fromKeySplit[i]; + boolean found = false; + for (YamlElement element : fromDestination) { + if (element instanceof YamlSection) { + if (((YamlSection) element).getKey().equals(nextKey)) { + fromDestination = ((YamlSection) element).elements(); + found = true; + break; + } + } + } + if (!found) { + throw new IllegalStateException(); + } + } + for (int i = 0; i < toKeySplit.length - 1; i++) { + String nextKey = toKeySplit[i]; + boolean found = false; + for (YamlElement element : toDestination) { + if (element instanceof YamlSection) { + if (((YamlSection) element).getKey().equals(nextKey)) { + toDestination = ((YamlSection) element).elements(); + found = true; + break; + } + } + } + if (!found) { + YamlSection newSection = new YamlSection(nextKey, new ArrayList<>(), "", new ArrayList<>()); + toDestination.add(newSection); + toDestination = newSection.elements(); + } + } + YamlElement toMove = null; + for (ListIterator iterator = fromDestination.listIterator(); iterator.hasNext(); ) { + YamlElement next = iterator.next(); + if (next instanceof YamlField) { + if (((YamlField) next).getKey().equals(finalFromKey)) { + toMove = next; + iterator.remove(); + } + } else if (next instanceof YamlSection) { + if (((YamlSection) next).getKey().equals(finalFromKey)) { + toMove = next; + iterator.remove(); + } + } + } + + if (toMove instanceof YamlField) { + ((YamlField) toMove).setKey(finalToKey); + } else if (toMove instanceof YamlSection) { + ((YamlSection) toMove).setKey(finalToKey); + } + if (before == null) { + toDestination.add(toMove); + } else { + int index = 0; + for (YamlElement element : toDestination) { + if (element instanceof YamlField) { + if (((YamlField) element).getKey().equals(before)) { + break; + } + } else if (element instanceof YamlSection) { + if (((YamlSection) element).getKey().equals(before)) { + break; + } + } + index++; + } + toDestination.add(index, toMove); + } + } + } +} diff --git a/src/main/java/com/froobworld/nabconfiguration/patcher/jobs/PatchJob.java b/src/main/java/com/froobworld/nabconfiguration/patcher/jobs/PatchJob.java new file mode 100644 index 0000000..d9ee8ff --- /dev/null +++ b/src/main/java/com/froobworld/nabconfiguration/patcher/jobs/PatchJob.java @@ -0,0 +1,9 @@ +package com.froobworld.nabconfiguration.patcher.jobs; + +import com.froobworld.nabconfiguration.patcher.structure.YamlFile; + +public interface PatchJob { + + void modify(YamlFile yamlFile); + +} diff --git a/src/main/java/com/froobworld/nabconfiguration/patcher/structure/YamlElement.java b/src/main/java/com/froobworld/nabconfiguration/patcher/structure/YamlElement.java new file mode 100644 index 0000000..75d6abf --- /dev/null +++ b/src/main/java/com/froobworld/nabconfiguration/patcher/structure/YamlElement.java @@ -0,0 +1,9 @@ +package com.froobworld.nabconfiguration.patcher.structure; + +import java.util.List; + +public interface YamlElement { + + List toLines(); + +} diff --git a/src/main/java/com/froobworld/nabconfiguration/patcher/structure/YamlField.java b/src/main/java/com/froobworld/nabconfiguration/patcher/structure/YamlField.java new file mode 100644 index 0000000..cdcafe1 --- /dev/null +++ b/src/main/java/com/froobworld/nabconfiguration/patcher/structure/YamlField.java @@ -0,0 +1,40 @@ +package com.froobworld.nabconfiguration.patcher.structure; + +import java.util.ArrayList; +import java.util.List; + +public class YamlField implements YamlElement { + protected List comment; + protected String key; + protected String value; + protected List body; + + public YamlField(String key, List comment, String value, List body) { + this.comment = comment; + this.key = key; + this.value = value; + this.body = body; + } + + + public String getKey() { + return key; + } + + public void setKey(String key) { + this.key = key; + } + + public void setComment(List comment) { + this.comment = comment; + } + + @Override + public List toLines() { + List lines = new ArrayList<>(comment); + lines.add(key + ":" + value); + lines.addAll(body); + return lines; + } + +} diff --git a/src/main/java/com/froobworld/nabconfiguration/patcher/structure/YamlFile.java b/src/main/java/com/froobworld/nabconfiguration/patcher/structure/YamlFile.java new file mode 100644 index 0000000..af1be69 --- /dev/null +++ b/src/main/java/com/froobworld/nabconfiguration/patcher/structure/YamlFile.java @@ -0,0 +1,45 @@ +package com.froobworld.nabconfiguration.patcher.structure; + +import com.froobworld.nabconfiguration.utils.YamlUtils; + +import java.util.ArrayList; +import java.util.List; + +public class YamlFile { + private List header; + private List elements; + + public YamlFile(List elements) { + this.elements = elements; + if (!elements.isEmpty()) { + YamlElement firstElement = elements.get(0); + if (firstElement instanceof YamlGibberish) { + header = firstElement.toLines(); + elements.remove(0); + } + } + if (header == null) { + header = new ArrayList<>(); + } + } + + + public void setHeader(List header) { + this.header = new ArrayList<>(header); + } + + public List toLines() { + List lines = new ArrayList<>(); + if (!header.isEmpty()) { + lines.addAll(header); + lines.add(""); + } + lines.addAll(YamlUtils.elementsToBody(elements, 0)); + return lines; + } + + public List getElements() { + return elements; + } + +} diff --git a/src/main/java/com/froobworld/nabconfiguration/patcher/structure/YamlGibberish.java b/src/main/java/com/froobworld/nabconfiguration/patcher/structure/YamlGibberish.java new file mode 100644 index 0000000..27809e3 --- /dev/null +++ b/src/main/java/com/froobworld/nabconfiguration/patcher/structure/YamlGibberish.java @@ -0,0 +1,19 @@ +package com.froobworld.nabconfiguration.patcher.structure; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class YamlGibberish implements YamlElement { + private List lines; + + public YamlGibberish(List lines) { + this.lines = lines; + } + + @Override + public List toLines() { + return new ArrayList<>(lines); + } + +} diff --git a/src/main/java/com/froobworld/nabconfiguration/patcher/structure/YamlSection.java b/src/main/java/com/froobworld/nabconfiguration/patcher/structure/YamlSection.java new file mode 100644 index 0000000..2a0acca --- /dev/null +++ b/src/main/java/com/froobworld/nabconfiguration/patcher/structure/YamlSection.java @@ -0,0 +1,47 @@ +package com.froobworld.nabconfiguration.patcher.structure; + +import com.froobworld.nabconfiguration.utils.YamlUtils; + +import java.util.ArrayList; +import java.util.List; +import java.util.ListIterator; + +public class YamlSection implements YamlElement { + protected List comment; + protected String key; + protected String value; + protected List elements; + + public YamlSection(String key, List comment, String value, List elements) { + this.key = key; + this.comment = comment; + this.value = value; + this.elements = elements; + } + + + public String getKey() { + return key; + } + + public void setKey(String key) { + this.key = key; + } + + public void setComment(List comment) { + this.comment = comment; + } + + public List elements() { + return elements; + } + + @Override + public List toLines() { + List lines = new ArrayList<>(comment); + lines.add(key + ":" + value); + lines.addAll(YamlUtils.elementsToBody(elements, 2)); + return lines; + } + +} diff --git a/src/main/java/com/froobworld/nabconfiguration/patcher/structure/parser/YamlFileParser.java b/src/main/java/com/froobworld/nabconfiguration/patcher/structure/parser/YamlFileParser.java new file mode 100644 index 0000000..4d1d3a7 --- /dev/null +++ b/src/main/java/com/froobworld/nabconfiguration/patcher/structure/parser/YamlFileParser.java @@ -0,0 +1,204 @@ +package com.froobworld.nabconfiguration.patcher.structure.parser; + +import com.froobworld.nabconfiguration.patcher.structure.*; +import org.yaml.snakeyaml.Yaml; + +import java.io.*; +import java.util.*; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +// TODO: Make this less terrible +public class YamlFileParser { + private static final Yaml YAML = new Yaml(); + private static final String COMMENT_REGEX = "(#[^\r\n|\r|\n]{0,200}(\r\n|\r|\n))"; + private static final String KEY_REGEX = "((?<=\\r\\n|\\r|\\n)[a-zA-Z0-9-_][a-zA-Z0-9-_ ]*:)"; + private static final Pattern YAML_ENTRY_SEPARATOR_PATTERN = Pattern.compile( + "(?=" + // Want to match empty space before the following pattern + "(? parse(String input) throws IOException { + Map yamlMap = YAML.load(input); + if (yamlMap == null) { + return new ArrayList<>(); + } + Set sectionKeys = yamlMap.entrySet().stream() + .filter(entry -> entry.getValue() == null || entry.getValue() instanceof Map) + .map(Map.Entry::getKey) + .collect(Collectors.toSet()); + + List elementList = new ArrayList<>(); + for (String entry : YAML_ENTRY_SEPARATOR_PATTERN.split(input)) { + ElementGibberishPairBuilder builder = new ElementGibberishPairBuilder(); + for (String line : entry.split("\n", -1)) { + if (line.trim().isEmpty()) { + builder.empty(); + } else if (line.matches(KEY_LINE_REGEX)) { + String[] keyValueArray = line.split(":", 2); + builder.key(keyValueArray[0], keyValueArray[1], sectionKeys.contains(keyValueArray[0])); + } else if (line.matches(" *" + COMMENT_LINE_REGEX)) { + builder.comment(line); + } else { + builder.other(line); + } + } + ElementGibberishPair pair = builder.build(); + if (pair.element != null) { + elementList.add(pair.element); + } + if (pair.gibberish != null) { + elementList.add(pair.gibberish); + } + } + + return elementList; + } + + private static class ElementGibberishPairBuilder { + private boolean section; // Is it a section? + private Integer sectionIndentation; // How much is the section indented by? + private List comment; // The comment appearing above the key + private String key; // The key + private String value; // The stuff appearing after the : of the key + private List body; // The stuff appearing beneath the key, excluding comments + private List tail; // Everything following the body, gibberish + + public ElementGibberishPairBuilder() { + this.comment = new ArrayList<>(); + this.body = new ArrayList<>(); + this.tail = new ArrayList<>(); + } + + public ElementGibberishPairBuilder key(String key, String value, boolean section) { + this.key = key; + this.value = value; + this.section = section; + return this; + } + + public ElementGibberishPairBuilder comment(String line) { + if (key == null) { + comment.add(line); + } else { + tail.add(line); + } + return this; + } + + public ElementGibberishPairBuilder other(String line) { + if (key == null) { + throw new IllegalArgumentException("Can't accept non-comment value before key has been supplied."); + } else { + body.addAll(tail); + body.add(line); + tail.clear(); + if (section && sectionIndentation == null) { + sectionIndentation = 0; + for (char c : line.toCharArray()) { + if (c == ' ') { + sectionIndentation++; + } else { + break; + } + } + } + } + return this; + } + + public ElementGibberishPairBuilder empty() { + if (key == null) { + comment.add(""); + } else { + tail.add(""); + } + return this; + } + + public ElementGibberishPair build() throws IOException { + // Remove leading empty strings + for (ListIterator iterator = tail.listIterator(); iterator.hasNext();) { + if (iterator.next().isEmpty()) { + iterator.remove(); + } else { + break; + } + } + for (ListIterator iterator = comment.listIterator(); iterator.hasNext();) { + if (iterator.next().isEmpty()) { + iterator.remove(); + } else { + break; + } + } + // Remove tailing empty strings + for (ListIterator iterator = tail.listIterator(tail.size()); iterator.hasPrevious();) { + if (iterator.previous().isEmpty()) { + iterator.remove(); + } else { + break; + } + } + for (ListIterator iterator = comment.listIterator(comment.size()); iterator.hasPrevious();) { + if (iterator.previous().isEmpty()) { + iterator.remove(); + } else { + break; + } + } + + YamlElement element = null; + YamlGibberish gibberish = key == null ? + (comment.isEmpty() ? null : new YamlGibberish(comment)) : + (tail.isEmpty() ? null : new YamlGibberish(tail)); + if (key != null) { + if (section) { + String sectionInput = body.stream() + .map(line -> line.replaceFirst(" {0," + sectionIndentation + "}", "")) + .collect(Collectors.joining("\n")); + + List sectionElements = parse(sectionInput); + if (sectionElements.isEmpty()) { + body.addAll(tail); + gibberish = null; + element = new YamlField(key, comment, value, body); + } else { + element = new YamlSection(key, comment, value, parse(sectionInput)); + } + } else { + body.addAll(tail); + gibberish = null; + element = new YamlField(key, comment, value, body); + } + } + + return new ElementGibberishPair(element, gibberish); + } + + } + + private static class ElementGibberishPair { + public final YamlElement element; + public final YamlGibberish gibberish; + + private ElementGibberishPair(YamlElement element, YamlGibberish gibberish) { + this.element = element; + this.gibberish = gibberish; + } + + } + +} diff --git a/src/main/java/com/froobworld/nabconfiguration/utils/InstantFallbackConfigurationSection.java b/src/main/java/com/froobworld/nabconfiguration/utils/InstantFallbackConfigurationSection.java new file mode 100644 index 0000000..9666cb2 --- /dev/null +++ b/src/main/java/com/froobworld/nabconfiguration/utils/InstantFallbackConfigurationSection.java @@ -0,0 +1,51 @@ +package com.froobworld.nabconfiguration.utils; + +import com.google.common.collect.Sets; +import org.bukkit.configuration.ConfigurationSection; + +import java.util.Collections; +import java.util.Set; + +public class InstantFallbackConfigurationSection { + private final ConfigurationSection baseSection; + private InstantFallbackConfigurationSection fallbackSection; + + public InstantFallbackConfigurationSection(ConfigurationSection baseSection) { + this(baseSection, null); + } + + private InstantFallbackConfigurationSection(ConfigurationSection baseSection, InstantFallbackConfigurationSection fallbackSection) { + this.baseSection = baseSection; + this.fallbackSection = fallbackSection; + } + + + public Object get(String key) { + return baseSection.get(key, fallbackSection == null ? null : fallbackSection.get(key)); + } + + public Set getKeys(boolean deep) { + return Sets.union(baseSection.getKeys(deep), fallbackSection == null ? Collections.emptySet() : fallbackSection.getKeys(deep)); + } + + public InstantFallbackConfigurationSection getSection(String key, String defaultKey) { + ConfigurationSection newBaseSection = baseSection.getConfigurationSection(key); + ConfigurationSection newFirstFallbackSection = defaultKey == null ? null : baseSection.getConfigurationSection(defaultKey); + InstantFallbackConfigurationSection fallbackSectionTail = fallbackSection == null ? null : fallbackSection.getSection(key, defaultKey); + if (newBaseSection == null && newFirstFallbackSection == null) { + return fallbackSection.getSection(key, defaultKey); + } + if (newBaseSection == null) { + return new InstantFallbackConfigurationSection(newFirstFallbackSection, fallbackSectionTail); + } + if (newFirstFallbackSection == null) { + return new InstantFallbackConfigurationSection(newBaseSection, fallbackSectionTail); + } + return new InstantFallbackConfigurationSection(newBaseSection, new InstantFallbackConfigurationSection(newFirstFallbackSection, fallbackSectionTail)); + } + + public ConfigurationSection getBaseSection() { + return baseSection; + } + +} diff --git a/src/main/java/com/froobworld/nabconfiguration/utils/YamlUtils.java b/src/main/java/com/froobworld/nabconfiguration/utils/YamlUtils.java new file mode 100644 index 0000000..393320f --- /dev/null +++ b/src/main/java/com/froobworld/nabconfiguration/utils/YamlUtils.java @@ -0,0 +1,94 @@ +package com.froobworld.nabconfiguration.utils; + +import com.froobworld.nabconfiguration.patcher.structure.*; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +public final class YamlUtils { + + private YamlUtils() {} + + public static boolean isComment(String line) { + return line.trim().startsWith("#"); + } + + public static List elementsToBody(List elements, int indentLevel) { + List lines = new ArrayList<>(); + for (Iterator iterator = elements.iterator(); iterator.hasNext();) { + YamlElement element = iterator.next(); + lines.addAll(element.toLines()); + if (iterator.hasNext()) { + lines.add(""); + } + } + + return lines.stream() + .map(string -> (string.isEmpty() ? "" : String.join("", Collections.nCopies(indentLevel, " "))) + string) + .collect(Collectors.toList()); + } + + public static YamlGibberish commentOut(YamlElement element) { + List lines = element.toLines(); + return new YamlGibberish( + lines.stream() + .map(line -> isComment(line) ? line : ("#" + line)) + .collect(Collectors.toList()) + ); + } + + public static List getMatchingKeys(String keyPattern, YamlFile yamlFile) { + List keys = new ArrayList<>(); + for (String key : getAllKeys(yamlFile.getElements())) { + String[] keySplit = key.split(Pattern.quote(".")); + String[] keyPatternSplit = keyPattern.split(Pattern.quote(".")); + if (keySplit.length == keyPatternSplit.length) { + List wildcardMatches = new ArrayList<>(); + for (int i = 0; i < keySplit.length; i++) { + if (keyPatternSplit[i].equalsIgnoreCase("*")) { + wildcardMatches.add(keySplit[i]); + } else { + if (!keySplit[i].equals(keyPatternSplit[i])) { + break; + } + } + if (i == keySplit.length - 1) { + keys.add(new WildcardString(key, wildcardMatches)); + } + } + } + } + return keys; + } + + private static List getAllKeys(List elements) { + List keys = new ArrayList<>(); + for (YamlElement element : elements) { + if (element instanceof YamlSection) { + keys.add(((YamlSection) element).getKey()); + keys.addAll(getAllKeys(((YamlSection) element).elements()).stream() + .map(key -> ((YamlSection) element).getKey() + "." + key) + .collect(Collectors.toSet())); + } + if (element instanceof YamlField) { + keys.add(((YamlField) element).getKey()); + } + } + return keys; + } + + public static class WildcardString { + public final String string; + public final List wildcardMatches; + + public WildcardString(String string, List wildcardMatches) { + this.string = string; + this.wildcardMatches = wildcardMatches; + } + } + +} diff --git a/src/main/java/com/froobworld/viewdistancetweaks/util/NmsUtils.java b/src/main/java/com/froobworld/viewdistancetweaks/util/NmsUtils.java index 3fe4ad6..5df0968 100644 --- a/src/main/java/com/froobworld/viewdistancetweaks/util/NmsUtils.java +++ b/src/main/java/com/froobworld/viewdistancetweaks/util/NmsUtils.java @@ -28,17 +28,29 @@ public static String getVersion() { public static int getMajorVersion() { String[] split = VERSION.replace("v", "").replace("R", "").split(Pattern.quote("_")); - return Integer.parseInt(split[0]); + try { + return Integer.parseInt(split[0]); + } catch(NumberFormatException e) { + return 1; + } } public static int getMinorVersion() { String[] split = VERSION.replace("v", "").replace("R", "").split(Pattern.quote("_")); - return split.length > 1 ? Integer.parseInt(split[1]) : 0; + try { + return split.length > 1 ? Integer.parseInt(split[1]) : 0; + } catch(NumberFormatException e) { + return 20; + } } public static int getRevisionNumber() { String[] split = VERSION.replace("v", "").replace("R", "").split(Pattern.quote("_")); - return split.length > 2 ? Integer.parseInt(split[2]) : 0; + try { + return split.length > 2 ? Integer.parseInt(split[2]) : 0; + } catch(NumberFormatException e) { + return 0; + } } } diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index c289109..4a150cc 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -2,7 +2,7 @@ name: ViewDistanceTweaks version: ${version} main: com.froobworld.viewdistancetweaks.ViewDistanceTweaks api-version: 1.14 -authors: [froobynooby] +authors: [froobynooby,djpiper28] description: A plugin that allows for dynamic view distances. softdepend: [PlaceholderAPI] commands: