diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1656c12 --- /dev/null +++ b/.gitignore @@ -0,0 +1,118 @@ +# User-specific stuff +.idea/ + +*.iml +*.ipr +*.iws + +# IntelliJ +out/ +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +*~ + +# temporary files which can be created if a process still has a handle open of a deleted file +.fuse_hidden* + +# KDE directory preferences +.directory + +# Linux trash folder which might appear on any partition or disk +.Trash-* + +# .nfs files are created when an open file is removed but is still being accessed +.nfs* + +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +# Windows thumbnail cache files +Thumbs.db +Thumbs.db:encryptable +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk + +.gradle +build/ + +# Ignore Gradle GUI config +gradle-app.setting + +# Cache of project +.gradletasknamecache + +**/build/ + +# Common working directory +run/ + +# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) +!gradle-wrapper.jar \ No newline at end of file diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..7a926a8 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "MockSkript"] + path = MockSkript + url = https://github.com/SkEditorPlus/MockSkript diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..0a04128 --- /dev/null +++ b/LICENSE @@ -0,0 +1,165 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser General Public License from time to time. Such new +versions will be similar in spirit to the present version, but may +differ in detail to address new problems or concerns. + + Each version is given a distinguishing version number. If the +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. diff --git a/MockSkript b/MockSkript new file mode 160000 index 0000000..95dfd95 --- /dev/null +++ b/MockSkript @@ -0,0 +1 @@ +Subproject commit 95dfd95b987fe4a08b81b3501b7d953163892edc diff --git a/MockSkriptBridge/build.gradle.kts b/MockSkriptBridge/build.gradle.kts new file mode 100644 index 0000000..3bbe04d --- /dev/null +++ b/MockSkriptBridge/build.gradle.kts @@ -0,0 +1,34 @@ +plugins { + id("java") + id("net.minecrell.plugin-yml.bukkit") version "0.6.0" +} + +repositories { + mavenCentral() + maven("https://repo.papermc.io/repository/maven-public/") +} + +dependencies { + compileOnly(rootProject) + compileOnly(project(":MockSkript")) { + exclude("*", "*") + } +} + +java { + toolchain.languageVersion.set(JavaLanguageVersion.of(17)) +} + +tasks { + compileJava { + options.encoding = Charsets.UTF_8.name() + options.release.set(17) + dependsOn(clean) + } + + jar.get().archiveVersion = "" +} + +bukkit { + main = "me.glicz.skanalyzer.bridge.MockSkriptBridgeImpl" +} \ No newline at end of file diff --git a/MockSkriptBridge/src/main/java/me/glicz/skanalyzer/bridge/AnalyzerCommandSender.java b/MockSkriptBridge/src/main/java/me/glicz/skanalyzer/bridge/AnalyzerCommandSender.java new file mode 100644 index 0000000..ca3a249 --- /dev/null +++ b/MockSkriptBridge/src/main/java/me/glicz/skanalyzer/bridge/AnalyzerCommandSender.java @@ -0,0 +1,59 @@ +package me.glicz.skanalyzer.bridge; + +import com.google.gson.Gson; +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import me.glicz.skanalyzer.structure.StructureType; +import me.glicz.skanalyzer.structure.data.StructureData; +import org.bukkit.command.MessageCommandSender; +import org.jetbrains.annotations.NotNull; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +public class AnalyzerCommandSender implements MessageCommandSender { + private final List messages = new ArrayList<>(); + private final Gson gson = new Gson(); + + @Override + public void sendMessage(@NotNull String message) { + messages.add(message); + } + + public void finish(Map>> structures) { + JsonObject jsonObject = new JsonObject(); + + messages.forEach(message -> gson.fromJson(message, JsonObject.class).asMap().forEach((key, value) -> { + JsonObject keyObject = getKeyObject(jsonObject, key); + + JsonArray errors = keyObject.getAsJsonArray("errors"); + if (errors == null) { + errors = new JsonArray(); + keyObject.add("errors", errors); + } + errors.add(value); + })); + + structures.forEach((key, value) -> { + JsonObject keyObject = getKeyObject(jsonObject, key); + + value.forEach((structureType, structureValues) -> { + JsonArray structuresArray = new JsonArray(); + structureValues.forEach(structureData -> structuresArray.add(gson.toJsonTree(structureData))); + keyObject.add(structureType.name().toLowerCase() + "s", structuresArray); + }); + }); + + System.out.println(jsonObject); + } + + private JsonObject getKeyObject(JsonObject jsonObject, String key) { + JsonObject keyObject = jsonObject.getAsJsonObject(key); + if (keyObject == null) { + keyObject = new JsonObject(); + jsonObject.add(key, keyObject); + } + return keyObject; + } +} diff --git a/MockSkriptBridge/src/main/java/me/glicz/skanalyzer/bridge/MockSkriptBridgeImpl.java b/MockSkriptBridge/src/main/java/me/glicz/skanalyzer/bridge/MockSkriptBridgeImpl.java new file mode 100644 index 0000000..5b6dd20 --- /dev/null +++ b/MockSkriptBridge/src/main/java/me/glicz/skanalyzer/bridge/MockSkriptBridgeImpl.java @@ -0,0 +1,190 @@ +package me.glicz.skanalyzer.bridge; + +import ch.njol.skript.ScriptLoader; +import ch.njol.skript.Skript; +import ch.njol.skript.command.ScriptCommand; +import ch.njol.skript.hooks.VaultHook; +import ch.njol.skript.hooks.regions.RegionsPlugin; +import ch.njol.skript.lang.SkriptEvent; +import ch.njol.skript.lang.SkriptEventInfo; +import ch.njol.skript.lang.function.Signature; +import ch.njol.skript.log.RedirectingLogHandler; +import ch.njol.skript.structures.StructCommand; +import ch.njol.skript.structures.StructFunction; +import me.glicz.skanalyzer.structure.StructureType; +import me.glicz.skanalyzer.structure.data.EventData; +import me.glicz.skanalyzer.structure.data.StructureData; +import org.bukkit.Bukkit; +import org.skriptlang.skript.lang.script.Script; + +import java.io.File; +import java.io.IOException; +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class MockSkriptBridgeImpl extends MockSkriptBridge { + private static final Field scriptCommandField, exprField, skriptEventInfoField, structureField; + + static { + Field tempScriptCommandField = null; + try { + tempScriptCommandField = StructCommand.class.getDeclaredField("scriptCommand"); + tempScriptCommandField.setAccessible(true); + } catch (Exception e) { + e.printStackTrace(System.out); + } + scriptCommandField = tempScriptCommandField; + + Field tempExprField = null; + try { + tempExprField = SkriptEvent.class.getDeclaredField("expr"); + tempExprField.setAccessible(true); + } catch (Exception e) { + e.printStackTrace(System.out); + } + exprField = tempExprField; + + Field tempSkriptEventInfo = null; + try { + tempSkriptEventInfo = SkriptEvent.class.getDeclaredField("skriptEventInfo"); + tempSkriptEventInfo.setAccessible(true); + } catch (Exception e) { + e.printStackTrace(System.out); + } + skriptEventInfoField = tempSkriptEventInfo; + + Field tempStructureField = null; + try { + tempStructureField = StructFunction.class.getDeclaredField("signature"); + tempStructureField.setAccessible(true); + } catch (Exception e) { + e.printStackTrace(System.out); + } + structureField = tempStructureField; + } + + public MockSkriptBridgeImpl() { + if (!Bukkit.getName().equals("SkAnalyzer")) + throw new RuntimeException("MockSkriptBridge only supports SkAnalyzer."); + } + + @Override + public void parseArgs(List args) { + if (args.contains("--forceVaultHook")) { + try { + String basePackage = VaultHook.class.getPackage().getName(); + Skript.getAddonInstance().loadClasses(basePackage + ".economy"); + Skript.getAddonInstance().loadClasses(basePackage + ".chat"); + Skript.getAddonInstance().loadClasses(basePackage + ".permission"); + System.out.println("Force loaded Vault hook."); + } catch (IOException e) { + System.out.println("Something went wrong while trying to force load Vault hook"); + e.printStackTrace(System.out); + } + } + if (args.contains("--forceRegionsHook")) { + try { + String basePackage = RegionsPlugin.class.getPackage().getName(); + Skript.getAddonInstance().loadClasses(basePackage); + System.out.println("Force loaded Regions hook."); + } catch (IOException e) { + System.out.println("Something went wrong while trying to force load Regions hook"); + e.printStackTrace(System.out); + } + } + } + + @Override + public void parseScript(String path) { + File file = new File(path); + if (!file.exists()) + return; + AnalyzerCommandSender sender = new AnalyzerCommandSender(); + RedirectingLogHandler logHandler = new RedirectingLogHandler(sender, null).start(); + ScriptLoader.loadScripts(file, logHandler, false).thenRun(() -> { + Map> structures = new HashMap<>(); + Script script = ScriptLoader.getScript(file); + if (script != null) { + script.getStructures().forEach(structure -> { + if (structure instanceof StructCommand command) { + ScriptCommand scriptCommand = getScriptCommand(command); + if (scriptCommand == null) return; + structures.putIfAbsent(StructureType.COMMAND, new ArrayList<>()); + structures.get(StructureType.COMMAND).add(new StructureData( + command.getEntryContainer().getSource().getLine(), + scriptCommand.getName() + )); + } else if (structure instanceof SkriptEvent event) { + SkriptEventInfo eventInfo = getEventInfo(event); + if (eventInfo == null) return; + structures.putIfAbsent(StructureType.EVENT, new ArrayList<>()); + structures.get(StructureType.EVENT).add(new EventData( + event.getEntryContainer().getSource().getLine(), + getEventExpression(event), + eventInfo.getId(), + event.getEventPriority() + )); + } else if (structure instanceof StructFunction function) { + Signature signature = getFunctionSignature(function); + if (signature == null) return; + structures.putIfAbsent(StructureType.FUNCTION, new ArrayList<>()); + structures.get(StructureType.FUNCTION).add(new StructureData( + function.getEntryContainer().getSource().getLine(), + signature.getName() + )); + } + }); + ScriptLoader.unloadScript(script); + } + sender.finish(Map.of(getCanonicalPath(file).replace('\\', '/'), structures)); + logHandler.close(); + }); + } + + private String getCanonicalPath(File file) { + try { + return file.getCanonicalPath(); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + private ScriptCommand getScriptCommand(StructCommand command) { + try { + return (ScriptCommand) scriptCommandField.get(command); + } catch (Throwable e) { + e.printStackTrace(System.out); + return null; + } + } + + private String getEventExpression(SkriptEvent event) { + try { + return (String) exprField.get(event); + } catch (Throwable e) { + e.printStackTrace(System.out); + return null; + } + } + + private SkriptEventInfo getEventInfo(SkriptEvent event) { + try { + return (SkriptEventInfo) skriptEventInfoField.get(event); + } catch (Throwable e) { + e.printStackTrace(System.out); + return null; + } + } + + private Signature getFunctionSignature(StructFunction function) { + try { + return (Signature) structureField.get(function); + } catch (Throwable e) { + e.printStackTrace(System.out); + return null; + } + } +} diff --git a/README.md b/README.md new file mode 100644 index 0000000..a8c5fa7 --- /dev/null +++ b/README.md @@ -0,0 +1,18 @@ +# SkAnalyzer +SkAnalyzer is a simple Skript parser + +## Usage +> [!NOTE] +> If you want to use SkAnalyzer in your project, please copyright us + +Simply run SkAnalyzer in command prompt and provide paths to your scripts + +## Compiling +After cloning this repository, open command prompt inside it and run +``` +git submodule init +``` +and after that +``` +./gradlew shadowJar +``` diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..4934ab0 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,50 @@ +plugins { + id("java") + id("java-library") + id("com.github.johnrengelman.shadow") version "8.1.1" +} + +repositories { + mavenCentral() + maven("https://repo.papermc.io/repository/maven-public/") +} + +dependencies { + compileOnly(project(":MockSkript")) { + exclude("*", "*") + } + api("com.github.seeseemelk:MockBukkit-v1.20:3.9.0") + implementation("org.apache.logging.log4j:log4j-core:3.0.0-alpha1") + implementation("commons-io:commons-io:2.14.0") + implementation("commons-lang:commons-lang:2.6") + implementation("org.slf4j:slf4j-simple:2.0.9") +} + +java { + toolchain.languageVersion.set(JavaLanguageVersion.of(17)) +} + +tasks { + compileJava { + options.encoding = Charsets.UTF_8.name() + options.release.set(17) + dependsOn(clean) + } + + shadowJar { + manifest.attributes["Main-Class"] = "me.glicz.skanalyzer.SkAnalyzer" + manifest.attributes["Specification-Version"] = version + + dependsOn(project(":MockSkriptBridge").tasks.jar) + + subprojects.forEach { subproject -> + from(subproject.tasks.jar.get().outputs.files.singleFile) { + include("*.jar") + rename { "${subproject.name}.jar.embedded" } + } + } + + archiveVersion = "" + archiveClassifier = null + } +} \ No newline at end of file diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..826e458 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,3 @@ +version=1.0 +group=me.glicz +org.gradle.caching=true \ 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..174e70d --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Mon Oct 23 16:58:05 CEST 2023 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.2-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..107acd3 --- /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/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..d642597 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,6 @@ +rootProject.name = "SkAnalyzer" + +include( + "MockSkript", + "MockSkriptBridge" +) diff --git a/src/main/java/me/glicz/skanalyzer/SkAnalyzer.java b/src/main/java/me/glicz/skanalyzer/SkAnalyzer.java new file mode 100644 index 0000000..a39af86 --- /dev/null +++ b/src/main/java/me/glicz/skanalyzer/SkAnalyzer.java @@ -0,0 +1,87 @@ +package me.glicz.skanalyzer; + +import be.seeseemelk.mockbukkit.MockBukkit; +import com.google.common.base.Preconditions; +import me.glicz.skanalyzer.loader.AddonsLoader; +import me.glicz.skanalyzer.mockbukkit.AnalyzerServer; +import org.apache.commons.io.FileUtils; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.util.List; +import java.util.Scanner; + +public class SkAnalyzer { + private static SkAnalyzer instance; + private final AnalyzerServer server; + + private SkAnalyzer(List args) { + Preconditions.checkArgument(instance == null, "SkAnalyzer instance is already set!"); + instance = this; + + System.out.printf("SkAnalyzer v%s - simple Skript parser. Created by Glicz.%n", getClass().getPackage().getSpecificationVersion()); + extractEmbeddedAddons(); + System.out.println("Enabling..."); + + server = MockBukkit.mock(new AnalyzerServer()); + AddonsLoader.loadAddons(); + AddonsLoader.getMockSkriptBridge().parseArgs(args); + + server.startTicking(); + System.out.println("Successfully enabled. Have fun!"); + + startReadingInput(); + } + + public static void main(String[] args) { + new SkAnalyzer(List.of(args)); + } + + public static SkAnalyzer get() { + return instance; + } + + public AnalyzerServer getServer() { + return server; + } + + private void startReadingInput() { + Thread thread = new Thread() { + private final Scanner scanner = new Scanner(System.in); + + @Override + public void run() { + while (!Thread.interrupted()) { + if (scanner.hasNext()) { + String line = scanner.nextLine(); + if (line != null) + AddonsLoader.getMockSkriptBridge().parseScript(line); + } + } + } + }; + thread.setDaemon(true); + thread.start(); + } + + private void extractEmbeddedAddons() { + System.out.println("Extracting embedded addons..."); + + try (InputStream embeddedJar = getClass().getClassLoader().getResourceAsStream("MockSkript.jar.embedded")) { + Preconditions.checkArgument(embeddedJar != null, "Couldn't find embedded MockSkript.jar"); + FileUtils.copyInputStreamToFile(embeddedJar, new File(AddonsLoader.ADDONS, "MockSkript.jar")); + } catch (IOException e) { + throw new RuntimeException(e); + } + + try (InputStream embeddedJar = getClass().getClassLoader().getResourceAsStream("MockSkriptBridge.jar.embedded")) { + Preconditions.checkArgument(embeddedJar != null, "Couldn't find embedded MockSkriptBridge.jar"); + FileUtils.copyInputStreamToFile(embeddedJar, new File(AddonsLoader.ADDONS, "MockSkriptBridge.jar")); + } catch (IOException e) { + throw new RuntimeException(e); + } + + System.out.println("Successfully extracted embedded addons!"); + } +} diff --git a/src/main/java/me/glicz/skanalyzer/bridge/MockSkriptBridge.java b/src/main/java/me/glicz/skanalyzer/bridge/MockSkriptBridge.java new file mode 100644 index 0000000..9a1240a --- /dev/null +++ b/src/main/java/me/glicz/skanalyzer/bridge/MockSkriptBridge.java @@ -0,0 +1,11 @@ +package me.glicz.skanalyzer.bridge; + +import org.bukkit.plugin.java.JavaPlugin; + +import java.util.List; + +public abstract class MockSkriptBridge extends JavaPlugin { + public abstract void parseArgs(List args); + + public abstract void parseScript(String path); +} diff --git a/src/main/java/me/glicz/skanalyzer/loader/AddonsLoader.java b/src/main/java/me/glicz/skanalyzer/loader/AddonsLoader.java new file mode 100644 index 0000000..8f36e8e --- /dev/null +++ b/src/main/java/me/glicz/skanalyzer/loader/AddonsLoader.java @@ -0,0 +1,54 @@ +package me.glicz.skanalyzer.loader; + +import io.papermc.paper.plugin.provider.classloader.ConfiguredPluginClassLoader; +import me.glicz.skanalyzer.SkAnalyzer; +import me.glicz.skanalyzer.bridge.MockSkriptBridge; +import me.glicz.skanalyzer.mockbukkit.AnalyzerClassLoader; +import org.bukkit.plugin.PluginDescriptionFile; +import org.bukkit.plugin.java.JavaPlugin; + +import java.io.File; +import java.util.jar.JarFile; + +public class AddonsLoader { + public static final File USER_HOME = new File(System.getProperty("user.home")); + public static final File ADDONS = new File(USER_HOME, "SkAnalyzer/addons"); + private static JavaPlugin skript; + private static MockSkriptBridge mockSkriptBridge; + + public static void loadAddons() { + if (skript != null) + throw new RuntimeException("Addons are already loaded!"); + skript = loadAddon(new File(ADDONS, "MockSkript.jar")); // currently only Skript support :( + mockSkriptBridge = (MockSkriptBridge) loadAddon(new File(ADDONS, "MockSkriptBridge.jar")); + } + + @SuppressWarnings("UnstableApiUsage") + private static JavaPlugin loadAddon(File file) { + try { + JarFile jarFile = new JarFile(file); + PluginDescriptionFile description = new PluginDescriptionFile(jarFile.getInputStream(jarFile.getEntry("plugin.yml"))); + AnalyzerClassLoader classLoader = new AnalyzerClassLoader( + SkAnalyzer.class.getClassLoader(), + description, + new File(AddonsLoader.ADDONS, description.getName()), + file, + jarFile + ); + if (skript != null) + classLoader.getGroup().add((ConfiguredPluginClassLoader) skript.getClass().getClassLoader()); + Class pluginClass = classLoader.loadClass(description.getMainClass(), true, false, false); + JavaPlugin plugin = (JavaPlugin) pluginClass.getConstructor().newInstance(); + SkAnalyzer.get().getServer().getPluginManager().registerLoadedPlugin(plugin); + SkAnalyzer.get().getServer().getPluginManager().enablePlugin(plugin); + return plugin; + } catch (Exception e) { + e.printStackTrace(System.out); + } + return null; + } + + public static MockSkriptBridge getMockSkriptBridge() { + return mockSkriptBridge; + } +} diff --git a/src/main/java/me/glicz/skanalyzer/mockbukkit/AnalyzerClassLoader.java b/src/main/java/me/glicz/skanalyzer/mockbukkit/AnalyzerClassLoader.java new file mode 100644 index 0000000..907d4ce --- /dev/null +++ b/src/main/java/me/glicz/skanalyzer/mockbukkit/AnalyzerClassLoader.java @@ -0,0 +1,160 @@ +package me.glicz.skanalyzer.mockbukkit; + +import be.seeseemelk.mockbukkit.plugin.MockBukkitPluginClassLoaderGroup; +import com.destroystokyo.paper.utils.PaperPluginLogger; +import com.google.common.io.ByteStreams; +import io.papermc.paper.plugin.configuration.PluginMeta; +import io.papermc.paper.plugin.provider.classloader.ConfiguredPluginClassLoader; +import io.papermc.paper.plugin.provider.classloader.PluginClassLoaderGroup; +import org.bukkit.Bukkit; +import org.bukkit.plugin.PluginDescriptionFile; +import org.bukkit.plugin.java.JavaPlugin; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.net.URLClassLoader; +import java.security.CodeSigner; +import java.security.CodeSource; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; +import java.util.jar.Manifest; + +@SuppressWarnings("UnstableApiUsage") +public class AnalyzerClassLoader extends URLClassLoader implements ConfiguredPluginClassLoader { + static { + ClassLoader.registerAsParallelCapable(); + } + + private final PluginClassLoaderGroup classLoaderGroup = new MockBukkitPluginClassLoaderGroup(); + private final Map> classes = new ConcurrentHashMap<>(); + private final PluginDescriptionFile description; + private final File dataFolder, file; + private final URL url; + private final JarFile jarFile; + private final Manifest manifest; + + public AnalyzerClassLoader(ClassLoader parent, PluginDescriptionFile description, File dataFolder, File file, JarFile jarFile) throws Exception { + super(file.getName(), new URL[]{file.toURI().toURL()}, parent); + this.description = description; + this.dataFolder = dataFolder; + this.file = file; + this.url = file.toURI().toURL(); + this.jarFile = jarFile; + this.manifest = jarFile.getManifest(); + } + + @Override + public PluginMeta getConfiguration() { + return description; + } + + @Override + protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException { + return loadClass0(name, resolve, true); + } + + @Override + public Class loadClass(@NotNull String name, boolean resolve, boolean checkGlobal, boolean checkLibraries) throws ClassNotFoundException { + return loadClass0(name, resolve, checkGlobal); + } + + private Class loadClass0(String name, boolean resolve, boolean checkGlobal) throws ClassNotFoundException { + try { + Class result = super.loadClass(name, resolve); + if (checkGlobal || result.getClassLoader() == this) + return result; + } catch (ClassNotFoundException ignored) { + } + + if (checkGlobal) { + Class result = this.classLoaderGroup.getClassByName(name, resolve, this); + if (result != null) + return result; + } + + throw new ClassNotFoundException(name); + } + + @Override + protected Class findClass(String name) throws ClassNotFoundException { + if (name.startsWith("org.bukkit.") || name.startsWith("net.minecraft.")) { + throw new ClassNotFoundException(name); + } + Class result = classes.get(name); + + if (result == null) { + String path = name.replace('.', '/').concat(".class"); + JarEntry entry = jarFile.getJarEntry(path); + + if (entry != null) { + byte[] classBytes; + + try (InputStream is = jarFile.getInputStream(entry)) { + classBytes = ByteStreams.toByteArray(is); + } catch (IOException ex) { + throw new ClassNotFoundException(name, ex); + } + + int dot = name.lastIndexOf('.'); + if (dot != -1) { + String pkgName = name.substring(0, dot); + if (getDefinedPackage(pkgName) == null) { + try { + if (manifest != null) + definePackage(pkgName, manifest, url); + else definePackage( + pkgName, null, null, null, + null, null, null, null + ); + } catch (IllegalArgumentException ex) { + if (getDefinedPackage(pkgName) == null) + throw new IllegalStateException("Cannot find package " + pkgName); + } + } + } + + CodeSigner[] signers = entry.getCodeSigners(); + CodeSource source = new CodeSource(url, signers); + + result = defineClass(name, classBytes, 0, classBytes.length, source); + } + + if (result == null) + result = super.findClass(name); + + classes.put(name, result); + } + + return result; + } + + @Override + public void init(JavaPlugin plugin) { + plugin.init(Bukkit.getServer(), description, dataFolder, file, this, description, PaperPluginLogger.getLogger(getConfiguration())); + } + + @Override + public @Nullable JavaPlugin getPlugin() { + return null; + } + + @Override + public @NotNull PluginClassLoaderGroup getGroup() { + return classLoaderGroup; + } + + @Override + public void close() throws IOException { + try { + super.close(); + } finally { + jarFile.close(); + } + } +} diff --git a/src/main/java/me/glicz/skanalyzer/mockbukkit/AnalyzerServer.java b/src/main/java/me/glicz/skanalyzer/mockbukkit/AnalyzerServer.java new file mode 100644 index 0000000..7f611fc --- /dev/null +++ b/src/main/java/me/glicz/skanalyzer/mockbukkit/AnalyzerServer.java @@ -0,0 +1,54 @@ +package me.glicz.skanalyzer.mockbukkit; + +import be.seeseemelk.mockbukkit.ServerMock; +import be.seeseemelk.mockbukkit.scheduler.BukkitSchedulerMock; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.block.data.BlockData; +import org.jetbrains.annotations.NotNull; + +import java.util.Timer; +import java.util.TimerTask; + +public class AnalyzerServer extends ServerMock { + private final AnalyzerUnsafeValues unsafe = new AnalyzerUnsafeValues(); + + public void startTicking() { + new Timer().scheduleAtFixedRate(new TimerTask() { + @Override + public void run() { + ((BukkitSchedulerMock) Bukkit.getScheduler()).performOneTick(); + } + }, 50, 50); + } + + @Override + public @NotNull String getName() { + return "SkAnalyzer"; + } + + @SuppressWarnings("deprecation") + @Override + public @NotNull AnalyzerUnsafeValues getUnsafe() { + return unsafe; + } + + @SuppressWarnings("DataFlowIssue") + @Override + public @NotNull BlockData createBlockData(String data) { + if (data.contains(":")) + data = data.split(":")[1]; + String rawMaterial = (data.indexOf('[') == -1) + ? data + : data.substring(0, data.indexOf('[')); + Material material = Material.getMaterial(rawMaterial.toUpperCase()); + if (material == null) + return null; + return createBlockData(material); + } + + @Override + public @NotNull BlockData createBlockData(Material material, String data) { + return createBlockData(material); + } +} diff --git a/src/main/java/me/glicz/skanalyzer/mockbukkit/AnalyzerUnsafeValues.java b/src/main/java/me/glicz/skanalyzer/mockbukkit/AnalyzerUnsafeValues.java new file mode 100644 index 0000000..508187d --- /dev/null +++ b/src/main/java/me/glicz/skanalyzer/mockbukkit/AnalyzerUnsafeValues.java @@ -0,0 +1,12 @@ +package me.glicz.skanalyzer.mockbukkit; + +import be.seeseemelk.mockbukkit.MockUnsafeValues; +import org.bukkit.inventory.ItemStack; + +@SuppressWarnings("deprecation") +public class AnalyzerUnsafeValues extends MockUnsafeValues { + @Override + public ItemStack modifyItemStack(ItemStack stack, String arguments) { + return stack; + } +} diff --git a/src/main/java/me/glicz/skanalyzer/structure/StructureType.java b/src/main/java/me/glicz/skanalyzer/structure/StructureType.java new file mode 100644 index 0000000..a4418e0 --- /dev/null +++ b/src/main/java/me/glicz/skanalyzer/structure/StructureType.java @@ -0,0 +1,7 @@ +package me.glicz.skanalyzer.structure; + +public enum StructureType { + COMMAND, + EVENT, + FUNCTION +} diff --git a/src/main/java/me/glicz/skanalyzer/structure/data/EventData.java b/src/main/java/me/glicz/skanalyzer/structure/data/EventData.java new file mode 100644 index 0000000..3967cf0 --- /dev/null +++ b/src/main/java/me/glicz/skanalyzer/structure/data/EventData.java @@ -0,0 +1,14 @@ +package me.glicz.skanalyzer.structure.data; + +import org.bukkit.event.EventPriority; + +public class EventData extends StructureData { + private final String id; + private final EventPriority eventPriority; + + public EventData(int line, String value, String id, EventPriority eventPriority) { + super(line, value); + this.id = id; + this.eventPriority = eventPriority; + } +} diff --git a/src/main/java/me/glicz/skanalyzer/structure/data/StructureData.java b/src/main/java/me/glicz/skanalyzer/structure/data/StructureData.java new file mode 100644 index 0000000..3e04d97 --- /dev/null +++ b/src/main/java/me/glicz/skanalyzer/structure/data/StructureData.java @@ -0,0 +1,11 @@ +package me.glicz.skanalyzer.structure.data; + +public class StructureData { + private final int line; + private final String value; + + public StructureData(int line, String value) { + this.line = line; + this.value = value; + } +} diff --git a/src/main/resources/logger.properties b/src/main/resources/logger.properties new file mode 100644 index 0000000..e69de29