addons editor commands

This commit is contained in:
Ronan committed 2026-11-09 20:40:17 +01:00
1 parent bd45e4cb87
commit 621f3a6876
12 files changed
+205 -24

No files matched your search

+6
View File
@@ -28,3 +28,9 @@ The wiki is available [here](../../../wiki)!
<br/>
<b><i><a href="https://www.spigotmc.org/resources/authors/superronancraft.13025/">Check out my other plugins!</a></i></b>
</p>
## Web configuration editor
Run `/rtp addons editor`, edit your config on MineCentral, and choose **Save and get sync command**. Apply it with `/betterrtp addons editorsync <token>`. Console and players with `betterrtp.addon.editor` (default: op) can use these commands.
Install the matching updated BetterRTP JAR as well: Addons shares its editor bridge. See [web editor setup](../docs/web-editor.md) for build, website migration, validation, and backup details.
+18 -12
View File
@@ -14,6 +14,17 @@
<maven.compiler.target>1.8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<profiles>
<profile>
<id>dev</id>
<build><plugins><plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.2.0</version>
<configuration><outputDirectory>../../../Java/plugins</outputDirectory></configuration>
</plugin></plugins></build>
</profile>
</profiles>
<build>
<resources>
<resource>
@@ -46,15 +57,6 @@
</execution>
</executions>
</plugin>
<plugin>
<!-- Local Server Building -->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.2.0</version>
<configuration>
<outputDirectory>../../../Java/plugins</outputDirectory>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
@@ -68,6 +70,10 @@
</build>
<repositories>
<repository>
<id>minecodes-repository-releases</id>
<url>https://repository.minecodes.pl/releases</url>
</repository>
<repository>
<id>spigot-repo</id>
<url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url>
@@ -75,7 +81,7 @@
<!-- PaperMC Repo -->
<repository>
<id>papermc</id>
<url>https://papermc.io/repo/repository/maven-public/</url>
<url>https://repo.papermc.io/repository/maven-public/</url>
</repository>
<!-- ProtocolLib Repo -->
<repository>
@@ -102,14 +108,14 @@
<dependency>
<groupId>io.papermc</groupId>
<artifactId>paperlib</artifactId>
<version>1.0.5</version>
<version>1.0.8</version>
<scope>compile</scope>
</dependency>
<!-- BetterRTP -->
<dependency>
<groupId>me.SuperRonanCraft</groupId>
<artifactId>BetterRTP</artifactId>
<version>LATEST</version>
<version>3.6.13</version>
<scope>provided</scope>
</dependency>
<!-- ProtocolLib -->
@@ -33,6 +33,14 @@ public class AddonsCommand implements RTPCommand, RTPCommandHelpable {
@Override
public void execute(CommandSender sendi, String label, String[] args) {
if (args.length >= 2 && (args[1].equalsIgnoreCase("editor") || args[1].equalsIgnoreCase("editorsync"))) {
Main plugin = Main.getInstance();
if (!plugin.canEdit(sendi)) { sendi.sendMessage("§cYou need betterrtp.addon.editor permission."); return; }
if (args[1].equalsIgnoreCase("editor") && args.length == 2) plugin.getEditorBridge().upload(sendi);
else if (args[1].equalsIgnoreCase("editorsync") && args.length == 3) plugin.getEditorBridge().redeem(sendi, args[2]);
else sendi.sendMessage("§eUsage: /" + label + " addons " + (args[1].equalsIgnoreCase("editor") ? "editor" : "editorsync <token>"));
return;
}
if (args.length == 2) {
for (AddonCmds cmds : AddonCmds.values()) {
if (cmds.name().equalsIgnoreCase(args[1])) {
@@ -44,6 +52,7 @@ public class AddonsCommand implements RTPCommand, RTPCommandHelpable {
} else {
List<String> list = new ArrayList<>();
list.add(MessagesHelp.PREFIX.get());
addEditorHelp(sendi, label, list);
for (AddonsHandler.Addons addon : Main.getInstance().getAddonsHandler().addons) {
RTPCommand cmd = addon.getCmd();
if (cmd instanceof RTPCommandHelpable)
@@ -57,6 +66,10 @@ public class AddonsCommand implements RTPCommand, RTPCommandHelpable {
@Override
public List<String> tabComplete(CommandSender sendi, String[] args) {
List<String> list = new ArrayList<>();
if (args.length == 2 && Main.getInstance().canEdit(sendi)) {
for (String command : new String[] { "editor", "editorsync" })
if (command.startsWith(args[1].toLowerCase(Locale.ROOT))) list.add(command);
}
if (args.length == 2)
for (AddonCmds cmds : AddonCmds.values()) {
if (cmds.name().toLowerCase().startsWith(args[1].toLowerCase()))
@@ -65,6 +78,13 @@ public class AddonsCommand implements RTPCommand, RTPCommandHelpable {
return list;
}
public static void addEditorHelp(CommandSender sender, String label, List<String> list) {
if (Main.getInstance().canEdit(sender)) {
list.add("§7- §e/" + label + " addons editor §7- Open the Addons web editor");
list.add("§7- §e/" + label + " addons editorsync <token> §7- Apply a saved Addons config");
}
}
@Override
public PermissionNode permission() {
return PermissionNode.USE;
@@ -30,7 +30,8 @@ public class AddonsHandler {
//addonCount++;
}
//Main.getInstance().getLogger().log(Level.INFO, addonCount + "/" + Addons.values().length + " addons were enabled!");
HelperRTP_Command.registerCommand(cmd, false);
if (!BetterRTP.getInstance().getCmd().commands.contains(cmd))
HelperRTP_Command.registerCommand(cmd, false);
}
public void unload() {
@@ -17,15 +17,26 @@ public class Main extends JavaPlugin {
public final AddonMessages msgs = new AddonMessages();
private final ReloadListener reloadListener = new ReloadListener();
@Getter
private me.SuperRonanCraft.BetterRTP.references.web.editor.EditorBridge editorBridge;
public boolean canEdit(org.bukkit.command.CommandSender sender) {
return !(sender instanceof org.bukkit.entity.Player) || sender.hasPermission("betterrtp.addon.editor");
}
@Override
public void onEnable() {
instance = this;
Bukkit.getPluginManager().registerEvents(reloadListener, this);
load();
editorBridge = new me.SuperRonanCraft.BetterRTP.references.web.editor.EditorBridge(
this, me.SuperRonanCraft.BetterRTP.versions.AsyncHandler::sync, sender -> load(),
this::canEdit, () -> Files.FILETYPE.CONFIG.getConfig().saveToString(), "betterrtp-addons");
}
@Override
public void onDisable() {
if (editorBridge != null) editorBridge.close();
addonsHandler.unload();
}
@@ -21,6 +21,7 @@ public class AddonsCommand_Help implements AddonsCommands, RTPCommandHelpable {
public void execute(CommandSender sendi, String label, String[] args) {
List<String> list = new ArrayList<>();
list.add(MessagesHelp.PREFIX.get());
AddonsCommand.addEditorHelp(sendi, label, list);
for (AddonsCommand.AddonCmds cmds : AddonsCommand.AddonCmds.values()) {
if (cmds.cmd instanceof RTPCommandHelpable)
list.add(((RTPCommandHelpable) cmds.cmd).getHelp().replace("%command%", label));
@@ -7,6 +7,9 @@ depend: [BetterRTP]
softdepend: [ProtocolLib]
permissions:
betterrtp.addon.editor:
description: Open and sync the BetterRTP Addons web editor
default: op
betterrtp.addon.portals:
description: Ability to use the portals addon commands
+24 -1
View File
@@ -1,4 +1,27 @@
# Free command editor
# Plugin web editors
BetterRTP and BetterRTP Addons share the form/YAML editor, private config library, 24-hour uploads, and single-use 15-minute sync commands.
| Plugin | Open server config | Apply saved config | Permission (default: op) | Website |
| --- | --- | --- | --- | --- |
| BetterRTP | `/rtp editor` | `/betterrtp editorsync <token>` | `betterrtp.editor` | `/editor/betterrtp` |
| BetterRTP Addons | `/rtp addons editor` | `/betterrtp addons editorsync <token>` | `betterrtp.addon.editor` | `/editor/betterrtp-addons` |
Console can use both commands. Addons sync backs up and replaces **BetterRTPAddons/config.yml**, then reloads the addons. It does not write BetterRTP's config or addon databases. Addons uses the editor bridge and website build metadata from the installed BetterRTP JAR, so install both updated JARs together.
## Addons deployment
1. Deploy the website with `pnpm db:deploy` to apply `0017_addons_editor` before serving the updated editor API. Existing tokens default to BetterRTP. The migration binds the existing `betterrtp-addons` catalog listing to its stable editor identity; its ID, release history, and premium classification remain unchanged. Later slug renames retain editor support.
2. Build from the BetterRTP repository: `mvn clean install`, then `mvn -f BetterRTPAddons/pom.xml clean package`. The JARs are in `target/` and `BetterRTPAddons/target/`. The Addons `dev` profile optionally copies its JAR to the local plugins directory.
3. Install both JARs and restart the Minecraft server. Open `/rtp addons editor`, edit a setting, save online, and run the returned command. Check Minecraft's apply confirmation and the Addons `editor-backups` folder.
Uploads, sync payloads, login recovery drafts, and My Configs are scoped to their plugin. Redeeming an Addons token using BetterRTP's command is rejected without consuming it. Existing expiry/cleanup rules apply to both plugins. The editor is free even when the catalog plugin requires premium to download.
The Addons form supports feature toggles, command/lore lists, menu worlds, and flashback warning times/messages. Validation preserves fixed keys/types, blocks Language-File changes, and checks menu lines/slots, timers, and stick quantities. The receiving server also validates materials and the logger date format. Quoted Minecraft color codes are accepted while YAML tags, aliases, and Bukkit object serialization remain blocked.
Run `mvn -f tests/editor/pom.xml test` and the website's `pnpm test`, `pnpm typecheck`, and `pnpm db:validate`. Automated checks cover default Addons YAML, numeric warning keys, collection edits, backups, plugin isolation, one-use sync, migration binding, and separate snapshot allowances. A live Minecraft upload/apply/reload still needs a server smoke test.
## BetterRTP command editor
`/rtp editor` uploads `config.yml` and loaded world names, then returns an independent eight-character editor token valid for 24 hours. Run the command from console or with `betterrtp.editor` (default: op). No login or premium is required. There is no active-editor slot, cancellation command, or plugin-controlled token lifetime. Running the command again creates another independent upload. `/rtp edit` is unchanged.
@@ -43,7 +43,10 @@ public class Commands {
//Command Event
Bukkit.getServer().getPluginManager().callEvent(event);
if (!event.isCancelled()) {
BetterRTP.debug(sendi.getName() + " executed: /" + label + " " + String.join(" ", args));
boolean editorSync = args[0].equalsIgnoreCase("editorsync") ||
(args[0].equalsIgnoreCase("addons") && args.length > 1 && args[1].equalsIgnoreCase("editorsync"));
BetterRTP.debug(sendi.getName() + " executed: /" + label + " " +
(editorSync ? (args[0].equalsIgnoreCase("addons") ? "addons editorsync [redacted]" : "editorsync [redacted]") : String.join(" ", args)));
cmd.execute(sendi, label, args);
Bukkit.getServer().getPluginManager().callEvent(new RTP_CommandEvent_After(sendi, cmd));
}
@@ -36,6 +36,8 @@ public final class EditorBridge {
return website;
}
private final JavaPlugin plugin;
private final String editorPlugin;
private final String editorName;
private final Consumer<Runnable> sync;
private final Consumer<CommandSender> reload;
private final Predicate<CommandSender> allowed;
@@ -48,6 +50,13 @@ public final class EditorBridge {
public EditorBridge(JavaPlugin plugin, Consumer<Runnable> sync, Consumer<CommandSender> reload,
Predicate<CommandSender> allowed, Supplier<String> loadedConfig) {
this(plugin, sync, reload, allowed, loadedConfig, "betterrtp");
}
public EditorBridge(JavaPlugin plugin, Consumer<Runnable> sync, Consumer<CommandSender> reload,
Predicate<CommandSender> allowed, Supplier<String> loadedConfig, String editorPlugin) {
if (!Arrays.asList("betterrtp", "betterrtp-addons").contains(editorPlugin)) throw new IllegalArgumentException("Unknown editor plugin");
this.editorPlugin = editorPlugin;
this.editorName = editorPlugin.equals("betterrtp") ? "BetterRTP" : "BetterRTP Addons";
this.plugin = plugin;
this.sync = sync;
this.reload = reload;
@@ -66,12 +75,13 @@ public final class EditorBridge {
// Snapshot loaded worlds on the command thread, before starting HTTP work.
List<String> worlds = new ArrayList<>();
for (org.bukkit.World world : Bukkit.getWorlds()) worlds.add(world.getName());
sender.sendMessage("§7Uploading a private BetterRTP editor config…");
sender.sendMessage("§7Uploading a private " + editorName + " editor config…");
worker.execute(() -> {
try {
JsonObject body = new JsonObject(); body.addProperty("protocol", 4);
body.addProperty("playerId", upload.player == null ? null : upload.player.toString());
body.addProperty("configFile", "config.yml");
body.addProperty("plugin", editorPlugin);
JsonArray availableWorlds = new JsonArray();
for (String world : worlds) availableWorlds.add(new JsonPrimitive(world));
body.add("worlds", availableWorlds);
@@ -84,10 +94,10 @@ public final class EditorBridge {
if (stopped) return;
CommandSender recipient = recipient(upload);
if (recipient == null || !allowed.test(recipient)) return;
String url = WEBSITE + "/editor/betterrtp?token=" + browserToken;
String url = WEBSITE + "/editor/" + editorPlugin + "?token=" + browserToken;
recipient.sendMessage("§ePrivate editor link: expires in 24 hours. Save online, then run the sync command here. Do not share it.");
if (recipient instanceof Player) {
TextComponent link = new TextComponent("§a[Open BetterRTP editor]");
TextComponent link = new TextComponent("§a[Open " + editorName + " editor]");
link.setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, url));
((Player) recipient).spigot().sendMessage(link);
} else recipient.sendMessage(url);
@@ -149,7 +159,7 @@ public final class EditorBridge {
if (stopped) return;
if (System.currentTimeMillis() >= tokenExpires) throw new IOException("Sync token expired before apply.");
CommandSender sender = executor == null ? Bukkit.getConsoleSender() : Bukkit.getPlayer(executor);
if (sender == null || !allowed.test(sender)) throw new IOException("The syncing player must be online and still have betterrtp.editor.");
if (sender == null || !allowed.test(sender)) throw new IOException("The syncing player must be online and still have editor permission.");
Path backup = EditorConfig.apply(configPath(), original.getBytes(StandardCharsets.UTF_8), edited, () -> {
reload.accept(sender);
String loaded = loadedConfig.get();
@@ -159,7 +169,7 @@ public final class EditorBridge {
});
sender.sendMessage("§aEditor changes applied and reloaded. Backup: " + backup.getFileName());
} catch (EditorConfig.ReloadFailure error) {
message(executor, "Configuration saved, but reload failed. The new file remains in place. Check the console and reload BetterRTP.");
message(executor, "Configuration saved, but reload failed. The new file remains in place. Check the console and reload the plugin.");
plugin.getLogger().warning("Editor config was written but reload failed; no rollback was performed.");
} catch (Exception error) {
message(executor, "Sync not applied: " + error.getMessage());
@@ -173,6 +183,7 @@ public final class EditorBridge {
connection.setRequestProperty("X-Editor-Actor", "plugin");
connection.setRequestProperty("User-Agent", "BetterRTP-Editor/4");
connection.setRequestProperty("X-Editor-Protocol", "4");
connection.setRequestProperty("X-Editor-Plugin", editorPlugin);
if (syncToken != null) {
connection.setRequestProperty("X-Editor-Sync-Token", syncToken);
}
@@ -14,12 +14,17 @@ public final class EditorConfig {
private static final Pattern TOKENS = Pattern.compile("(^|[\\s\\[\\]{},])[!&*]", Pattern.MULTILINE);
private EditorConfig() { }
private static String withoutQuotedScalars(String text) {
// Only complete, single-line quoted scalars: Minecraft color codes are text, not YAML anchors.
return text.replaceAll("\"(?:\\\\[^\\r\\n]|[^\"\\\\\\r\\n])*\"|'(?:''|[^'\\r\\n])*'", "quoted");
}
public static YamlConfiguration parse(String text) throws Exception {
// Bukkit supports object deserialization through the reserved == key. Reject equals
// and encoded character escapes before invoking its parser, not only after parsing.
if (text.indexOf('=') >= 0 || Pattern.compile("\\\\[xuU]").matcher(text).find())
if (text.indexOf("==") >= 0 || Pattern.compile("\\\\[xuU]").matcher(text).find())
throw new IOException("Object serialization markers and encoded character escapes are not supported.");
if (text.getBytes(StandardCharsets.UTF_8).length > MAX_BYTES || TOKENS.matcher(text).find())
if (text.getBytes(StandardCharsets.UTF_8).length > MAX_BYTES || TOKENS.matcher(withoutQuotedScalars(text)).find())
throw new IOException("Configuration too large, or YAML tags/anchors/aliases present.");
int lines = 0, flow = 0;
for (String line : text.split("\\n")) {
@@ -29,7 +34,10 @@ public final class EditorConfig {
if (flow > 128) throw new IOException("Too many flow collections.");
YamlConfiguration parsed = new YamlConfiguration();
parsed.loadFromString(text);
if (!parsed.isConfigurationSection("Settings") || !parsed.isConfigurationSection("Default"))
if (parsed.isConfigurationSection("Flashback")) {
for (String section : Arrays.asList("Flashback", "Logger", "Portals", "ExtraEffects", "MagicStick", "Commands", "Parties", "RTPMenu"))
if (!parsed.isConfigurationSection(section)) throw new IOException("Missing addon section: " + section);
} else if (!parsed.isConfigurationSection("Settings") || !parsed.isConfigurationSection("Default"))
throw new IOException("Missing Settings or Default section.");
return parsed;
}
@@ -38,7 +46,11 @@ public final class EditorConfig {
YamlConfiguration before = parse(original), after = parse(edited);
if (!Objects.equals(before.get("Language-File"), after.get("Language-File")))
throw new IOException("Change Language-File locally, not through the web editor.");
compare(before, after, "config", 0, (Map<?, ?>) normalize(after.get("Default")));
compare(before, after, "config", 0, (Map<?, ?>) normalize(after.get(after.isConfigurationSection("Flashback") ? "RTPMenu" : "Default")));
if (after.isConfigurationSection("Flashback")) {
new java.text.SimpleDateFormat(after.getString("Logger.Format"));
org.bukkit.Material.valueOf(after.getString("MagicStick.Item.Material").toUpperCase(Locale.ROOT));
}
}
private static Object normalize(Object value) {
@@ -48,6 +60,9 @@ public final class EditorConfig {
private static void compare(Object oldValue, Object newValue, String path, int depth, Map<?, ?> defaults) throws IOException {
if (depth > 32) throw new IOException("Configuration nesting is too deep.");
oldValue = normalize(oldValue); newValue = normalize(newValue);
if (path.equals("config.RTPMenu.WorldList") || path.equals("config.Flashback.Timer.Warnings")) {
addonEntries(oldValue, newValue, path, depth, defaults); return;
}
if (Arrays.asList("config.BlacklistedBlocks", "config.DisabledWorlds", "config.Default.Biomes").contains(path)) {
stringList(newValue, path); return;
}
@@ -78,6 +93,9 @@ public final class EditorConfig {
if (!Double.isFinite(n) || n < Integer.MIN_VALUE || n > Integer.MAX_VALUE ||
((oldValue instanceof Integer || oldValue instanceof Long) && n != Math.rint(n)))
throw new IOException("Invalid number: " + path);
if (path.equals("config.RTPMenu.Lines") && (n < 1 || n > 6)) throw new IOException("Menu lines must be 1–6.");
if (Arrays.asList("config.RTPMenu.AutoRefresh", "config.Flashback.Timer.Delay").contains(path) && n < 0) throw new IOException("Negative time: " + path);
if (path.equals("config.MagicStick.GiveFirstJoin.Amount") && (n < 1 || n > 64)) throw new IOException("Stick amount must be 1–64.");
if (path.endsWith("Radius") && (n < 0 || n > 30000000)) throw new IOException("Invalid radius: " + path);
if ((path.endsWith(".Time") || path.endsWith(".LockAfter")) && n < 0) throw new IOException("Negative time: " + path);
if (path.endsWith(".PreloadRadius") && (n < 0 || n > 16)) throw new IOException("PreloadRadius must be 0–16.");
@@ -91,6 +109,56 @@ public final class EditorConfig {
} else if (!Objects.equals(oldValue, newValue)) throw new IOException("Unsupported setting: " + path);
}
private static void addonEntries(Object before, Object after, String path, int depth, Map<?, ?> defaults) throws IOException {
boolean warnings = path.endsWith("Warnings");
Map<String, Object> old = addonMap(before, path), next = addonMap(after, path);
for (Map.Entry<String, Object> entry : next.entrySet()) {
String key = entry.getKey(); Object value = normalize(entry.getValue());
if (warnings) {
try {
if (!key.matches("[0-9]+") || Long.parseLong(key) > Integer.MAX_VALUE || !(value instanceof String))
throw new IOException("Invalid warning: " + key);
} catch (NumberFormatException e) { throw new IOException("Invalid warning time."); }
} else {
if (!(value instanceof Map)) throw new IOException("Expected menu world settings.");
Map<?, ?> settings = (Map<?, ?>) value;
Object previousValue = normalize(old.get(key));
Map<?, ?> previous = previousValue instanceof Map ? (Map<?, ?>) previousValue : Collections.emptyMap();
Map<String, Object> schema = new LinkedHashMap<>();
schema.put("Name", ""); schema.put("Item", "MAP"); schema.put("Slot", 0); schema.put("Lore", Collections.emptyList());
for (Map.Entry<?, ?> field : settings.entrySet()) {
String name = String.valueOf(field.getKey());
if (!schema.containsKey(name) && !previous.containsKey(name)) throw new IOException("Unknown menu setting: " + name);
compare(schema.containsKey(name) ? schema.get(name) : previous.get(name), field.getValue(), path + "." + key + "." + name, depth + 1, defaults);
}
for (Object name : previous.keySet())
if (!schema.containsKey(name) && !settings.containsKey(name)) throw new IOException("Keep existing menu setting: " + name);
Object slot = settings.containsKey("Slot") ? settings.get("Slot") : 0;
if (!(slot instanceof Number) || ((Number) slot).intValue() < 0 || ((Number) slot).intValue() >= ((Number) defaults.get("Lines")).intValue() * 9)
throw new IOException("Menu slot must fit within the configured lines.");
if (settings.containsKey("Item")) {
try { org.bukkit.Material.valueOf(((String) settings.get("Item")).toUpperCase(Locale.ROOT)); }
catch (IllegalArgumentException e) { throw new IOException("Unknown menu material."); }
}
}
}
}
private static Map<String, Object> addonMap(Object value, String path) throws IOException {
if (!(value instanceof List) || ((List<?>) value).size() > 1000) throw new IOException("Expected named list: " + path);
Map<String, Object> result = new LinkedHashMap<>();
for (Object item : (List<?>) value) {
item = normalize(item);
if (!(item instanceof Map) || ((Map<?, ?>) item).isEmpty()) throw new IOException("Expected named entry: " + path);
for (Map.Entry<?, ?> entry : ((Map<?, ?>) item).entrySet()) {
String key = String.valueOf(entry.getKey());
if (!validName(key) || result.containsKey(key)) throw new IOException("Invalid or duplicate name: " + path);
result.put(key, entry.getValue());
}
}
return result;
}
private static boolean validName(String value) {
return !value.trim().isEmpty() && value.equals(value.trim()) && value.length() <= 100 && !Pattern.compile("[\\x00-\\x1f]").matcher(value).find();
}
@@ -10,6 +10,34 @@ public class EditorConfigTest {
try { EditorConfig.validate(original, edited); fail("Expected rejection"); }
catch (java.io.IOException expected) { }
}
private String addons() throws Exception {
return new String(Files.readAllBytes(Paths.get("../../BetterRTPAddons/src/main/resources/config.yml")), StandardCharsets.UTF_8);
}
@Test public void acceptsAddonDefaultsAndCollectionEdits() throws Exception {
String before = addons();
EditorConfig.validate(before, before);
String after = before.replace("600: ", "300: ").replace("world_nether:", "survival:").replace("Lines: 3", "Lines: 4");
EditorConfig.validate(before, after);
Path dir = Files.createTempDirectory("addons-editor");
Path file = dir.resolve("config.yml");
Files.write(file, before.getBytes(StandardCharsets.UTF_8));
Path backup = EditorConfig.apply(file, before.getBytes(StandardCharsets.UTF_8), after, () -> {});
assertEquals(before, new String(Files.readAllBytes(backup), StandardCharsets.UTF_8));
assertTrue(EditorConfig.equivalent(after, new String(Files.readAllBytes(file), StandardCharsets.UTF_8)));
}
@Test public void rejectsInvalidAddonSettingsAndUnsafeYaml() throws Exception {
String before = addons();
for (String after : new String[] {
before.replace("Lines: 3", "Lines: 7"), before.replace("Slot: 3", "Slot: 27"),
before.replace("AutoRefresh: 0", "AutoRefresh: -1"), before.replace("600:", "bad:"),
before.replace("en.yml", "other.yml"), before + "Bad: &anchor value\n",
before + "Bad: !!java/object something\n", before + "Bad:\n ==: org.bukkit.inventory.ItemStack\n" }) {
try { EditorConfig.validate(before, after); fail("Expected addon validation failure"); }
catch (java.io.IOException expected) { }
}
try { EditorConfig.validate(original, before); fail("Expected cross-plugin failure"); }
catch (java.io.IOException expected) { }
}
@Test public void acceptsValidChange() throws Exception { EditorConfig.validate(original, original.replace("1000", "2000")); }
@Test public void rejectsWrongTypeAndRange() throws Exception {
rejected(original.replace("1000", "false"));