diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..630784d --- /dev/null +++ b/build.gradle @@ -0,0 +1,22 @@ +plugins { + id 'java' +} + +group = 'io.github.skippyall' +version = '1.0-SNAPSHOT' + +subprojects { + repositories { + exclusiveContent { + forRepository { + maven { + name = "minebench-repo" + url = "https://repo.minebench.de/" + } + } + filter { + includeModule("de.themoep", "minedown-adventure") + } + } + } +} \ No newline at end of file diff --git a/common/build.gradle b/common/build.gradle new file mode 100644 index 0000000..0cf03e4 --- /dev/null +++ b/common/build.gradle @@ -0,0 +1,40 @@ +plugins { + id 'java' + id 'com.gradleup.shadow' version '8.3.5' +} + +repositories { + mavenCentral() + maven { + url = "https://libraries.minecraft.net" + } +} + +dependencies { + compileOnly "com.mojang:brigadier:${brigadier_version}" + compileOnly "net.kyori:adventure-api:${adventure_version}" + compileOnly "net.kyori:adventure-text-serializer-json:${adventure_version}" + compileOnly "net.kyori:adventure-text-minimessage:${adventure_version}" + + compileOnly("org.slf4j:slf4j-api:$slf4j_version") + + compileOnly("com.google.code.gson:gson:${gson_version}") + + implementation "de.themoep:minedown-adventure:${minedown_version}" +} + +def targetJavaVersion = 21 +tasks.withType(JavaCompile).configureEach { + // ensure that the encoding is set to UTF-8, no matter what the system default is + // this fixes some edge cases with special characters not displaying correctly + // see http://yodaconditions.net/blog/fix-for-java-file-encoding-problems-with-gradle.html + // If Javadoc is generated, this must be specified in that task too. + it.options.encoding = "UTF-8" + if (targetJavaVersion >= 10 || JavaVersion.current().isJava10Compatible()) { + it.options.release.set(targetJavaVersion) + } +} + +shadowJar { + relocate("de.themoep.minedown.adventure", "io.github.skippyall.minedown") +} \ No newline at end of file diff --git a/common/src/main/java/io/github/skippyall/ruler/FileUtils.java b/common/src/main/java/io/github/skippyall/ruler/FileUtils.java new file mode 100644 index 0000000..0207dad --- /dev/null +++ b/common/src/main/java/io/github/skippyall/ruler/FileUtils.java @@ -0,0 +1,47 @@ +package io.github.skippyall.ruler; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.stream.Stream; + +public class FileUtils { + public static Path removeExtension(Path path) { + return Path.of(removeExtension(path.toString())); + } + + public static String removeExtension(String path) { + if(path.contains(".")) { + return path.substring(0, path.lastIndexOf('.')); + } else { + return path; + } + } + + public static String getExtension(Path path) { + return getExtension(path.toString()); + } + + public static String getExtension(String path) { + if(path.contains(".")) { + return path.substring(path.lastIndexOf('.') + 1); + } else { + return ""; + } + } + + public static Path append(Path path, String extension) { + return Path.of(path.toString() + extension); + } + + public static Path findFileWithName(Path path) { + try (Stream files = Files.list(path.getParent())) { + return files + .filter(foundPath -> removeExtension(foundPath).equals(path)) + .findFirst() + .orElse(null); + } catch (IOException e) { + return null; + } + } +} diff --git a/common/src/main/java/io/github/skippyall/ruler/MineDownSerializer.java b/common/src/main/java/io/github/skippyall/ruler/MineDownSerializer.java new file mode 100644 index 0000000..1a9bd59 --- /dev/null +++ b/common/src/main/java/io/github/skippyall/ruler/MineDownSerializer.java @@ -0,0 +1,18 @@ +package io.github.skippyall.ruler; + +import de.themoep.minedown.adventure.MineDown; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.serializer.ComponentSerializer; +import org.jspecify.annotations.NonNull; + +public class MineDownSerializer implements ComponentSerializer { + @Override + public @NonNull Component deserialize(@NonNull String input) { + return MineDown.parse(input); + } + + @Override + public @NonNull String serialize(@NonNull Component component) { + return MineDown.stringify(component); + } +} diff --git a/common/src/main/java/io/github/skippyall/ruler/Platform.java b/common/src/main/java/io/github/skippyall/ruler/Platform.java new file mode 100644 index 0000000..492a0f8 --- /dev/null +++ b/common/src/main/java/io/github/skippyall/ruler/Platform.java @@ -0,0 +1,13 @@ +package io.github.skippyall.ruler; + +import org.slf4j.Logger; + +import java.nio.file.Path; +import java.util.concurrent.CompletableFuture; +import java.util.function.Supplier; + +public interface Platform { + Path getConfigDirectory(); + Logger getLogger(); + CompletableFuture runAsync(Supplier supplier); +} diff --git a/common/src/main/java/io/github/skippyall/ruler/Ruler.java b/common/src/main/java/io/github/skippyall/ruler/Ruler.java new file mode 100644 index 0000000..225e380 --- /dev/null +++ b/common/src/main/java/io/github/skippyall/ruler/Ruler.java @@ -0,0 +1,21 @@ +package io.github.skippyall.ruler; + +import org.jetbrains.annotations.Nullable; + +public class Ruler { + public static final String ID = "ruler"; + + @Nullable + private static Platform platform; + + public static void init(Platform platform) { + Ruler.platform = platform; + } + + public static Platform getPlatform() { + if(platform == null) { + throw new IllegalStateException("Ruler is not initialized yet!"); + } + return platform; + } +} diff --git a/common/src/main/java/io/github/skippyall/ruler/command/CommandHelper.java b/common/src/main/java/io/github/skippyall/ruler/command/CommandHelper.java new file mode 100644 index 0000000..f070762 --- /dev/null +++ b/common/src/main/java/io/github/skippyall/ruler/command/CommandHelper.java @@ -0,0 +1,7 @@ +package io.github.skippyall.ruler.command; + +import net.kyori.adventure.audience.Audience; + +public interface CommandHelper { + Audience toAudience(S source); +} diff --git a/common/src/main/java/io/github/skippyall/ruler/command/Commands.java b/common/src/main/java/io/github/skippyall/ruler/command/Commands.java new file mode 100644 index 0000000..e70c963 --- /dev/null +++ b/common/src/main/java/io/github/skippyall/ruler/command/Commands.java @@ -0,0 +1,57 @@ +package io.github.skippyall.ruler.command; + +import com.mojang.brigadier.arguments.ArgumentType; +import com.mojang.brigadier.arguments.StringArgumentType; +import com.mojang.brigadier.builder.LiteralArgumentBuilder; +import com.mojang.brigadier.builder.RequiredArgumentBuilder; +import io.github.skippyall.ruler.Ruler; +import io.github.skippyall.ruler.config.ConfigLoader; +import net.kyori.adventure.audience.Audience; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.format.NamedTextColor; + +import java.util.List; + +public class Commands { + private final CommandHelper helper; + private final RuleSuggestionProvider ruleSuggestionProvider = new RuleSuggestionProvider<>(); + + public Commands(CommandHelper helper) { + this.helper = helper; + } + + public List> getCommands() { + return List.of( + literal("ruler") + .then(literal("open") + .then(argument("path", StringArgumentType.string()) + .suggests(ruleSuggestionProvider) + .executes(context -> { + String path = StringArgumentType.getString(context, "path"); + Audience player = helper.toAudience(context.getSource()); + + try { + player.sendMessage(ConfigLoader.getRule(path, player)); + } catch (Exception e) { + player.sendMessage(Component.text("This file doesn't exist").color(NamedTextColor.RED)); + Ruler.getPlatform().getLogger().error("Error while loading rule", e); + } + return 0; + }) + ) + ) + .executes(context -> { + helper.toAudience(context.getSource()).sendMessage(Component.text("Hi")); + return 0; + }) + ); + } + + private LiteralArgumentBuilder literal(String name) { + return LiteralArgumentBuilder.literal(name); + } + + private RequiredArgumentBuilder argument(String name, ArgumentType type) { + return RequiredArgumentBuilder.argument(name, type); + } +} diff --git a/common/src/main/java/io/github/skippyall/ruler/command/RuleSuggestionProvider.java b/common/src/main/java/io/github/skippyall/ruler/command/RuleSuggestionProvider.java new file mode 100644 index 0000000..3e32e6a --- /dev/null +++ b/common/src/main/java/io/github/skippyall/ruler/command/RuleSuggestionProvider.java @@ -0,0 +1,40 @@ +package io.github.skippyall.ruler.command; + +import com.mojang.brigadier.context.CommandContext; +import com.mojang.brigadier.exceptions.CommandSyntaxException; +import com.mojang.brigadier.suggestion.SuggestionProvider; +import com.mojang.brigadier.suggestion.Suggestions; +import com.mojang.brigadier.suggestion.SuggestionsBuilder; +import io.github.skippyall.ruler.Ruler; +import io.github.skippyall.ruler.rule.RuleUtils; + +import java.util.List; +import java.util.concurrent.CompletableFuture; + +public class RuleSuggestionProvider implements SuggestionProvider { + @Override + public CompletableFuture getSuggestions(CommandContext commandContext, SuggestionsBuilder suggestionsBuilder) throws CommandSyntaxException { + return Ruler.getPlatform().runAsync(() -> { + String start = suggestionsBuilder.getInput(); + int last = start.lastIndexOf('.'); + + String incomplete; + String completed = ""; + + if (last != -1) { + incomplete = start.substring(last + 1); + completed = start.substring(0, last); + } else { + incomplete = start; + } + List rules = RuleUtils.listRules(completed, true); + for (String rule : rules) { + if (rule.startsWith(incomplete)) { + suggestionsBuilder.suggest(completed + rule); + } + } + return suggestionsBuilder.build(); + }); + + } +} diff --git a/common/src/main/java/io/github/skippyall/ruler/config/ConfigLoader.java b/common/src/main/java/io/github/skippyall/ruler/config/ConfigLoader.java new file mode 100644 index 0000000..5bdf0cc --- /dev/null +++ b/common/src/main/java/io/github/skippyall/ruler/config/ConfigLoader.java @@ -0,0 +1,88 @@ +package io.github.skippyall.ruler.config; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonParseException; +import io.github.skippyall.ruler.FileUtils; +import io.github.skippyall.ruler.Ruler; +import io.github.skippyall.ruler.config.condition.Condition; +import io.github.skippyall.ruler.config.condition.ConditionTypeAdapter; +import io.github.skippyall.ruler.rule.InvalidRuleException; +import io.github.skippyall.ruler.rule.RuleUtils; +import net.kyori.adventure.audience.Audience; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.serializer.ComponentSerializer; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; + +public class ConfigLoader { + public static final Gson configSerializer = new GsonBuilder() + .setPrettyPrinting() + .registerTypeAdapter(Condition.class, new ConditionTypeAdapter()) + .registerTypeAdapter(Redirect.class, new Redirect.Adapter()) + .create(); + + public static RuleConfig loadConfig(String rulePath) { + Path configPath = RuleUtils.getFilePathWithoutExtension(rulePath); + return loadConfig(configPath); + } + + private static RuleConfig loadConfig(Path fileWithoutExtension) { + RuleConfig parentConfig = null; + if(RuleUtils.isInDirectory(fileWithoutExtension.getParent())) { + parentConfig = loadConfig(fileWithoutExtension.getParent()); + } + RuleConfig config = null; + Path configPath = FileUtils.append(fileWithoutExtension, ".config.json"); + if(Files.isRegularFile(configPath)) { + try { + config = configSerializer.fromJson(Files.newBufferedReader(configPath), RuleConfig.class); + } catch (IOException | JsonParseException e) { + Ruler.getPlatform().getLogger().error("Could not read config {}", configPath, e); + return parentConfig; + } + } else { + return parentConfig; + } + + if(parentConfig != null) { + config.applyParentRules(parentConfig); + } + return config; + } + + public static String getActualRulePath(String rulePath, Audience audience) { + Path fileWithoutExtension = RuleUtils.getFilePathWithoutExtension(rulePath); + RuleConfig config = loadConfig(fileWithoutExtension); + + if(config != null) { + for (Redirect redirect : config.getRedirects()) { + if (redirect.getCondition().test(audience)) { + return redirect.getRulePath(); + } + } + } + + return rulePath; + } + + public static Component getRule(String path, Audience player) throws InvalidRuleException { + String actualPath = ConfigLoader.getActualRulePath(path, player); + Ruler.getPlatform().getLogger().error(actualPath); + + Path filePath = RuleUtils.getFilePath(actualPath); + + String extension = FileUtils.getExtension(filePath); + + ComponentSerializer serializer = RuleUtils.getSerializer(extension); + + if(serializer == null) { + throw new InvalidRuleException("File doesn't exist"); + } + + + return RuleUtils.readRuleFromFile(filePath, serializer); + } +} diff --git a/common/src/main/java/io/github/skippyall/ruler/config/Redirect.java b/common/src/main/java/io/github/skippyall/ruler/config/Redirect.java new file mode 100644 index 0000000..0ea3222 --- /dev/null +++ b/common/src/main/java/io/github/skippyall/ruler/config/Redirect.java @@ -0,0 +1,70 @@ +package io.github.skippyall.ruler.config; + +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import io.github.skippyall.ruler.config.condition.AlwaysCondition; +import io.github.skippyall.ruler.config.condition.Condition; +import io.github.skippyall.ruler.config.condition.Conditions; + +import java.lang.reflect.Type; + +public class Redirect { + Condition condition = AlwaysCondition.ALWAYS_TRUE; + String rulePath; + + public Redirect(String rulePath) { + this.rulePath = rulePath; + } + + public Redirect(Condition condition, String rulePath) { + this.condition = condition; + this.rulePath = rulePath; + } + + public Condition getCondition() { + return condition; + } + + public void setCondition(Condition condition) { + this.condition = condition; + } + + public String getRulePath() { + return rulePath; + } + + public void setRulePath(String rulePath) { + this.rulePath = rulePath; + } + + public static class Adapter implements JsonDeserializer, JsonSerializer { + @Override + public Redirect deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { + if(json.isJsonObject()) { + JsonObject object = json.getAsJsonObject(); + String rulePath = object.get("rulePath").getAsString(); + Condition condition = AlwaysCondition.ALWAYS_TRUE; + if(object.has("condition")) { + condition = Conditions.deserialize(object.get("condition")); + } + return new Redirect(condition, rulePath); + } else { + String rulePath = json.getAsString(); + return new Redirect(rulePath); + } + } + + @Override + public JsonElement serialize(Redirect src, Type typeOfSrc, JsonSerializationContext context) { + JsonObject object = new JsonObject(); + object.addProperty("rulePath", src.rulePath); + object.add("condition", Conditions.serialize(src.condition)); + return null; + } + } +} diff --git a/common/src/main/java/io/github/skippyall/ruler/config/RuleConfig.java b/common/src/main/java/io/github/skippyall/ruler/config/RuleConfig.java new file mode 100644 index 0000000..ec41560 --- /dev/null +++ b/common/src/main/java/io/github/skippyall/ruler/config/RuleConfig.java @@ -0,0 +1,24 @@ +package io.github.skippyall.ruler.config; + +import java.util.ArrayList; +import java.util.List; + +public class RuleConfig { + private List redirects = new ArrayList<>(); + + public RuleConfig() { + + } + + public void applyParentRules(RuleConfig parent) { + redirects.addAll(parent.getRedirects()); + } + + public List getRedirects() { + return redirects; + } + + public void setRedirects(List redirects) { + this.redirects = redirects; + } +} diff --git a/common/src/main/java/io/github/skippyall/ruler/config/condition/AlwaysCondition.java b/common/src/main/java/io/github/skippyall/ruler/config/condition/AlwaysCondition.java new file mode 100644 index 0000000..3cf7440 --- /dev/null +++ b/common/src/main/java/io/github/skippyall/ruler/config/condition/AlwaysCondition.java @@ -0,0 +1,37 @@ +package io.github.skippyall.ruler.config.condition; + +import com.google.gson.JsonObject; +import io.github.skippyall.ruler.Ruler; +import net.kyori.adventure.audience.Audience; +import net.kyori.adventure.key.Key; + +public class AlwaysCondition implements Condition { + public static final Key ALWAYS_TRUE_KEY = Key.key(Ruler.ID, "always_true"); + public static final Key ALWAYS_FALSE_KEY = Key.key(Ruler.ID, "always_false"); + + public static final AlwaysCondition ALWAYS_TRUE = new AlwaysCondition(true, ALWAYS_TRUE_KEY); + public static final AlwaysCondition ALWAYS_FALSE = new AlwaysCondition(false, ALWAYS_FALSE_KEY); + + private final boolean value; + private final Key type; + + private AlwaysCondition(boolean value, Key type) { + this.value = value; + this.type = type; + } + + @Override + public boolean test(Audience audience) { + return value; + } + + @Override + public Key getType() { + return type; + } + + @Override + public JsonObject serialize() { + return new JsonObject(); + } +} diff --git a/common/src/main/java/io/github/skippyall/ruler/config/condition/Condition.java b/common/src/main/java/io/github/skippyall/ruler/config/condition/Condition.java new file mode 100644 index 0000000..67918bb --- /dev/null +++ b/common/src/main/java/io/github/skippyall/ruler/config/condition/Condition.java @@ -0,0 +1,13 @@ +package io.github.skippyall.ruler.config.condition; + +import com.google.gson.JsonObject; +import net.kyori.adventure.audience.Audience; +import net.kyori.adventure.key.Key; + +public interface Condition { + boolean test(Audience audience); + + Key getType(); + + JsonObject serialize(); +} diff --git a/common/src/main/java/io/github/skippyall/ruler/config/condition/ConditionTypeAdapter.java b/common/src/main/java/io/github/skippyall/ruler/config/condition/ConditionTypeAdapter.java new file mode 100644 index 0000000..9063433 --- /dev/null +++ b/common/src/main/java/io/github/skippyall/ruler/config/condition/ConditionTypeAdapter.java @@ -0,0 +1,26 @@ +package io.github.skippyall.ruler.config.condition; + +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonParseException; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; + +import java.lang.reflect.Type; + +public class ConditionTypeAdapter implements JsonSerializer, JsonDeserializer { + @Override + public Condition deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { + try { + return Conditions.deserialize(json); + } catch (Exception e) { + throw new JsonParseException(e); + } + } + + @Override + public JsonElement serialize(Condition src, Type typeOfSrc, JsonSerializationContext context) { + return Conditions.serialize(src); + } +} diff --git a/common/src/main/java/io/github/skippyall/ruler/config/condition/Conditions.java b/common/src/main/java/io/github/skippyall/ruler/config/condition/Conditions.java new file mode 100644 index 0000000..af75ccb --- /dev/null +++ b/common/src/main/java/io/github/skippyall/ruler/config/condition/Conditions.java @@ -0,0 +1,39 @@ +package io.github.skippyall.ruler.config.condition; + +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import net.kyori.adventure.key.Key; + +import java.util.HashMap; +import java.util.function.Function; + +public class Conditions { + private static final HashMap> deserializers = new HashMap<>(); + + public static void register(Key name, Function deserializer) { + deserializers.put(name, deserializer); + } + + public static Condition deserialize(JsonElement config) { + if(config.isJsonObject()) { + JsonObject object = config.getAsJsonObject(); + return deserializers.get(Key.key(object.get("type").getAsString())).apply(object); + } else { + String type = config.getAsString(); + return deserializers.get(Key.key(type)).apply(null); + } + } + + public static JsonObject serialize(Condition condition) { + JsonObject config = condition.serialize(); + config.addProperty("type", condition.getType().asString()); + return config; + } + + static { + register(AlwaysCondition.ALWAYS_TRUE_KEY, object -> AlwaysCondition.ALWAYS_TRUE); + register(AlwaysCondition.ALWAYS_FALSE_KEY, object -> AlwaysCondition.ALWAYS_FALSE); + register(TwoParamLogicCondition.AND_KEY, element -> TwoParamLogicCondition.and(TwoParamLogicCondition.deserialize(element))); + register(TwoParamLogicCondition.OR_KEY, element -> TwoParamLogicCondition.or(TwoParamLogicCondition.deserialize(element))); + } +} diff --git a/common/src/main/java/io/github/skippyall/ruler/config/condition/TwoParamLogicCondition.java b/common/src/main/java/io/github/skippyall/ruler/config/condition/TwoParamLogicCondition.java new file mode 100644 index 0000000..e7f9547 --- /dev/null +++ b/common/src/main/java/io/github/skippyall/ruler/config/condition/TwoParamLogicCondition.java @@ -0,0 +1,76 @@ +package io.github.skippyall.ruler.config.condition; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import io.github.skippyall.ruler.Ruler; +import net.kyori.adventure.audience.Audience; +import net.kyori.adventure.key.Key; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.BinaryOperator; + +public class TwoParamLogicCondition implements Condition { + public static final Key AND_KEY = Key.key(Ruler.ID, "and"); + public static final Key OR_KEY = Key.key(Ruler.ID, "or"); + + private final Key key; + private final BinaryOperator logic; + private List conditions; + + private TwoParamLogicCondition(Key key, BinaryOperator logic, List conditions) { + this.key = key; + this.logic = logic; + this.conditions = conditions; + } + + public static TwoParamLogicCondition and(List conditions) { + return new TwoParamLogicCondition(AND_KEY, (b1, b2) -> b1 && b2, conditions); + } + + public static TwoParamLogicCondition or(List conditions) { + return new TwoParamLogicCondition(OR_KEY, (b1, b2) -> b1 || b2, conditions); + } + + @Override + public boolean test(Audience audience) { + boolean currentValue = false; + boolean first = true; + + for(Condition condition : conditions) { + if(first) { + currentValue = condition.test(audience); + first = false; + } else { + currentValue = logic.apply(currentValue, condition.test(audience)); + } + } + return currentValue; + } + + @Override + public Key getType() { + return key; + } + + @Override + public JsonObject serialize() { + JsonArray conditionArray = new JsonArray(); + for(Condition condition : conditions) { + conditionArray.add(Conditions.serialize(condition)); + } + JsonObject object = new JsonObject(); + object.add("conditions", conditionArray); + return object; + } + + public static List deserialize(JsonElement element) { + List conditions = new ArrayList<>(); + JsonArray array = element.getAsJsonArray(); + for(JsonElement conditionElement : array) { + conditions.add(Conditions.deserialize(conditionElement.getAsJsonObject())); + } + return conditions; + } +} diff --git a/common/src/main/java/io/github/skippyall/ruler/rule/InvalidRuleException.java b/common/src/main/java/io/github/skippyall/ruler/rule/InvalidRuleException.java new file mode 100644 index 0000000..f869b86 --- /dev/null +++ b/common/src/main/java/io/github/skippyall/ruler/rule/InvalidRuleException.java @@ -0,0 +1,15 @@ +package io.github.skippyall.ruler.rule; + +public class InvalidRuleException extends RuntimeException { + public InvalidRuleException(String message) { + super(message); + } + + public InvalidRuleException(String message, Throwable cause) { + super(message, cause); + } + + public InvalidRuleException(Throwable cause) { + super(cause); + } +} diff --git a/common/src/main/java/io/github/skippyall/ruler/rule/RuleUtils.java b/common/src/main/java/io/github/skippyall/ruler/rule/RuleUtils.java new file mode 100644 index 0000000..0f7f370 --- /dev/null +++ b/common/src/main/java/io/github/skippyall/ruler/rule/RuleUtils.java @@ -0,0 +1,137 @@ +package io.github.skippyall.ruler.rule; + +import io.github.skippyall.ruler.FileUtils; +import io.github.skippyall.ruler.MineDownSerializer; +import io.github.skippyall.ruler.Ruler; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.minimessage.MiniMessage; +import net.kyori.adventure.text.serializer.ComponentSerializer; +import net.kyori.adventure.text.serializer.json.JSONComponentSerializer; +import org.jspecify.annotations.Nullable; + +import java.io.IOException; +import java.nio.file.FileSystems; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.stream.Stream; + +public class RuleUtils { + private static final Map> extension_to_serializer = Map.of( + "json", JSONComponentSerializer.json(), + "md", new MineDownSerializer(), + "minimessage", MiniMessage.miniMessage() + ); + + @Nullable + public static ComponentSerializer getSerializer(String fileNameExtension) { + return extension_to_serializer.get(fileNameExtension); + } + + public static Path getRoot() { + return Ruler.getPlatform().getConfigDirectory().resolve("rules").toAbsolutePath(); + } + + public static boolean isValidRulePath(String path) { + return path.matches("([A-Za-z0-9\\-_.]+)") && + Arrays.stream(path.split("\\.")).noneMatch(String::isEmpty); + } + + public static void checkValidRulePath(String path) throws InvalidRuleException { + if(!isValidRulePath(path)) { + throw new InvalidRuleException("\"" + path + "\" is not a valid rule path"); + } + } + + public static boolean isInDirectory(Path path) { + return path.toAbsolutePath().startsWith(getRoot()); + } + + public static void checkDirectory(Path path) throws InvalidRuleException { + if(!isInDirectory(path)) { + throw new InvalidRuleException("File path \"" + path.toString() + "\" is not in the root rule directory."); + } + } + + public static Path getFilePathWithoutExtension(String rulePath) throws InvalidRuleException { + if(rulePath.isEmpty()) { + return getRoot(); + } + checkValidRulePath(rulePath); + Path joinedPath = getRoot().resolve(rulePath.replace(".", FileSystems.getDefault().getSeparator())).toAbsolutePath(); + checkDirectory(joinedPath); + return joinedPath; + } + + public static Path getFilePath(String rulePath) throws InvalidRuleException { + Path withoutExtension = getFilePathWithoutExtension(rulePath); + + String extension = tryFormats(withoutExtension); + if(extension == null) { + throw new InvalidRuleException("File for rule \"" + rulePath + "\" not found."); + } + + return Path.of(withoutExtension.toString() + "." + extension); + } + + public static String getRulePath(Path filePath) throws InvalidRuleException { + checkDirectory(filePath); + + Path relative = filePath.toAbsolutePath().relativize(getRoot()); + String withoutExtension = FileUtils.removeExtension(relative).toString(); + String path = withoutExtension.replace(FileSystems.getDefault().getSeparator(), "."); + + checkValidRulePath(path); + return path; + } + + public static Component readRuleFromFile(Path path, ComponentSerializer serializer) throws InvalidRuleException { + String text; + try { + text = Files.readString(path); + } catch (IOException e) { + throw new InvalidRuleException("Exception while reading file", e); + } + try { + return serializer.deserialize(text); + } catch (Exception e) { + throw new InvalidRuleException("Exception while parsing", e); + } + } + + public static @Nullable String tryFormats(Path path) { + String stringPath = path.toString(); + for (String extension : extension_to_serializer.keySet()) { + if(Files.exists(Path.of(stringPath + "." + extension))) { + return extension; + } + } + return null; + } + + public static List listRules(String basePath, boolean directories) { + Path dirPath = getFilePathWithoutExtension(basePath); + try { + if(!Files.isDirectory(dirPath)) { + return List.of(); + } + try(Stream paths = Files.list(dirPath)) { + return paths + .filter(path -> { + if (Files.isDirectory(path)) { + return directories; + } else { + return extension_to_serializer.containsKey(FileUtils.getExtension(path)); + } + }) + .map(RuleUtils::getRulePath) + .toList(); + } + } catch (IOException e) { + Ruler.getPlatform().getLogger().error("Exception while listing rules", e); + return List.of(); + } + } +} diff --git a/fabric/build.gradle b/fabric/build.gradle new file mode 100644 index 0000000..eb95134 --- /dev/null +++ b/fabric/build.gradle @@ -0,0 +1,111 @@ +plugins { + id 'fabric-loom' version '1.16-SNAPSHOT' apply true + id 'maven-publish' + id 'com.gradleup.shadow' version '9.4.1' +} + +version = project.mod_version +group = project.maven_group + +base { + archivesName = project.archives_base_name +} + +configurations { + shadowBundle { + canBeResolved = true + canBeConsumed = false + } +} + +repositories { + // Add repositories to retrieve artifacts from in here. + // You should only use this when depending on other mods because + // Loom adds the essential maven repositories to download Minecraft and libraries from automatically. + // See https://docs.gradle.org/current/userguide/declaring_repositories.html + // for more information about repositories. +} + +dependencies { + // To change the versions see the gradle.properties file + minecraft "com.mojang:minecraft:${project.minecraft_version}" + mappings "net.fabricmc:yarn:${project.yarn_mappings}:v2" + modImplementation "net.fabricmc:fabric-loader:${project.loader_version}" + + modImplementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_version}" + + modImplementation include("net.kyori:adventure-platform-fabric:${project.adventure_platform_fabric_version}") + + implementation project(":common") + shadowBundle(project(":common")) +} + +processResources { + inputs.property "version", project.version + inputs.property "minecraft_version", project.minecraft_version + inputs.property "loader_version", project.loader_version + filteringCharset "UTF-8" + + filesMatching("fabric.mod.json") { + expand "version": project.version, + "minecraft_version": project.minecraft_version, + "loader_version": project.loader_version + } +} + +def targetJavaVersion = 21 +tasks.withType(JavaCompile).configureEach { + // ensure that the encoding is set to UTF-8, no matter what the system default is + // this fixes some edge cases with special characters not displaying correctly + // see http://yodaconditions.net/blog/fix-for-java-file-encoding-problems-with-gradle.html + // If Javadoc is generated, this must be specified in that task too. + it.options.encoding = "UTF-8" + if (targetJavaVersion >= 10 || JavaVersion.current().isJava10Compatible()) { + it.options.release.set(targetJavaVersion) + } +} + +java { + def javaVersion = JavaVersion.toVersion(targetJavaVersion) + if (JavaVersion.current() < javaVersion) { + toolchain.languageVersion = JavaLanguageVersion.of(targetJavaVersion) + } + // Loom will automatically attach sourcesJar to a RemapSourcesJar task and to the "build" task + // if it is present. + // If you remove this line, sources will not be generated. + withSourcesJar() +} + +jar { + from("LICENSE") { + rename { "${it}_${project.archivesBaseName}"} + } +} + +shadowJar { + configurations = [project.configurations.shadowBundle] + archiveClassifier = 'dev-shadow' + relocate("de.themoep.minedown.adventure", "io.github.skippyall.minedown") +} + +remapJar { + input.set shadowJar.archiveFile +} + +// configure the maven publication +publishing { + publications { + create("mavenJava", MavenPublication) { + artifactId = project.archives_base_name + from components.java + } + } + + // See https://docs.gradle.org/current/userguide/publishing_maven.html for information on how to set up publishing. + repositories { + // Add repositories to publish to here. + // Notice: This block does NOT have the same function as the block in the top level. + // The repositories here will be used for publishing your artifact, not for + // retrieving dependencies. + } +} diff --git a/fabric/gradle.properties b/fabric/gradle.properties new file mode 100644 index 0000000..27d1976 --- /dev/null +++ b/fabric/gradle.properties @@ -0,0 +1,19 @@ +# Done to increase the memory available to gradle. +org.gradle.jvmargs=-Xmx1G + +# Fabric Properties + # check these on https://modmuss50.me/fabric.html + minecraft_version=1.21.8 + yarn_mappings=1.21.8+build.1 + loader_version=0.17.2 + +# Mod Properties + mod_version = 1.0-SNAPSHOT + maven_group = io.github.skippyall + archives_base_name = ruler-fabric + +# Dependencies + # check this on https://modmuss50.me/fabric.html + fabric_version=0.133.4+1.21.8 + + adventure_platform_fabric_version=6.6.0 diff --git a/fabric/src/main/java/io/github/skippyall/ruler/fabric/FabricCommandHelper.java b/fabric/src/main/java/io/github/skippyall/ruler/fabric/FabricCommandHelper.java new file mode 100644 index 0000000..d36fbdd --- /dev/null +++ b/fabric/src/main/java/io/github/skippyall/ruler/fabric/FabricCommandHelper.java @@ -0,0 +1,12 @@ +package io.github.skippyall.ruler.fabric; + +import io.github.skippyall.ruler.command.CommandHelper; +import net.kyori.adventure.audience.Audience; +import net.minecraft.server.command.ServerCommandSource; + +public class FabricCommandHelper implements CommandHelper { + @Override + public Audience toAudience(ServerCommandSource source) { + return source.audience(); + } +} diff --git a/fabric/src/main/java/io/github/skippyall/ruler/fabric/FabricPlatform.java b/fabric/src/main/java/io/github/skippyall/ruler/fabric/FabricPlatform.java new file mode 100644 index 0000000..92e13bd --- /dev/null +++ b/fabric/src/main/java/io/github/skippyall/ruler/fabric/FabricPlatform.java @@ -0,0 +1,33 @@ +package io.github.skippyall.ruler.fabric; + +import io.github.skippyall.ruler.Platform; +import net.fabricmc.loader.api.FabricLoader; +import net.minecraft.util.Util; +import org.slf4j.Logger; + +import java.nio.file.Path; +import java.util.concurrent.CompletableFuture; +import java.util.function.Supplier; + +public class FabricPlatform implements Platform { + private static final Path CONFIG_DIR = FabricLoader.getInstance().getConfigDir().resolve(RulerFabric.MOD_ID).toAbsolutePath(); + + public FabricPlatform() { + + } + + @Override + public Path getConfigDirectory() { + return CONFIG_DIR; + } + + @Override + public Logger getLogger() { + return RulerFabric.LOGGER; + } + + @Override + public CompletableFuture runAsync(Supplier supplier) { + return CompletableFuture.supplyAsync(supplier, Util.getMainWorkerExecutor()); + } +} diff --git a/fabric/src/main/java/io/github/skippyall/ruler/fabric/RulerFabric.java b/fabric/src/main/java/io/github/skippyall/ruler/fabric/RulerFabric.java new file mode 100644 index 0000000..0829b59 --- /dev/null +++ b/fabric/src/main/java/io/github/skippyall/ruler/fabric/RulerFabric.java @@ -0,0 +1,26 @@ +package io.github.skippyall.ruler.fabric; + +import com.mojang.brigadier.builder.LiteralArgumentBuilder; +import io.github.skippyall.ruler.Ruler; +import io.github.skippyall.ruler.command.Commands; +import net.fabricmc.api.ModInitializer; +import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback; +import net.minecraft.server.command.ServerCommandSource; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class RulerFabric implements ModInitializer { + public static final String MOD_ID = "ruler"; + public static final Commands COMMANDS = new Commands<>(new FabricCommandHelper()); + public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID); + + @Override + public void onInitialize() { + Ruler.init(new FabricPlatform()); + CommandRegistrationCallback.EVENT.register((dispatcher, access,environment) -> { + for(LiteralArgumentBuilder node : COMMANDS.getCommands()) { + dispatcher.register(node); + } + }); + } +} diff --git a/fabric/src/main/resources/fabric.mod.json b/fabric/src/main/resources/fabric.mod.json new file mode 100644 index 0000000..df713e7 --- /dev/null +++ b/fabric/src/main/resources/fabric.mod.json @@ -0,0 +1,26 @@ +{ + "schemaVersion": 1, + "id": "ruler", + "version": "${version}", + + "name": "Ruler", + "description": "", + "authors": [ + "skippyall" + ], + "contact": {}, + + "license": "MIT", + + "environment": "*", + "entrypoints": { + "main": [ + "io.github.skippyall.ruler.fabric.RulerFabric" + ] + }, + "depends": { + "fabricloader": ">=${loader_version}", + "fabric": "*", + "minecraft": "${minecraft_version}" + } +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..6be1ca8 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,6 @@ +brigadier_version=1.3.10 +adventure_version=4.26.1 +minedown_version=1.7.3-SNAPSHOT +slf4j_version=2.0.17 +gson_version=2.13.0 +night_config_version=3.6.0 \ 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..c6a280c --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Wed Apr 09 17:43:33 CEST 2025 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.4.1-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 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 b/settings.gradle new file mode 100644 index 0000000..2cd1f4a --- /dev/null +++ b/settings.gradle @@ -0,0 +1,12 @@ +pluginManagement { + repositories { + maven { + name = 'Fabric' + url = 'https://maven.fabricmc.net/' + } + gradlePluginPortal() + } +} + +rootProject.name = 'Ruler' +include ('common', 'velocity', 'fabric') diff --git a/velocity/build.gradle b/velocity/build.gradle new file mode 100644 index 0000000..2893054 --- /dev/null +++ b/velocity/build.gradle @@ -0,0 +1,79 @@ +plugins { + id 'java' + id 'eclipse' + id 'org.jetbrains.gradle.plugin.idea-ext' version '1.1.8' + id("xyz.jpenilla.run-velocity") version "2.3.1" + id 'com.gradleup.shadow' version '8.3.5' +} + +configurations { + shadowBundle { + canBeResolved = true + canBeConsumed = false + } +} + +repositories { + mavenCentral() + maven { + name = "papermc-repo" + url = "https://repo.papermc.io/repository/maven-public/" + } + maven { + name = "sonatype" + url = "https://oss.sonatype.org/content/groups/public/" + } +} + +dependencies { + compileOnly("com.velocitypowered:velocity-api:3.4.0-SNAPSHOT") + annotationProcessor("com.velocitypowered:velocity-api:3.4.0-SNAPSHOT") + + implementation project(":common") + shadowBundle(project(":common")) +} + +shadowJar { + configurations = [project.configurations.shadowBundle] + archiveClassifier = 'dev-shadow' + relocate("de.themoep.minedown.adventure", "io.github.skippyall.minedown") + relocate("com.electronwill.nightconfig", "io.github.skippyall.nightconfig") +} + +tasks { + runVelocity { + // Configure the Velocity version for our task. + // This is the only required configuration besides applying the plugin. + // Your plugin's jar (or shadowJar if present) will be used automatically. + velocityVersion("3.4.0-SNAPSHOT") + } +} + +def targetJavaVersion = 21 +java { + toolchain.languageVersion = JavaLanguageVersion.of(targetJavaVersion) +} + +tasks.withType(JavaCompile).configureEach { + options.encoding = 'UTF-8' + options.release.set(targetJavaVersion) +} + +/* +def templateSource = file('src/main/templates') +def templateDest = layout.buildDirectory.dir('generated/sources/templates') +def generateTemplates = tasks.register('generateTemplates', Copy) { task -> + def props = [ + 'version': project.version + ] + task.inputs.properties props + + task.from templateSource + task.into templateDest + task.expand props +} + +sourceSets.main.java.srcDir(generateTemplates.map { it.outputs }) + +project.idea.project.settings.taskTriggers.afterSync generateTemplates +project.eclipse.synchronizationTasks(generateTemplates)*/ diff --git a/velocity/src/main/java/io/github/skippyall/ruler/velocity/RulerVelocity.java b/velocity/src/main/java/io/github/skippyall/ruler/velocity/RulerVelocity.java new file mode 100644 index 0000000..5c82592 --- /dev/null +++ b/velocity/src/main/java/io/github/skippyall/ruler/velocity/RulerVelocity.java @@ -0,0 +1,51 @@ +package io.github.skippyall.ruler.velocity; + +import com.google.inject.Inject; +import com.mojang.brigadier.builder.LiteralArgumentBuilder; +import com.velocitypowered.api.command.BrigadierCommand; +import com.velocitypowered.api.command.CommandManager; +import com.velocitypowered.api.command.CommandSource; +import com.velocitypowered.api.event.Subscribe; +import com.velocitypowered.api.event.proxy.ProxyInitializeEvent; +import com.velocitypowered.api.plugin.Plugin; +import com.velocitypowered.api.plugin.annotation.DataDirectory; +import com.velocitypowered.api.proxy.ProxyServer; +import io.github.skippyall.ruler.Ruler; +import io.github.skippyall.ruler.command.Commands; +import io.github.skippyall.ruler.velocity.config.Registration; +import org.slf4j.Logger; + +import java.nio.file.Path; + +@Plugin( + id = "ruler-velocity", + name = "Ruler", + version = "1.0" +) +public class RulerVelocity { + public static Logger logger; + public static ProxyServer server; + public static Path configDirectory; + public static Commands commands; + public static RulerVelocity instance; + + @Inject + public RulerVelocity(ProxyServer server, Logger logger, @DataDirectory Path dir) { + RulerVelocity.server = server; + RulerVelocity.logger = logger; + RulerVelocity.configDirectory = dir; + instance = this; + } + + @Subscribe + public void onProxyInitialization(ProxyInitializeEvent event) { + Ruler.init(new VelocityPlatform()); + commands = new Commands<>(new VelocityCommandHelper()); + CommandManager manager = server.getCommandManager(); + for(LiteralArgumentBuilder builder : commands.getCommands()) { + BrigadierCommand command = new BrigadierCommand(builder); + manager.register(manager.metaBuilder(command).plugin(this).build(), command); + } + Registration.register(); + } +} diff --git a/velocity/src/main/java/io/github/skippyall/ruler/velocity/VelocityCommandHelper.java b/velocity/src/main/java/io/github/skippyall/ruler/velocity/VelocityCommandHelper.java new file mode 100644 index 0000000..a433895 --- /dev/null +++ b/velocity/src/main/java/io/github/skippyall/ruler/velocity/VelocityCommandHelper.java @@ -0,0 +1,12 @@ +package io.github.skippyall.ruler.velocity; + +import com.velocitypowered.api.command.CommandSource; +import io.github.skippyall.ruler.command.CommandHelper; +import net.kyori.adventure.audience.Audience; + +public class VelocityCommandHelper implements CommandHelper { + @Override + public Audience toAudience(CommandSource source) { + return source; + } +} diff --git a/velocity/src/main/java/io/github/skippyall/ruler/velocity/VelocityPlatform.java b/velocity/src/main/java/io/github/skippyall/ruler/velocity/VelocityPlatform.java new file mode 100644 index 0000000..bad9300 --- /dev/null +++ b/velocity/src/main/java/io/github/skippyall/ruler/velocity/VelocityPlatform.java @@ -0,0 +1,27 @@ +package io.github.skippyall.ruler.velocity; + +import io.github.skippyall.ruler.Platform; +import org.slf4j.Logger; + +import java.nio.file.Path; +import java.util.concurrent.CompletableFuture; +import java.util.function.Supplier; + +public class VelocityPlatform implements Platform { + @Override + public Path getConfigDirectory() { + return RulerVelocity.configDirectory; + } + + @Override + public Logger getLogger() { + return RulerVelocity.logger; + } + + @Override + public CompletableFuture runAsync(Supplier supplier) { + CompletableFuture future = new CompletableFuture<>(); + RulerVelocity.server.getScheduler().buildTask(RulerVelocity.instance, () -> future.complete(supplier.get())).schedule(); + return future; + } +} diff --git a/velocity/src/main/java/io/github/skippyall/ruler/velocity/config/Registration.java b/velocity/src/main/java/io/github/skippyall/ruler/velocity/config/Registration.java new file mode 100644 index 0000000..ad3edfb --- /dev/null +++ b/velocity/src/main/java/io/github/skippyall/ruler/velocity/config/Registration.java @@ -0,0 +1,12 @@ +package io.github.skippyall.ruler.velocity.config; + +import io.github.skippyall.ruler.config.condition.Conditions; +import net.kyori.adventure.key.Key; + +public class Registration { + public static void register() { + Conditions.register(Key.key("ruler", "server"), object -> + new ServerCondition(object.get("server").getAsString()) + ); + } +} diff --git a/velocity/src/main/java/io/github/skippyall/ruler/velocity/config/ServerCondition.java b/velocity/src/main/java/io/github/skippyall/ruler/velocity/config/ServerCondition.java new file mode 100644 index 0000000..a12ce37 --- /dev/null +++ b/velocity/src/main/java/io/github/skippyall/ruler/velocity/config/ServerCondition.java @@ -0,0 +1,41 @@ +package io.github.skippyall.ruler.velocity.config; + +import com.google.gson.JsonObject; +import com.velocitypowered.api.proxy.Player; +import com.velocitypowered.api.proxy.ServerConnection; +import io.github.skippyall.ruler.config.condition.Condition; +import net.kyori.adventure.audience.Audience; +import net.kyori.adventure.key.Key; + +import java.util.Optional; + +public class ServerCondition implements Condition { + private String server; + + public ServerCondition(String server) { + this.server = server; + } + + @Override + public boolean test(Audience audience) { + if(audience instanceof Player player) { + Optional server = player.getCurrentServer(); + if(server.isPresent()) { + return server.get().getServer().getServerInfo().getName().equals(this.server); + } + } + return false; + } + + @Override + public Key getType() { + return Key.key("ruler", "server"); + } + + @Override + public JsonObject serialize() { + JsonObject object = new JsonObject(); + object.addProperty("server", server); + return object; + } +}