Add the tooling command dispatcher and the ToolPack over Iris's pack data

ToolingCommands resolves the pack of a line (pack=<name>, the sender's world, the
sender's open studio), walks the registering module's Command tree, parses the typed
arguments and runs the action on a worker thread. It also completes, and gates
commands to operators unless they are open to everyone. IrisToolPack holds the
pack's IrisData for each edit, so no hotload or second edit runs inside it, then
reloads the resources once; outputFolder is the workspace exports folder of the pack
and IrisObjectCodec reads and writes .iob.
This commit is contained in:
piexel committed 2026-11-06 10:51:10 +01:00
1 parent f7d2ce86a7
commit bcec8e474d
15 files changed
+1623

No files matched your search

@@ -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 <https://www.gnu.org/licenses/>.
*/
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<String> usage() {
return Optional.ofNullable(usage);
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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=<name>} option, which may stand anywhere in the line. */
record CommandLine(Optional<String> packName, List<String> words) {
static final String PACK_OPTION = "pack=";
static CommandLine of(List<String> tokens) throws CommandFailure {
List<String> words = new ArrayList<>();
Optional<String> 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);
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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<PackWorld> world;
private final Optional<PlatformRegistries> platform;
private final Map<Argument<?>, Object> values = new IdentityHashMap<>();
CommandRun(Sender sender, ToolPack pack, Optional<PackWorld> world, Optional<PlatformRegistries> platform) {
this.sender = sender;
this.pack = pack;
this.world = world;
this.platform = platform;
}
<T> void put(Argument<T> argument, T value) {
values.put(argument, value);
}
@Override
@SuppressWarnings("unchecked")
public <T> T get(Argument<T> 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<PackWorld> world() {
return world;
}
@Override
public Optional<PlatformRegistries> platform() {
return platform;
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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;
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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<CommandRegistration> 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();
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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> T edit(PackEdit<T> 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();
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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<String> path, List<String> arguments) {
static Optional<LocatedCommand> locate(List<CommandRegistration> roots, List<String> words) {
Optional<CommandRegistration> root = roots.stream()
.filter(candidate -> candidate.command().answersTo(words.getFirst()))
.findFirst();
if (root.isEmpty()) {
return Optional.empty();
}
Command command = root.get().command();
List<String> path = new ArrayList<>(List.of(command.name()));
int consumed = 1;
while (consumed < words.size()) {
Optional<Command> 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<String> 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<Command> childAnsweringTo(Command command, String word) {
return command.children().stream().filter(child -> child.answersTo(word)).findFirst();
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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=<name>}. */
public interface PackDirectory {
/** The pack folder named {@code name}; empty when there is none. */
Optional<ServedPack> find(String name);
/** The names of the pack folders, sorted. */
List<String> 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<ServedPack> 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<String> names() {
return PackDirectoryResolver.listVisiblePackDirectories(IrisPlatforms.get().packsFolderNoCreate()).stream()
.map(File::getName)
.filter(name -> !name.equals(IrisToolPack.EXPORTS_FOLDER))
.toList();
}
};
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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());
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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=<name>} 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<CommandRegistration> commands();
/** The pack as the commands of the module that owns {@code log} see it. */
ToolPack toolPack(ModuleLog log);
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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=<name>} 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.
* <p>
* 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 + "<name>";
private static final String WORKER_NAME_PREFIX = "Iris-Tooling-";
private final PackDirectory packs;
private final Executor workers;
private final Supplier<Optional<PlatformRegistries>> platform;
public ToolingCommands(PackDirectory packs, Executor workers, Supplier<Optional<PlatformRegistries>> 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<String> 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<String> 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<String> 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<String> complete(ToolingSender sender, List<String> 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<CommandRegistration> 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<LocatedCommand> 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<String> tokens, boolean onlyIfOpenToEveryone) {
try {
CommandLine line = CommandLine.of(tokens);
if (line.words().isEmpty()) {
return false;
}
ResolvedPack pack = resolvePack(sender, line.packName());
Optional<LocatedCommand> 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<String> packName) throws CommandFailure {
if (packName.isPresent()) {
ServedPack named = packs.find(packName.get()).orElseThrow(() -> new CommandFailure("No pack named " + packName.get()));
Optional<PackWorld> world = sender.world().filter(standing -> standing.pack().equals(named)).map(SenderWorld::world);
return new ResolvedPack(named, world);
}
Optional<SenderWorld> 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<CommandRegistration> 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<String> 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 <T> void parseInto(CommandRun context, Argument<T> 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<String> completions(ToolingSender sender, LocatedCommand located, String partial, CommandRun context) {
List<String> suggestions = new ArrayList<>();
List<String> 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<Argument<?>> 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 <T> boolean parsesInto(CommandRun context, Argument<T> 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<String> 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<PackWorld> world) {}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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<SenderWorld> world();
/** The pack of the studio the sender has open; empty when none is, and always on a platform without a studio. */
Optional<ServedPack> openStudioPack();
}
@@ -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}));
}
}
@@ -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<String> infos = Collections.synchronizedList(new ArrayList<>());
final List<String> successes = Collections.synchronizedList(new ArrayList<>());
final List<String> errors = Collections.synchronizedList(new ArrayList<>());
boolean operator = true;
Optional<SenderWorld> world = Optional.empty();
Optional<ServedPack> 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 <T> Optional<T> extension(Class<T> type) {
return Optional.empty();
}
@Override
public boolean isOperator() {
return operator;
}
@Override
public Optional<SenderWorld> world() {
return world;
}
@Override
public Optional<ServedPack> openStudioPack() {
return studio;
}
}
@@ -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<String> NOTES = ResourceKind.of("test:note", "notes", String.class);
private enum Mode { FAST_PASS, SLOW }
private final Executor sameThread = Runnable::run;
private final Map<String, FakePack> packsByName = new LinkedHashMap<>();
private final RecordingSender sender = new RecordingSender();
private final List<Object> seen = Collections.synchronizedList(new ArrayList<>());
private Optional<PlatformRegistries> registries = Optional.empty();
private ToolingCommands dispatcher;
@Before
public void dispatcherOverFakePacks() {
dispatcher = new ToolingCommands(new PackDirectory() {
@Override
public Optional<ServedPack> find(String name) {
return Optional.ofNullable(packsByName.get(name));
}
@Override
public List<String> 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<String> 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<String> 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<String> label = Argument.word("label");
Argument<Long> count = Argument.integer("count", 1, 10);
Argument<Mode> 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 <label> <count> [note]"), sender.infos);
assertTrue(seen.isEmpty());
}
@Test
public void reportsTooManyArgumentsAndInvalidValues() {
packWith("one", Command.named("give").argument(Argument.integer("count", 1, 10))
.argument(Argument.choice("mode", Mode.class).orElse(Mode.SLOW)).runs(context -> seen.add("ran")));
standIn(packsByName.get("one"));
run("give 3 slow extra words");
run("give 11");
run("give three");
run("give 3 sideways");
assertEquals(List.of("Too many arguments: extra words", "count must be a whole number from 1 to 10",
"count must be a whole number", "mode must be one of fast-pass, slow"), sender.errors);
assertTrue(seen.isEmpty());
}
@Test
public void textTakesTheRestOfTheLineJoinedBySingleSpaces() {
Argument<String> title = Argument.word("title");
Argument<String> body = Argument.text("body");
packWith("one", Command.named("note").argument(title).argument(body)
.runs(context -> seen.add(context.get(title) + "|" + context.get(body))));
standIn(packsByName.get("one"));
run("note head several spaced words");
assertEquals(List.of("head|several spaced words"), seen);
}
@Test
public void aWordThatNamesASubCommandSelectsItAndAliasesWork() {
packWith("one", Command.named("tools").alias("t").child(recording("list").alias("ls")).child(recording("clear")));
standIn(packsByName.get("one"));
run("tools list");
run("t ls");
run("tools clear");
assertEquals(List.of("list", "list", "clear"), seen);
}
@Test
public void aCommandWithoutAnActionListsItsSubCommandsAndRejectsUnknownOnes() {
packWith("one", Command.named("tools").describe("Pack tools")
.child(Command.named("list").describe("List things").argument(Argument.word("filter").orElse("all")))
.child(recording("clear")));
standIn(packsByName.get("one"));
assertTrue(run("tools"));
assertTrue(run("tools frobnicate"));
assertEquals(List.of("tools: Pack tools", " tools list [filter] - List things", " tools clear",
"tools: Pack tools", " tools list [filter] - List things", " tools clear"), sender.infos);
assertEquals(List.of("Unknown tools sub-command: frobnicate"), sender.errors);
}
@Test
public void aLineThatNoRootOwnsIsNotHandled() {
packWith("one", recording("tools"));
standIn(packsByName.get("one"));
assertFalse(run("elsewhere now"));
assertFalse(run(""));
assertTrue(sender.errors.isEmpty());
}
@Test
public void packOptionIsTakenOutOfTheLineWhereverItStands() {
Argument<String> label = Argument.word("label");
packWith("alpha", Command.named("give").argument(label).runs(context -> seen.add(context.get(label))));
packWith("beta", Command.named("other").runs(context -> seen.add("beta")));
run("pack=alpha give apple");
run("give pack=alpha pear");
run("give plum pack=alpha");
assertEquals(List.of("apple", "pear", "plum"), seen);
}
@Test
public void aNamedPackWinsOverTheSendersWorldAndAnUnknownOneIsAnError() {
packWith("alpha", Command.named("give").runs(context -> seen.add("alpha")));
packWith("beta", Command.named("give").runs(context -> seen.add("beta")));
standIn(packsByName.get("beta"));
run("give pack=alpha");
run("give");
run("give pack=missing");
run("give pack=alpha pack=beta");
assertEquals(List.of("alpha", "beta"), seen);
assertEquals(List.of("No pack named missing", "Name one pack only"), sender.errors);
}
@Test
public void withoutAPackOrAWorldItFallsBackToTheOpenStudioThenAsksForAPack() {
packWith("alpha", Command.named("give").runs(context -> seen.add("alpha")));
run("give");
sender.studio = Optional.of(packsByName.get("alpha"));
run("give");
assertEquals(List.of("Name a pack: pack=<name>"), sender.errors);
assertEquals(List.of("alpha"), seen);
}
@Test
public void theWorldIsOnTheContextOnlyWhenItGeneratesWithTheResolvedPack() {
PackWorld world = mock(PackWorld.class);
AtomicReference<Optional<PackWorld>> given = new AtomicReference<>();
packWith("alpha", Command.named("where").runs(context -> given.set(context.world())));
packWith("beta", Command.named("where").runs(context -> given.set(context.world())));
sender.world = Optional.of(new SenderWorld(packsByName.get("alpha"), world));
run("where");
assertSame(world, given.get().orElseThrow());
run("where pack=beta");
assertTrue(given.get().isEmpty());
run("where pack=alpha");
assertSame(world, given.get().orElseThrow());
}
@Test
public void onlyOperatorsRunACommandUnlessItIsOpenToEveryone() {
packWith("alpha", recording("locked"), Command.named("public").openToEveryone().runs(context -> seen.add("public")));
standIn(packsByName.get("alpha"));
sender.operator = false;
assertTrue(run("locked"));
assertTrue(run("public"));
assertFalse(dispatcher.executeIfOpenToEveryone(sender, words("locked")));
assertTrue(dispatcher.executeIfOpenToEveryone(sender, words("public")));
assertEquals(List.of("public", "public"), seen);
assertEquals(List.of("Only operators may use locked"), sender.errors);
}
@Test
public void aSenderWithoutTheRootPermissionLearnsNothingFromAFailedLine() {
packWith("alpha", Command.named("public").openToEveryone().argument(Argument.integer("n", 1, 2)).runs(context -> seen.add("ran")));
standIn(packsByName.get("alpha"));
sender.operator = false;
assertFalse(dispatcher.executeIfOpenToEveryone(sender, words("public 9")));
assertFalse(dispatcher.executeIfOpenToEveryone(sender, words("missing")));
assertFalse(dispatcher.executeIfOpenToEveryone(sender, words("public pack=nowhere")));
assertTrue(sender.errors.isEmpty());
assertTrue(sender.infos.isEmpty());
}
@Test
public void anActionRunsOnAWorkerThreadAndWhatItThrowsReachesTheSender() throws Exception {
ExecutorService workers = Executors.newSingleThreadExecutor(task -> new Thread(task, "test-worker"));
try {
ToolingCommands threaded = new ToolingCommands(packDirectory(), workers, () -> registries);
AtomicReference<String> threadName = new AtomicReference<>();
CountDownLatch done = new CountDownLatch(2);
packWith("alpha",
Command.named("where").runs(context -> {
threadName.set(Thread.currentThread().getName());
done.countDown();
}),
Command.named("boom").runs(context -> {
done.countDown();
throw new IllegalStateException("kaput");
}));
standIn(packsByName.get("alpha"));
threaded.execute(sender, words("where"));
threaded.execute(sender, words("boom"));
assertTrue(done.await(10, TimeUnit.SECONDS));
workers.shutdown();
assertTrue(workers.awaitTermination(10, TimeUnit.SECONDS));
assertEquals("test-worker", threadName.get());
assertNotEquals(Thread.currentThread().getName(), threadName.get());
assertEquals(List.of("boom failed: kaput"), sender.errors);
} finally {
workers.shutdownNow();
}
}
private PackDirectory packDirectory() {
return new PackDirectory() {
@Override
public Optional<ServedPack> find(String name) {
return Optional.ofNullable(packsByName.get(name));
}
@Override
public List<String> names() {
return List.copyOf(packsByName.keySet());
}
};
}
@Test
public void aPackWhoseModulesDidNotLoadFailsTheLineWithTheReason() {
FakePack broken = new FakePack("broken", null, null);
packsByName.put("broken", broken);
assertTrue(run("anything pack=broken"));
assertEquals(List.of("The modules of pack broken did not load: Command root tools is registered by module a already"),
sender.errors);
}
@Test
public void resourceAndRegisteredArgumentsReadThePackAndThePlatform() {
Argument<ResourceId> note = Argument.resource("note", NOTES);
Argument<ResourceId> structure = Argument.registered("structure", Reference.STRUCTURE);
packWith("alpha", Command.named("show").argument(note).argument(structure)
.runs(context -> seen.add(context.get(note) + "|" + context.get(structure))));
standIn(packsByName.get("alpha"));
registries = Optional.of(reference -> reference == Reference.STRUCTURE
? Set.of(new ResourceId("minecraft", "village_plains")) : Set.of());
run("show alpha village_plains");
run("show other:gamma minecraft:village_plains");
run("show nowhere village_plains");
run("show alpha igloo");
assertEquals(List.of("test:alpha|minecraft:village_plains", "other:gamma|minecraft:village_plains"), seen);
assertEquals(List.of("No notes resource 'nowhere' in this pack", "No structure 'igloo' is registered"), sender.errors);
}
@Test
public void completesRootsSubCommandsChoicesAndResources() {
packWith("alpha",
Command.named("tools").child(recording("list")).child(recording("clear")).child(Command.named("mode")
.argument(Argument.choice("mode", Mode.class)).argument(Argument.resource("note", NOTES))
.argument(Argument.text("rest")).runs(context -> { })),
recording("tidy"));
packWith("beta", recording("betaonly"));
standIn(packsByName.get("alpha"));
assertEquals(List.of("tidy", "tools"), complete("t"));
assertEquals(List.of("list", "clear", "mode"), complete("tools "));
assertEquals(List.of("clear"), complete("tools c"));
assertEquals(List.of("fast-pass", "slow"), complete("tools mode "));
assertEquals(List.of("slow"), complete("tools mode s"));
assertEquals(List.of("alpha", "beta", "other:gamma"), complete("tools mode slow "));
assertEquals(List.of("beta"), complete("tools mode slow b"));
assertEquals(List.of(), complete("tools mode slow beta "));
assertEquals(List.of(), complete("tools mode sideways "));
assertEquals(List.of(), complete("tools mode slow beta typing more"));
}
@Test
public void completesPackNamesAndDoesNotOfferWhatTheSenderMayNotRun() {
packWith("alpha", recording("locked"), Command.named("public").openToEveryone().runs(context -> { }));
packWith("alpine", recording("other"));
sender.operator = false;
standIn(packsByName.get("alpha"));
assertEquals(List.of("pack=alpha", "pack=alpine"), complete("pack=al"));
assertEquals(List.of("pack=alpine"), complete("pack=alpi"));
assertEquals(List.of("public"), complete(""));
assertEquals(List.of(), complete("locked "));
}
@Test
public void completionNeverThrows() {
assertEquals(List.of(), complete("tools "));
assertEquals(List.of(), dispatcher.complete(sender, List.of()));
assertEquals(List.of(), complete("tools pack=a pack=b "));
}
/** A pack of the test: its catalog's root commands, or the failure of its modules when it has none. */
private static final class FakePack implements ServedPack {
private final String name;
private final List<CommandRegistration> commands;
private final ToolPack toolPack;
FakePack(String name, List<CommandRegistration> commands, ToolPack toolPack) {
this.name = name;
this.commands = commands;
this.toolPack = toolPack;
}
@Override
public String name() {
return name;
}
@Override
public List<CommandRegistration> commands() {
if (commands == null) {
throw new IllegalStateException("The modules of pack " + name
+ " did not load: Command root tools is registered by module a already");
}
return commands;
}
@Override
public ToolPack toolPack(ModuleLog log) {
return toolPack;
}
}
}