diff --git a/core/src/main/java/art/arcane/iris/core/tooling/CommandFailure.java b/core/src/main/java/art/arcane/iris/core/tooling/CommandFailure.java new file mode 100644 index 000000000..b38cf4f04 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/tooling/CommandFailure.java @@ -0,0 +1,39 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.tooling; + +import java.util.Optional; + +/** A problem with the line, worded for the sender, and optionally how to write the command. */ +final class CommandFailure extends Exception { + private final String usage; + + CommandFailure(String message) { + this(message, null); + } + + CommandFailure(String message, String usage) { + super(message, null, false, false); + this.usage = usage; + } + + Optional usage() { + return Optional.ofNullable(usage); + } +} diff --git a/core/src/main/java/art/arcane/iris/core/tooling/CommandLine.java b/core/src/main/java/art/arcane/iris/core/tooling/CommandLine.java new file mode 100644 index 000000000..976600de4 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/tooling/CommandLine.java @@ -0,0 +1,44 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.tooling; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +/** A line sent to the dispatcher without its {@code pack=} option, which may stand anywhere in the line. */ +record CommandLine(Optional packName, List words) { + static final String PACK_OPTION = "pack="; + + static CommandLine of(List tokens) throws CommandFailure { + List words = new ArrayList<>(); + Optional packName = Optional.empty(); + for (String token : tokens) { + if (!token.startsWith(PACK_OPTION)) { + words.add(token); + continue; + } + if (packName.isPresent()) { + throw new CommandFailure("Name one pack only"); + } + packName = Optional.of(token.substring(PACK_OPTION.length())); + } + return new CommandLine(packName, words); + } +} diff --git a/core/src/main/java/art/arcane/iris/core/tooling/CommandRun.java b/core/src/main/java/art/arcane/iris/core/tooling/CommandRun.java new file mode 100644 index 000000000..4139c3252 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/tooling/CommandRun.java @@ -0,0 +1,81 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package art.arcane.iris.core.tooling; + +import com.volmit.resource.PlatformRegistries; +import com.volmit.tooling.Argument; +import com.volmit.tooling.CommandContext; +import com.volmit.tooling.Sender; +import com.volmit.tooling.ToolPack; +import com.volmit.world.PackWorld; + +import java.util.IdentityHashMap; +import java.util.Map; +import java.util.Optional; + +/** One run of a command, or one completion: the arguments parsed so far, and what the command runs against. */ +final class CommandRun implements CommandContext { + private final Sender sender; + private final ToolPack pack; + private final Optional world; + private final Optional platform; + private final Map, Object> values = new IdentityHashMap<>(); + + CommandRun(Sender sender, ToolPack pack, Optional world, Optional platform) { + this.sender = sender; + this.pack = pack; + this.world = world; + this.platform = platform; + } + + void put(Argument argument, T value) { + values.put(argument, value); + } + + @Override + @SuppressWarnings("unchecked") + public T get(Argument argument) { + if (values.containsKey(argument)) { + return (T) values.get(argument); + } + if (argument.isOptional()) { + return argument.fallback(); + } + throw new IllegalStateException("The sender gave no value for " + argument.name() + " yet"); + } + + @Override + public Sender sender() { + return sender; + } + + @Override + public ToolPack pack() { + return pack; + } + + @Override + public Optional world() { + return world; + } + + @Override + public Optional platform() { + return platform; + } +} diff --git a/core/src/main/java/art/arcane/iris/core/tooling/IrisObjectCodec.java b/core/src/main/java/art/arcane/iris/core/tooling/IrisObjectCodec.java new file mode 100644 index 000000000..fd78d7cd5 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/tooling/IrisObjectCodec.java @@ -0,0 +1,81 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.tooling; + +import art.arcane.iris.core.modules.BlockEntities; +import art.arcane.iris.core.modules.ObjectGeometry; +import art.arcane.iris.core.modules.PlatformBlockStates; +import art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.iris.util.common.data.B; +import art.arcane.volmlib.util.math.IrisBlockVector; +import com.volmit.geometry.BlockBox; +import com.volmit.object.GeneratedObject; +import com.volmit.object.ObjectBlock; +import com.volmit.tooling.ObjectCodec; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; + +/** The {@code .iob} format of Iris's {@link IrisObject}: the format the host reads below a pack's {@code objects} folder. */ +public final class IrisObjectCodec implements ObjectCodec { + private static final String EXTENSION = ".iob"; + + @Override + public String extension() { + return EXTENSION; + } + + @Override + public byte[] encode(GeneratedObject object) throws IOException { + if (!object.markers().isEmpty()) { + throw new IOException("The " + EXTENSION + " format holds no markers, and the object has " + object.markers().size()); + } + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + irisObjectOf(object).write(bytes); + return bytes.toByteArray(); + } + + @Override + public GeneratedObject decode(byte[] bytes) throws IOException { + IrisObject object = new IrisObject(); + try { + object.read(new ByteArrayInputStream(bytes)); + } catch (IOException failure) { + throw failure; + } catch (Throwable failure) { + throw new IOException("Cannot read an " + EXTENSION + " object: " + failure.getMessage(), failure); + } + return ObjectGeometry.of(object); + } + + /** Iris keys an object's blocks by their offset from its center, so the local positions are the keys. */ + private static IrisObject irisObjectOf(GeneratedObject object) { + BlockBox bounds = object.bounds(); + IrisObject irisObject = new IrisObject( + bounds.maxX() - bounds.minX(), bounds.maxY() - bounds.minY(), bounds.maxZ() - bounds.minZ()); + PlatformBlockStates states = new PlatformBlockStates(B::getState); + for (ObjectBlock block : object.blocks()) { + IrisBlockVector offset = new IrisBlockVector(block.position().x(), block.position().y(), block.position().z()); + irisObject.blocks.put(offset, states.toPlatform(block.state())); + block.blockEntity().ifPresent(entity -> irisObject.states.put(offset.clone(), BlockEntities.tileOf(entity))); + } + return irisObject; + } +} diff --git a/core/src/main/java/art/arcane/iris/core/tooling/IrisServedPack.java b/core/src/main/java/art/arcane/iris/core/tooling/IrisServedPack.java new file mode 100644 index 000000000..17704e3ec --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/tooling/IrisServedPack.java @@ -0,0 +1,76 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.tooling; + +import art.arcane.iris.core.loader.IrisData; +import com.volmit.ModuleLog; +import com.volmit.host.CommandRegistration; +import com.volmit.tooling.ToolPack; + +import java.nio.file.Path; +import java.util.List; +import java.util.Objects; + +/** A pack Iris serves from its {@link IrisData}; two instances are equal when they read one pack folder. */ +public final class IrisServedPack implements ServedPack { + private final IrisData data; + + public IrisServedPack(IrisData data) { + this.data = Objects.requireNonNull(data, "data"); + } + + @Override + public String name() { + return data.getDataFolder().getName(); + } + + @Override + public List commands() { + try { + return data.getModules().pack().catalog().commands(); + } catch (RuntimeException modulesFailed) { + throw new IllegalStateException("The modules of pack " + name() + " did not load: " + modulesFailed.getMessage(), + modulesFailed); + } + } + + @Override + public ToolPack toolPack(ModuleLog log) { + return new IrisToolPack(data, log); + } + + @Override + public boolean equals(Object other) { + return other instanceof IrisServedPack served && folder().equals(served.folder()); + } + + @Override + public int hashCode() { + return folder().hashCode(); + } + + @Override + public String toString() { + return "pack " + name(); + } + + private Path folder() { + return data.getDataFolder().toPath().toAbsolutePath().normalize(); + } +} diff --git a/core/src/main/java/art/arcane/iris/core/tooling/IrisToolPack.java b/core/src/main/java/art/arcane/iris/core/tooling/IrisToolPack.java new file mode 100644 index 000000000..921cbb796 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/tooling/IrisToolPack.java @@ -0,0 +1,108 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.tooling; + +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.core.modules.IrisValidationContext; +import art.arcane.iris.spi.IrisPlatforms; +import com.volmit.ModuleLog; +import com.volmit.config.PackSettings; +import com.volmit.resource.PackResources; +import com.volmit.tooling.ObjectCodec; +import com.volmit.tooling.PackEdit; +import com.volmit.tooling.ToolPack; + +import java.io.File; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Objects; + +/** + * One pack as a command of one module sees it. An edit holds the pack's {@link IrisData}, which a hotload also takes, so + * a hotload waits for the edit and a second edit waits for the first. Built-in modules that still read Iris's own pack + * data reach it through {@link #dataOf(ToolPack)}. + */ +public final class IrisToolPack implements ToolPack { + static final String EXPORTS_FOLDER = "exports"; + + private final IrisData data; + private final ModuleLog log; + private final ObjectCodec objects = new IrisObjectCodec(); + + public IrisToolPack(IrisData data, ModuleLog log) { + this.data = Objects.requireNonNull(data, "data"); + this.log = Objects.requireNonNull(log, "log"); + } + + /** The pack data behind {@code pack}, for built-in modules compiled into Iris. */ + public static IrisData dataOf(ToolPack pack) { + if (!(pack instanceof IrisToolPack irisPack)) { + throw new IllegalArgumentException("Built-in tools run on packs Iris serves, not " + pack); + } + return irisPack.data; + } + + @Override + public PackResources resources() { + return data.getPackResources(); + } + + @Override + public PackSettings settings() { + return IrisValidationContext.forPack(data).settings(); + } + + @Override + public T edit(PackEdit edit) throws IOException { + synchronized (data) { + T result = edit.apply(data.getDataFolder().toPath()); + data.invalidateStructureResources(); + return result; + } + } + + /** The workspace's {@code exports} folder, one folder for each pack, beside the packs themselves. */ + @Override + public Path outputFolder() { + File packsFolder = IrisPlatforms.get().packsFolder(); + Path output = packsFolder.toPath().resolve(EXPORTS_FOLDER).resolve(data.getDataFolder().getName()); + try { + return Files.createDirectories(output).toAbsolutePath().normalize(); + } catch (IOException failure) { + throw new UncheckedIOException("Cannot create the export folder " + output, failure); + } + } + + @Override + public ObjectCodec objects() { + return objects; + } + + @Override + public ModuleLog log() { + return log; + } + + @Override + public String toString() { + return "pack " + data.getDataFolder().getName(); + } +} diff --git a/core/src/main/java/art/arcane/iris/core/tooling/LocatedCommand.java b/core/src/main/java/art/arcane/iris/core/tooling/LocatedCommand.java new file mode 100644 index 000000000..664c95df8 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/tooling/LocatedCommand.java @@ -0,0 +1,75 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.tooling; + +import com.volmit.host.CommandRegistration; +import com.volmit.tooling.Argument; +import com.volmit.tooling.Command; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +/** + * The command the leading words of a line name below a module's root, and the words left over as its arguments. + * A word that names a sub-command always selects it. + */ +record LocatedCommand(CommandRegistration root, Command command, List path, List arguments) { + static Optional locate(List roots, List words) { + Optional root = roots.stream() + .filter(candidate -> candidate.command().answersTo(words.getFirst())) + .findFirst(); + if (root.isEmpty()) { + return Optional.empty(); + } + Command command = root.get().command(); + List path = new ArrayList<>(List.of(command.name())); + int consumed = 1; + while (consumed < words.size()) { + Optional child = childAnsweringTo(command, words.get(consumed)); + if (child.isEmpty()) { + break; + } + command = child.get(); + path.add(command.name()); + consumed++; + } + return Optional.of(new LocatedCommand(root.get(), command, path, words.subList(consumed, words.size()))); + } + + String pathText() { + return String.join(" ", path); + } + + String usage() { + return usageOf(path, command); + } + + static String usageOf(List path, Command command) { + StringBuilder usage = new StringBuilder(String.join(" ", path)); + for (Argument argument : command.arguments()) { + usage.append(argument.isOptional() ? " [" : " <").append(argument.name()).append(argument.isOptional() ? "]" : ">"); + } + return usage.toString(); + } + + private static Optional childAnsweringTo(Command command, String word) { + return command.children().stream().filter(child -> child.answersTo(word)).findFirst(); + } +} diff --git a/core/src/main/java/art/arcane/iris/core/tooling/PackDirectory.java b/core/src/main/java/art/arcane/iris/core/tooling/PackDirectory.java new file mode 100644 index 000000000..c902a3d1a --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/tooling/PackDirectory.java @@ -0,0 +1,58 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.tooling; + +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.core.pack.PackDirectoryResolver; +import art.arcane.iris.spi.IrisPlatforms; + +import java.io.File; +import java.util.List; +import java.util.Optional; + +/** The packs a line may name with {@code pack=}. */ +public interface PackDirectory { + /** The pack folder named {@code name}; empty when there is none. */ + Optional find(String name); + + /** The names of the pack folders, sorted. */ + List names(); + + /** The packs below the packs folder of the bound platform; the folder the exports go to is no pack. */ + static PackDirectory ofBoundPlatform() { + return new PackDirectory() { + @Override + public Optional find(String name) { + File folder = PackDirectoryResolver.resolveExisting(IrisPlatforms.get().packsFolderNoCreate(), name); + if (folder == null || folder.getName().equals(IrisToolPack.EXPORTS_FOLDER)) { + return Optional.empty(); + } + return Optional.of(new IrisServedPack(IrisData.get(folder))); + } + + @Override + public List names() { + return PackDirectoryResolver.listVisiblePackDirectories(IrisPlatforms.get().packsFolderNoCreate()).stream() + .map(File::getName) + .filter(name -> !name.equals(IrisToolPack.EXPORTS_FOLDER)) + .toList(); + } + }; + } +} diff --git a/core/src/main/java/art/arcane/iris/core/tooling/SenderWorld.java b/core/src/main/java/art/arcane/iris/core/tooling/SenderWorld.java new file mode 100644 index 000000000..e4bc80c75 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/tooling/SenderWorld.java @@ -0,0 +1,37 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.tooling; + +import art.arcane.iris.engine.framework.Engine; +import com.volmit.world.PackWorld; + +import java.util.Objects; + +/** The Iris world a sender stands in, and the pack it generates with. */ +public record SenderWorld(ServedPack pack, PackWorld world) { + public SenderWorld { + Objects.requireNonNull(pack, "pack"); + Objects.requireNonNull(world, "world"); + } + + /** The world {@code engine} generates. */ + public static SenderWorld of(Engine engine) { + return new SenderWorld(new IrisServedPack(engine.getData()), engine.getGeneration().world()); + } +} diff --git a/core/src/main/java/art/arcane/iris/core/tooling/ServedPack.java b/core/src/main/java/art/arcane/iris/core/tooling/ServedPack.java new file mode 100644 index 000000000..6e4960b54 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/tooling/ServedPack.java @@ -0,0 +1,44 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.tooling; + +import com.volmit.ModuleLog; +import com.volmit.host.CommandRegistration; +import com.volmit.tooling.ToolPack; + +import java.util.List; + +/** + * A pack the dispatcher runs module commands against. Two instances of one pack are equal, so the dispatcher can tell that + * the pack a line names is the pack of the sender's world. + */ +public interface ServedPack { + /** The pack's folder name, as {@code pack=} writes it. */ + String name(); + + /** + * The root commands the pack's modules registered. + * + * @throws IllegalStateException when the pack's modules did not load, with the reason + */ + List commands(); + + /** The pack as the commands of the module that owns {@code log} see it. */ + ToolPack toolPack(ModuleLog log); +} diff --git a/core/src/main/java/art/arcane/iris/core/tooling/ToolingCommands.java b/core/src/main/java/art/arcane/iris/core/tooling/ToolingCommands.java new file mode 100644 index 000000000..b76eeb69f --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/tooling/ToolingCommands.java @@ -0,0 +1,295 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.tooling; + +import art.arcane.iris.core.modules.IrisValidationContext; +import art.arcane.iris.spi.IrisLogging; +import com.volmit.host.CommandRegistration; +import com.volmit.resource.PlatformRegistries; +import com.volmit.tooling.Argument; +import com.volmit.tooling.Command; +import com.volmit.world.PackWorld; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.Executor; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Supplier; + +/** + * The one dispatcher of the commands modules register ({@link com.volmit.tooling.ToolingRegistry#registerCommand}), + * which both adapters mount as the tail of their {@code /iris} root. It resolves the pack first, because the commands + * belong to one pack's module set: {@code pack=} anywhere in the line, else the pack of the sender's world, else the + * pack of the sender's open studio. Then it walks the module's command tree, parses the arguments and runs the action on a + * worker thread, so no command runs on the server's main thread or a region thread. + *

+ * Words are separated by whitespace; there is no quoting, and an argument that takes the rest of the line gets the + * remaining words joined by single spaces. + */ +public final class ToolingCommands { + private static final String NAME_A_PACK = "Name a pack: " + CommandLine.PACK_OPTION + ""; + private static final String WORKER_NAME_PREFIX = "Iris-Tooling-"; + + private final PackDirectory packs; + private final Executor workers; + private final Supplier> platform; + + public ToolingCommands(PackDirectory packs, Executor workers, Supplier> platform) { + this.packs = packs; + this.workers = workers; + this.platform = platform; + } + + /** The dispatcher of the bound platform, with daemon worker threads created as commands need them. */ + public static ToolingCommands forBoundPlatform() { + AtomicInteger workerNumber = new AtomicInteger(); + ExecutorService workers = Executors.newCachedThreadPool(task -> { + Thread worker = new Thread(task, WORKER_NAME_PREFIX + workerNumber.incrementAndGet()); + worker.setDaemon(true); + return worker; + }); + return new ToolingCommands(PackDirectory.ofBoundPlatform(), workers, IrisValidationContext::boundPlatformRegistries); + } + + /** + * Runs the command the words name, if some module of the resolved pack registers its root: the pack, the tree and the + * arguments are resolved on the calling thread and the action runs on a worker. A problem with the line reaches the + * sender as an error. + * + * @return whether the line was a command of this dispatcher; false leaves the sender without a reply + */ + public boolean execute(ToolingSender sender, List words) { + return run(sender, words, false); + } + + /** + * Like {@link #execute}, for a sender the platform denies the root command: runs only a command opened to everyone, + * and tells the sender nothing otherwise. + * + * @return whether it ran such a command + */ + public boolean executeIfOpenToEveryone(ToolingSender sender, List words) { + return run(sender, words, true); + } + + /** Like {@link #execute}, with the resolving done on a worker too, for callers that must not block. */ + public void executeOffThread(ToolingSender sender, List words) { + workers.execute(() -> { + if (!execute(sender, words)) { + sender.error("Unknown command"); + } + }); + } + + /** The words that can follow {@code words}, whose last word is the one being typed. */ + public List complete(ToolingSender sender, List words) { + if (words.isEmpty()) { + return List.of(); + } + String partial = words.getLast(); + if (partial.startsWith(CommandLine.PACK_OPTION)) { + return packs.names().stream().map(name -> CommandLine.PACK_OPTION + name).filter(option -> option.startsWith(partial)).toList(); + } + try { + CommandLine typed = CommandLine.of(words.subList(0, words.size() - 1)); + ResolvedPack pack = resolvePack(sender, typed.packName()); + List roots = rootsOf(pack.served()); + if (typed.words().isEmpty()) { + return roots.stream() + .filter(root -> mayRun(sender, root.command())) + .map(root -> root.command().name()) + .filter(name -> name.startsWith(partial)) + .toList(); + } + Optional located = LocatedCommand.locate(roots, typed.words()); + if (located.isEmpty() || !mayRun(sender, located.get().command())) { + return List.of(); + } + return completions(sender, located.get(), partial, contextOf(sender, pack, located.get())); + } catch (CommandFailure | RuntimeException cannotComplete) { + return List.of(); + } + } + + private boolean run(ToolingSender sender, List tokens, boolean onlyIfOpenToEveryone) { + try { + CommandLine line = CommandLine.of(tokens); + if (line.words().isEmpty()) { + return false; + } + ResolvedPack pack = resolvePack(sender, line.packName()); + Optional located = LocatedCommand.locate(rootsOf(pack.served()), line.words()); + if (located.isEmpty()) { + return false; + } + if (onlyIfOpenToEveryone && !located.get().command().isOpenToEveryone()) { + return false; + } + launch(sender, pack, located.get()); + return true; + } catch (CommandFailure failure) { + if (onlyIfOpenToEveryone) { + return false; + } + sender.error(failure.getMessage()); + failure.usage().ifPresent(sender::info); + return true; + } catch (RuntimeException failure) { + IrisLogging.reportError(failure); + sender.error("Command failed: " + reasonOf(failure)); + return true; + } + } + + private void launch(ToolingSender sender, ResolvedPack pack, LocatedCommand located) throws CommandFailure { + if (!mayRun(sender, located.command())) { + throw new CommandFailure("Only operators may use " + located.pathText()); + } + if (located.command().action().isEmpty()) { + describeGroup(sender, located); + return; + } + CommandRun context = contextOf(sender, pack, located); + parseArguments(located, context); + workers.execute(() -> runAction(located, context)); + } + + private static void runAction(LocatedCommand located, CommandRun context) { + try { + located.command().action().orElseThrow().run(context); + } catch (Throwable failure) { + context.sender().error(located.pathText() + " failed: " + reasonOf(failure)); + located.root().module().log().error("Command " + located.pathText() + " failed", failure); + } + } + + private static String reasonOf(Throwable failure) { + return failure.getMessage() == null ? failure.getClass().getSimpleName() : failure.getMessage(); + } + + private static boolean mayRun(ToolingSender sender, Command command) { + return sender.isOperator() || command.isOpenToEveryone(); + } + + private ResolvedPack resolvePack(ToolingSender sender, Optional packName) throws CommandFailure { + if (packName.isPresent()) { + ServedPack named = packs.find(packName.get()).orElseThrow(() -> new CommandFailure("No pack named " + packName.get())); + Optional world = sender.world().filter(standing -> standing.pack().equals(named)).map(SenderWorld::world); + return new ResolvedPack(named, world); + } + Optional standing = sender.world(); + if (standing.isPresent()) { + return new ResolvedPack(standing.get().pack(), Optional.of(standing.get().world())); + } + ServedPack ofStudio = sender.openStudioPack().orElseThrow(() -> new CommandFailure(NAME_A_PACK)); + return new ResolvedPack(ofStudio, Optional.empty()); + } + + private static List rootsOf(ServedPack pack) throws CommandFailure { + try { + return pack.commands(); + } catch (IllegalStateException modulesFailed) { + throw new CommandFailure(modulesFailed.getMessage()); + } + } + + private CommandRun contextOf(ToolingSender sender, ResolvedPack pack, LocatedCommand located) { + return new CommandRun(sender, pack.served().toolPack(located.root().module().log()), pack.world(), platform.get()); + } + + private static void parseArguments(LocatedCommand located, CommandRun context) throws CommandFailure { + List typed = located.arguments(); + int next = 0; + for (Argument argument : located.command().arguments()) { + if (next >= typed.size()) { + if (argument.isOptional()) continue; + throw new CommandFailure("Missing " + argument.name(), "Use: " + located.usage()); + } + String text = argument.takesRestOfLine() ? String.join(" ", typed.subList(next, typed.size())) : typed.get(next); + next = argument.takesRestOfLine() ? typed.size() : next + 1; + parseInto(context, argument, text, located); + } + if (next < typed.size()) { + throw new CommandFailure("Too many arguments: " + String.join(" ", typed.subList(next, typed.size())), + "Use: " + located.usage()); + } + } + + private static void parseInto(CommandRun context, Argument argument, String text, LocatedCommand located) throws CommandFailure { + try { + context.put(argument, argument.parse(text, context)); + } catch (IllegalArgumentException invalid) { + throw new CommandFailure(invalid.getMessage(), "Use: " + located.usage()); + } + } + + private static List completions(ToolingSender sender, LocatedCommand located, String partial, CommandRun context) { + List suggestions = new ArrayList<>(); + List typed = located.arguments(); + if (typed.isEmpty()) { + located.command().children().stream() + .filter(child -> mayRun(sender, child)) + .map(Command::name) + .filter(name -> name.startsWith(partial)) + .forEach(suggestions::add); + } + List> arguments = located.command().arguments(); + for (int index = 0; index < typed.size() && index < arguments.size(); index++) { + Argument argument = arguments.get(index); + if (argument.takesRestOfLine()) { + return List.of(); + } + if (!parsesInto(context, argument, typed.get(index))) { + return List.of(); + } + } + if (typed.size() < arguments.size()) { + suggestions.addAll(arguments.get(typed.size()).complete(partial, context)); + } + return suggestions.stream().distinct().toList(); + } + + private static boolean parsesInto(CommandRun context, Argument argument, String text) { + try { + context.put(argument, argument.parse(text, context)); + return true; + } catch (RuntimeException invalid) { + return false; + } + } + + private static void describeGroup(ToolingSender sender, LocatedCommand located) { + if (!located.arguments().isEmpty()) { + sender.error("Unknown " + located.pathText() + " sub-command: " + located.arguments().getFirst()); + } + String description = located.command().description(); + sender.info(located.pathText() + (description.isEmpty() ? "" : ": " + description)); + for (Command child : located.command().children()) { + if (!mayRun(sender, child)) continue; + List childPath = new ArrayList<>(located.path()); + childPath.add(child.name()); + sender.info(" " + LocatedCommand.usageOf(childPath, child) + (child.description().isEmpty() ? "" : " - " + child.description())); + } + } + + private record ResolvedPack(ServedPack served, Optional world) {} +} diff --git a/core/src/main/java/art/arcane/iris/core/tooling/ToolingSender.java b/core/src/main/java/art/arcane/iris/core/tooling/ToolingSender.java new file mode 100644 index 000000000..c6a2e3222 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/tooling/ToolingSender.java @@ -0,0 +1,39 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.tooling; + +import com.volmit.tooling.Sender; + +import java.util.Optional; + +/** + * Who sent a tooling command, as the adapter that received it knows them: the module-facing {@link Sender}, and what the + * dispatcher needs to decide who may run a command and which pack it runs against. An adapter reads the platform state + * here when it builds the sender, on the thread the platform needs, so the dispatcher may run anywhere. + */ +public interface ToolingSender extends Sender { + /** Whether the platform treats the sender as an operator: the Bukkit permission {@code iris.all}, game master level on modded. */ + boolean isOperator(); + + /** The Iris world the sender stands in; empty for the console or a world Iris does not generate. */ + Optional world(); + + /** The pack of the studio the sender has open; empty when none is, and always on a platform without a studio. */ + Optional openStudioPack(); +} diff --git a/core/src/test/java/art/arcane/iris/core/tooling/IrisToolPackTest.java b/core/src/test/java/art/arcane/iris/core/tooling/IrisToolPackTest.java new file mode 100644 index 000000000..58fab7978 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/core/tooling/IrisToolPackTest.java @@ -0,0 +1,146 @@ +package art.arcane.iris.core.tooling; + +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.spi.IrisPlatform; +import art.arcane.iris.spi.IrisPlatforms; +import com.volmit.ModuleLog; +import org.junit.After; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import java.io.File; +import java.io.IOException; +import java.io.InterruptedIOException; +import java.nio.file.Path; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +public class IrisToolPackTest { + @Rule + public TemporaryFolder temporaryFolder = new TemporaryFolder(); + + private IrisPlatform previousPlatform; + private File packsFolder; + private File packFolder; + private IrisData data; + private IrisToolPack pack; + + @Before + public void aPackInsideAWorkspace() throws Exception { + previousPlatform = IrisPlatforms.isBound() ? IrisPlatforms.get() : null; + IrisPlatforms.unbind(); + packsFolder = temporaryFolder.newFolder("packs"); + IrisPlatform platform = mock(IrisPlatform.class); + when(platform.packsFolder()).thenReturn(packsFolder); + IrisPlatforms.bind(platform); + packFolder = new File(packsFolder, "overworld"); + assertTrue(packFolder.mkdirs()); + data = mock(IrisData.class); + when(data.getDataFolder()).thenReturn(packFolder); + pack = new IrisToolPack(data, mock(ModuleLog.class)); + } + + @After + public void restorePlatform() { + IrisPlatforms.unbind(); + if (previousPlatform != null) { + IrisPlatforms.bind(previousPlatform); + } + } + + @Test + public void anEditChangesFilesBelowThePackRootAndReloadsTheResourcesOnce() throws Exception { + Path seenRoot = pack.edit(root -> { + java.nio.file.Files.writeString(root.resolve("note.txt"), "x"); + java.nio.file.Files.writeString(root.resolve("second.txt"), "y"); + return root; + }); + + assertEquals(packFolder.toPath(), seenRoot); + assertTrue(new File(packFolder, "second.txt").isFile()); + verify(data, times(1)).invalidateStructureResources(); + } + + @Test + public void anEditThatThrowsLeavesNoReloadBehind() { + IOException failure = new IOException("disk full"); + + IOException thrown = assertThrows(IOException.class, () -> pack.edit(root -> { + throw failure; + })); + + assertSame(failure, thrown); + verify(data, never()).invalidateStructureResources(); + } + + @Test + public void oneEditRunsAtATimeAndASecondWaitsForTheFirst() throws Exception { + ExecutorService threads = Executors.newFixedThreadPool(2); + try { + CountDownLatch firstInside = new CountDownLatch(1); + CountDownLatch releaseFirst = new CountDownLatch(1); + AtomicBoolean secondEntered = new AtomicBoolean(); + Future first = threads.submit(() -> pack.edit(root -> { + firstInside.countDown(); + awaitRelease(releaseFirst); + return null; + })); + assertTrue(firstInside.await(10, TimeUnit.SECONDS)); + Future second = threads.submit(() -> pack.edit(root -> { + secondEntered.set(true); + return null; + })); + + Thread.sleep(200); + assertFalse(secondEntered.get()); + releaseFirst.countDown(); + first.get(10, TimeUnit.SECONDS); + second.get(10, TimeUnit.SECONDS); + + assertTrue(secondEntered.get()); + verify(data, times(2)).invalidateStructureResources(); + } finally { + threads.shutdownNow(); + } + } + + private static void awaitRelease(CountDownLatch release) throws IOException { + try { + release.await(10, TimeUnit.SECONDS); + } catch (InterruptedException interrupted) { + throw new InterruptedIOException("Interrupted while the edit was held"); + } + } + + @Test + public void theOutputFolderIsTheWorkspaceExportsFolderOfThePack() { + Path output = pack.outputFolder(); + + assertEquals(new File(new File(packsFolder, "exports"), "overworld").toPath().toAbsolutePath().normalize(), output); + assertTrue(output.toFile().isDirectory()); + assertFalse(output.startsWith(packFolder.toPath())); + } + + @Test + public void theObjectCodecReadsAndWritesIobFiles() { + assertEquals(".iob", pack.objects().extension()); + assertThrows(IOException.class, () -> pack.objects().decode(new byte[] {1, 2, 3})); + } +} diff --git a/core/src/test/java/art/arcane/iris/core/tooling/RecordingSender.java b/core/src/test/java/art/arcane/iris/core/tooling/RecordingSender.java new file mode 100644 index 000000000..98dc3f25d --- /dev/null +++ b/core/src/test/java/art/arcane/iris/core/tooling/RecordingSender.java @@ -0,0 +1,56 @@ +package art.arcane.iris.core.tooling; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Optional; + +/** A sender that keeps what it was told, by kind. */ +final class RecordingSender implements ToolingSender { + final List infos = Collections.synchronizedList(new ArrayList<>()); + final List successes = Collections.synchronizedList(new ArrayList<>()); + final List errors = Collections.synchronizedList(new ArrayList<>()); + boolean operator = true; + Optional world = Optional.empty(); + Optional studio = Optional.empty(); + + @Override + public String name() { + return "Tester"; + } + + @Override + public void info(String message) { + infos.add(message); + } + + @Override + public void success(String message) { + successes.add(message); + } + + @Override + public void error(String message) { + errors.add(message); + } + + @Override + public Optional extension(Class type) { + return Optional.empty(); + } + + @Override + public boolean isOperator() { + return operator; + } + + @Override + public Optional world() { + return world; + } + + @Override + public Optional openStudioPack() { + return studio; + } +} diff --git a/core/src/test/java/art/arcane/iris/core/tooling/ToolingCommandsTest.java b/core/src/test/java/art/arcane/iris/core/tooling/ToolingCommandsTest.java new file mode 100644 index 000000000..ac9cd20b6 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/core/tooling/ToolingCommandsTest.java @@ -0,0 +1,444 @@ +package art.arcane.iris.core.tooling; + +import art.arcane.iris.core.modules.ModuleResourceFixture; +import com.volmit.IrisModule; +import com.volmit.ModuleInfo; +import com.volmit.ModuleLog; +import com.volmit.ModuleSetup; +import com.volmit.config.Reference; +import com.volmit.host.CommandRegistration; +import com.volmit.resource.PackResources; +import com.volmit.resource.PlatformRegistries; +import com.volmit.resource.ResourceId; +import com.volmit.resource.ResourceKind; +import com.volmit.tooling.Argument; +import com.volmit.tooling.Command; +import com.volmit.tooling.ToolPack; +import com.volmit.world.PackWorld; +import org.junit.Before; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executor; +import java.util.concurrent.Executors; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class ToolingCommandsTest { + private static final ResourceKind NOTES = ResourceKind.of("test:note", "notes", String.class); + + private enum Mode { FAST_PASS, SLOW } + + private final Executor sameThread = Runnable::run; + private final Map packsByName = new LinkedHashMap<>(); + private final RecordingSender sender = new RecordingSender(); + private final List seen = Collections.synchronizedList(new ArrayList<>()); + private Optional registries = Optional.empty(); + private ToolingCommands dispatcher; + + @Before + public void dispatcherOverFakePacks() { + dispatcher = new ToolingCommands(new PackDirectory() { + @Override + public Optional find(String name) { + return Optional.ofNullable(packsByName.get(name)); + } + + @Override + public List names() { + return List.copyOf(packsByName.keySet()); + } + }, sameThread, () -> registries); + } + + private FakePack packWith(String name, Command... roots) { + PackResources resources = mock(PackResources.class, org.mockito.Mockito.CALLS_REAL_METHODS); + when(resources.packId()).thenReturn(new ResourceId("test", name)); + when(resources.ids(NOTES)).thenReturn(List.of(new ResourceId("test", "alpha"), new ResourceId("test", "beta"), + new ResourceId("other", "gamma"))); + ToolPack toolPack = mock(ToolPack.class); + when(toolPack.resources()).thenReturn(resources); + IrisModule module = new IrisModule() { + @Override + public ModuleInfo info() { + return ModuleInfo.of("test:" + name, name, "1"); + } + + @Override + public void setup(ModuleSetup setup) { + for (Command root : roots) setup.tooling().registerCommand(root); + } + }; + FakePack pack = new FakePack(name, ModuleResourceFixture.catalogOf(module).commands(), toolPack); + packsByName.put(name, pack); + return pack; + } + + private static List words(String line) { + return line.isBlank() ? List.of() : List.of(line.trim().split("\\s+", -1)); + } + + private boolean run(String line) { + return dispatcher.execute(sender, words(line)); + } + + private List complete(String line) { + return dispatcher.complete(sender, List.of(line.split(" ", -1))); + } + + private void standIn(FakePack pack) { + sender.world = Optional.of(new SenderWorld(pack, mock(PackWorld.class))); + } + + private Command recording(String name) { + return Command.named(name).runs(context -> seen.add(name)); + } + + @Test + public void parsesRequiredAndOptionalArgumentsInOrder() { + Argument label = Argument.word("label"); + Argument count = Argument.integer("count", 1, 10); + Argument mode = Argument.choice("mode", Mode.class).orElse(Mode.SLOW); + packWith("one", Command.named("give").argument(label).argument(count).argument(mode) + .runs(context -> seen.add(List.of(context.get(label), context.get(count), context.get(mode))))); + standIn(packsByName.get("one")); + + assertTrue(run("give apple 3")); + assertTrue(run("give pear 7 fast-pass")); + + assertEquals(List.of(List.of("apple", 3L, Mode.SLOW), List.of("pear", 7L, Mode.FAST_PASS)), seen); + assertTrue(sender.errors.isEmpty()); + } + + @Test + public void reportsAMissingRequiredArgumentWithTheUsage() { + packWith("one", Command.named("give").argument(Argument.word("label")).argument(Argument.integer("count", 1, 10)) + .argument(Argument.word("note").orElse("none")).runs(context -> seen.add("ran"))); + standIn(packsByName.get("one")); + + assertTrue(run("give apple")); + + assertEquals(List.of("Missing count"), sender.errors); + assertEquals(List.of("Use: give