Add the platform-neutral command api for module tooling

A module registers a root Command through ToolingRegistry.registerCommand: typed
Arguments (word, text, integer, decimal, flag, choice, resource, registered),
sub-commands, and a CommandAction that runs against a CommandContext with a
ToolPack, a Sender and the platform's registries. ToolPack.edit is the one way to
change pack files; ObjectCodec reads and writes the host's object format.
The host catalogues the root commands and fails a pack load when two modules
claim one root name or alias, naming both.
This commit is contained in:
piexel committed 2026-11-06 10:17:59 +01:00
1 parent 480e5485ac
commit fc81e54b0c
16 files changed
+874 -5

No files matched your search

@@ -0,0 +1,254 @@
package com.volmit.tooling;
import com.volmit.config.Reference;
import com.volmit.resource.PlatformRegistries;
import com.volmit.resource.ResourceId;
import com.volmit.resource.ResourceKind;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Stream;
/**
* One typed argument of a {@link Command}: its name, how text becomes a value, what the host completes, and an optional
* default. Immutable; each method returns a changed copy. Modules declare arguments and read their values with
* {@link CommandContext#get}; the host calls {@link #parse} and {@link #complete}.
*/
public final class Argument<T> {
private static final String CHOICE_SEPARATOR = "-";
private static final String PLATFORM_NAMESPACE = "minecraft";
private final String name;
private final String description;
private final Parser<T> parser;
private final Completer completer;
private final boolean takesRestOfLine;
private final T fallback;
private final Suggestions suggestions;
private Argument(String name, String description, Parser<T> parser, Completer completer, boolean takesRestOfLine,
T fallback, Suggestions suggestions) {
this.name = name;
this.description = description;
this.parser = parser;
this.completer = completer;
this.takesRestOfLine = takesRestOfLine;
this.fallback = fallback;
this.suggestions = suggestions;
}
/** One word. */
public static Argument<String> word(String name) {
return of(name, false, (text, context) -> text, (partial, context) -> List.of());
}
/** The rest of the line. Only as the last argument. */
public static Argument<String> text(String name) {
return of(name, true, (text, context) -> text, (partial, context) -> List.of());
}
/** A whole number from {@code min} to {@code max}. */
public static Argument<Long> integer(String name, long min, long max) {
if (min > max) {
throw new IllegalArgumentException("Argument " + name + " allows no number: " + min + " is above " + max);
}
return of(name, false, (text, context) -> {
var value = parseWholeNumber(name, text);
if (value < min || value > max) {
throw new IllegalArgumentException(name + " must be a whole number from " + min + " to " + max);
}
return value;
}, (partial, context) -> List.of());
}
/** A number from {@code min} to {@code max}. */
public static Argument<Double> decimal(String name, double min, double max) {
if (!(min <= max)) {
throw new IllegalArgumentException("Argument " + name + " allows no number: " + min + " is above " + max);
}
return of(name, false, (text, context) -> {
var value = parseNumber(name, text);
if (!(value >= min && value <= max)) {
throw new IllegalArgumentException(name + " must be a number from " + min + " to " + max);
}
return value;
}, (partial, context) -> List.of());
}
/** {@code true} or {@code false}. */
public static Argument<Boolean> flag(String name) {
return of(name, false, (text, context) -> {
if (text.equalsIgnoreCase("true")) return true;
if (text.equalsIgnoreCase("false")) return false;
throw new IllegalArgumentException(name + " must be true or false");
}, (partial, context) -> List.of("true", "false"));
}
/** One constant of {@code type}, written in lower case with '-'. */
public static <E extends Enum<E>> Argument<E> choice(String name, Class<E> type) {
var words = Arrays.stream(type.getEnumConstants()).map(Argument::choiceWord).toList();
return of(name, false, (text, context) -> {
for (var constant : type.getEnumConstants()) {
if (choiceWord(constant).equals(text.toLowerCase(Locale.ROOT))) return constant;
}
throw new IllegalArgumentException(name + " must be one of " + String.join(", ", words));
}, (partial, context) -> words);
}
/** The id of a resource of {@code kind} in the resolved pack; completes {@link com.volmit.resource.PackResources#ids}.
* Written as the key the pack's files name ({@code villages/plains}) or as the full id.
*/
public static Argument<ResourceId> resource(String name, ResourceKind<?> kind) {
return of(name, false, (text, context) -> {
var resources = context.pack().resources();
var id = text.indexOf(':') < 0 ? resources.idOf(text) : ResourceId.parse(text);
if (!resources.ids(kind).contains(id)) {
throw new IllegalArgumentException("No " + kind.folder() + " resource '" + text + "' in this pack");
}
return id;
}, (partial, context) -> {
var resources = context.pack().resources();
var packNamespace = resources.packId().namespace();
return resources.ids(kind).stream()
.map(id -> id.namespace().equals(packNamespace) ? id.path() : id.toString())
.toList();
});
}
/** An id registered in the platform's {@code registry}, such as {@link Reference#STRUCTURE}; completes
* {@link PlatformRegistries#ids}. Written as the platform writes it, {@code minecraft:village_plains}, or without the
* {@code minecraft:} namespace.
*/
public static Argument<ResourceId> registered(String name, Reference registry) {
Objects.requireNonNull(registry, "registry");
return of(name, false, (text, context) -> {
var id = ResourceId.ofPlatformKey(text);
if (!registeredIds(context, registry).contains(id)) {
throw new IllegalArgumentException("No " + registryName(registry) + " '" + text + "' is registered");
}
return id;
}, (partial, context) -> registeredIds(context, registry).stream().flatMap(Argument::platformWritings).toList());
}
private static Stream<String> platformWritings(ResourceId id) {
return id.namespace().equals(PLATFORM_NAMESPACE) ? Stream.of(id.toString(), id.path()) : Stream.of(id.toString());
}
/** This argument, optional, with {@code fallback} when the sender leaves it out. */
public Argument<T> orElse(T fallback) {
return new Argument<>(name, description, parser, completer, takesRestOfLine,
Objects.requireNonNull(fallback, "fallback"), suggestions);
}
/** This argument with the help text the host shows. */
public Argument<T> describe(String description) {
return new Argument<>(name, Objects.requireNonNull(description, "description"), parser, completer, takesRestOfLine,
fallback, suggestions);
}
/** This argument completing what {@code suggestions} returns as well, such as the bays of an open studio session. */
public Argument<T> suggesting(Suggestions suggestions) {
return new Argument<>(name, description, parser, completer, takesRestOfLine, fallback,
Objects.requireNonNull(suggestions, "suggestions"));
}
public String name() {
return name;
}
/** The help text, empty when the module gave none. */
public String description() {
return description;
}
/** Whether the argument takes every word that is left, so the host passes it unsplit. */
public boolean takesRestOfLine() {
return takesRestOfLine;
}
/** Whether the sender may leave the argument out. */
public boolean isOptional() {
return fallback != null;
}
/** The value used when the sender leaves an optional argument out; null for a required one. */
public T fallback() {
return fallback;
}
/**
* The value {@code text} stands for. For the host.
*
* @throws IllegalArgumentException with a message for the sender when {@code text} is no such value
*/
public T parse(String text, CommandContext context) {
return parser.parse(text, context);
}
/** The completions for {@code partial}, the word typed so far: this argument's own and the module's, sorted and without
* repeats. For the host.
*/
public List<String> complete(String partial, CommandContext context) {
var lowered = partial.toLowerCase(Locale.ROOT);
var own = completer.complete(partial, context).stream();
var added = suggestions == null ? Stream.<String>empty() : suggestions.suggest(context).stream();
return Stream.concat(own, added)
.filter(candidate -> candidate.toLowerCase(Locale.ROOT).startsWith(lowered))
.distinct()
.sorted()
.toList();
}
@Override
public String toString() {
return "argument " + name;
}
private static <T> Argument<T> of(String name, boolean takesRestOfLine, Parser<T> parser, Completer completer) {
Objects.requireNonNull(name, "name");
if (name.isBlank() || name.chars().anyMatch(Character::isWhitespace)) {
throw new IllegalArgumentException("Argument name '" + name + "' must be one word");
}
return new Argument<>(name, "", parser, completer, takesRestOfLine, null, null);
}
private static String choiceWord(Enum<?> constant) {
return constant.name().toLowerCase(Locale.ROOT).replace("_", CHOICE_SEPARATOR);
}
private static long parseWholeNumber(String name, String text) {
try {
return Long.parseLong(text);
} catch (NumberFormatException notANumber) {
throw new IllegalArgumentException(name + " must be a whole number");
}
}
private static double parseNumber(String name, String text) {
try {
return Double.parseDouble(text);
} catch (NumberFormatException notANumber) {
throw new IllegalArgumentException(name + " must be a number");
}
}
private static Set<ResourceId> registeredIds(CommandContext context, Reference registry) {
return context.platform()
.orElseThrow(() -> new IllegalArgumentException("This server has no registries to read " + registryName(registry) + " ids from"))
.ids(registry);
}
private static String registryName(Reference registry) {
return registry.name().toLowerCase(Locale.ROOT).replace('_', ' ');
}
private interface Parser<T> {
T parse(String text, CommandContext context);
}
private interface Completer {
List<String> complete(String partial, CommandContext context);
}
}
@@ -0,0 +1,166 @@
package com.volmit.tooling;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.regex.Pattern;
/**
* One command: a name, sub-commands, and at most one action over typed arguments. Immutable; each method returns a
* changed copy. A module registers its root command with {@link ToolingRegistry#registerCommand}, and the host mounts it
* below its own command root, such as {@code /iris structure list}. A word that names a sub-command always selects it,
* so give a command that has children either no arguments or arguments no child is named like.
*/
public final class Command {
private static final Pattern NAME = Pattern.compile("[a-z0-9-]+");
private final String name;
private final List<String> aliases;
private final String description;
private final List<Command> children;
private final List<Argument<?>> arguments;
private final CommandAction action;
private final boolean openToEveryone;
private Command(String name, List<String> aliases, String description, List<Command> children,
List<Argument<?>> arguments, CommandAction action, boolean openToEveryone) {
this.name = name;
this.aliases = List.copyOf(aliases);
this.description = description;
this.children = List.copyOf(children);
this.arguments = List.copyOf(arguments);
this.action = action;
this.openToEveryone = openToEveryone;
}
/** A command named {@code name}: lower case letters, digits and '-'. */
public static Command named(String name) {
requireWord(name, "Command name");
return new Command(name, List.of(), "", List.of(), List.of(), null, false);
}
/** This command, also answering to {@code aliases}, which are written like a name and differ from it and from each other. */
public Command alias(String... aliases) {
var all = new ArrayList<>(this.aliases);
for (var alias : aliases) {
requireWord(alias, "Alias of command " + name);
if (alias.equals(name) || all.contains(alias)) {
throw new IllegalArgumentException("Command " + name + " answers to " + alias + " already");
}
all.add(alias);
}
return new Command(name, all, description, children, arguments, action, openToEveryone);
}
/** This command with the one-line help text the host shows. */
public Command describe(String description) {
return new Command(name, aliases, requireText(description, "Description of command " + name), children, arguments,
action, openToEveryone);
}
/** This command with {@code child} as a sub-command; a child that shares a name or alias with another child fails. */
public Command child(Command child) {
var added = new ArrayList<>(children);
for (var existing : children) {
for (var word : child.words()) {
if (existing.answersTo(word)) {
throw new IllegalArgumentException("Command " + name + " has a sub-command answering to " + word
+ " already (" + existing.name + "), so " + child.name + " cannot use it");
}
}
}
added.add(child);
return new Command(name, aliases, description, added, arguments, action, openToEveryone);
}
/** This command taking {@code argument} next; an optional argument may not come before a required one, nothing may
* follow an argument that takes the rest of the line, and two arguments cannot share a name.
*/
public Command argument(Argument<?> argument) {
var added = new ArrayList<>(arguments);
if (!added.isEmpty() && added.getLast().takesRestOfLine()) {
throw new IllegalArgumentException("Argument " + argument.name() + " of command " + name + " follows "
+ added.getLast().name() + ", which takes the rest of the line");
}
if (!added.isEmpty() && added.getLast().isOptional() && !argument.isOptional()) {
throw new IllegalArgumentException("Required argument " + argument.name() + " of command " + name
+ " follows the optional argument " + added.getLast().name());
}
if (added.stream().anyMatch(existing -> existing.name().equals(argument.name()))) {
throw new IllegalArgumentException("Command " + name + " has an argument named " + argument.name() + " already");
}
added.add(argument);
return new Command(name, aliases, description, children, added, action, openToEveryone);
}
/** This command running {@code action}; a command without an action only groups its children. */
public Command runs(CommandAction action) {
return new Command(name, aliases, description, children, arguments, Objects.requireNonNull(action, "action"),
openToEveryone);
}
/** This command usable by every sender; by default only operators may run it. */
public Command openToEveryone() {
return new Command(name, aliases, description, children, arguments, action, true);
}
public String name() {
return name;
}
public List<String> aliases() {
return aliases;
}
/** The help text, empty when the module gave none. */
public String description() {
return description;
}
public List<Command> children() {
return children;
}
public List<Argument<?>> arguments() {
return arguments;
}
/** What the command runs; empty for a command that only groups its children. */
public Optional<CommandAction> action() {
return Optional.ofNullable(action);
}
/** Whether every sender may run this command, not only operators. */
public boolean isOpenToEveryone() {
return openToEveryone;
}
/** Whether {@code word} is this command's name or one of its aliases. */
public boolean answersTo(String word) {
return name.equals(word) || aliases.contains(word);
}
/** The name and the aliases. */
public List<String> words() {
var words = new ArrayList<String>();
words.add(name);
words.addAll(aliases);
return words;
}
@Override
public String toString() {
return "command " + name;
}
private static void requireWord(String word, String what) {
if (word == null || !NAME.matcher(word).matches()) {
throw new IllegalArgumentException(what + " '" + word + "' must be lower case letters, digits and '-'");
}
}
private static String requireText(String text, String what) {
return Objects.requireNonNull(text, what);
}
}
@@ -0,0 +1,11 @@
package com.volmit.tooling;
/**
* What a command does. The host runs it on a worker thread, never on the server's main thread or a region thread, so it
* may block; to touch the world it asks the platform for the right thread. What it throws reaches the sender as an error
* and the module's log.
*/
@FunctionalInterface
public interface CommandAction {
void run(CommandContext context) throws Exception;
}
@@ -0,0 +1,33 @@
package com.volmit.tooling;
import com.volmit.resource.PlatformRegistries;
import com.volmit.world.PackWorld;
import java.util.Optional;
/**
* One run of a command, or one completion: the arguments parsed so far, who sent it and what it runs against. Valid only
* while the action or the suggestions run.
*/
public interface CommandContext {
/**
* The value of {@code argument}, or its fallback when the sender left it out.
*
* @throws IllegalStateException when the argument is required and has no value yet, as in the suggestions of an
* argument that comes before it
*/
<T> T get(Argument<T> argument);
/** Who sent the command. */
Sender sender();
/** The pack the host resolved for this command: the one named by {@code pack=<name>}, else the pack of the sender's
* world, else the pack of the sender's open studio.
*/
ToolPack pack();
/** The world the sender stands in, when it generates with {@link #pack()}; empty for the console or another pack's world. */
Optional<PackWorld> world();
/** The platform's registries; empty when the host runs without a platform. */
Optional<PlatformRegistries> platform();
}
@@ -0,0 +1,14 @@
package com.volmit.tooling;
import com.volmit.object.GeneratedObject;
import java.io.IOException;
/** The host's object file format, so tools can stage object files inside their own transactions. */
public interface ObjectCodec {
/** The file name extension the host reads below the folder of {@link com.volmit.resource.PackResources#OBJECTS}, such as {@code .iob}. */
String extension();
byte[] encode(GeneratedObject object) throws IOException;
GeneratedObject decode(byte[] bytes) throws IOException;
}
@@ -0,0 +1,11 @@
package com.volmit.tooling;
import java.io.IOException;
import java.nio.file.Path;
/** A change to the pack's files, run by {@link ToolPack#edit}. */
@FunctionalInterface
public interface PackEdit<T> {
/** Changes files below {@code packRoot}; atomicity across files is the edit's own job. */
T apply(Path packRoot) throws IOException;
}
@@ -0,0 +1,24 @@
package com.volmit.tooling;
import java.util.Optional;
/**
* Who sent a command. Safe from any thread: the host delivers messages on the thread the platform needs. Messages are
* plain text, and the host styles them; there is no colour and no translation.
*/
public interface Sender {
/** The sender's name as the platform shows it, such as a player's name or "Server". */
String name();
/** A plain line; the host styles it as information. */
void info(String message);
/** A plain line; the host styles it as a success. */
void success(String message);
/** A plain line; the host styles it as an error. */
void error(String message);
/** The platform's own sender as {@code type}, such as a Bukkit {@code Player}; empty when it is not one. For platform parts. */
<T> Optional<T> extension(Class<T> type);
}
@@ -0,0 +1,10 @@
package com.volmit.tooling;
import java.util.List;
/** Completions for one {@link Argument}, asked while the sender types, so keep it cheap. */
@FunctionalInterface
public interface Suggestions {
/** Candidate words; the host keeps those that start with what the sender typed. */
List<String> suggest(CommandContext context);
}
@@ -0,0 +1,35 @@
package com.volmit.tooling;
import com.volmit.ModuleLog;
import com.volmit.config.PackSettings;
import com.volmit.resource.PackResources;
import java.io.IOException;
import java.nio.file.Path;
/**
* A pack as tools see it: its current resources, its folder, and the one way to change files in it. Tools are file tools,
* so a {@link Path} is honest here; it is confined to {@link #edit} and {@link #outputFolder}.
*/
public interface ToolPack {
/** The current snapshot; a new one after every edit, so never keep it across an edit. */
PackResources resources();
/** Every settings entry of the pack, as validators see them. */
PackSettings settings();
/**
* Runs {@code edit} with this pack locked against other edits and hotloads, then reloads the resources once if it
* returned normally. One edit runs at a time per pack, so a second caller waits. An edit that throws leaves no reload
* behind, so it must leave the files as it found them; multi-file atomicity is the edit's own job.
*/
<T> T edit(PackEdit<T> edit) throws IOException;
/** A folder outside the pack for what tools produce, such as exports; created on first use. */
Path outputFolder();
/** Reads and writes pack objects in the host's object file format. */
ObjectCodec objects();
/** The log of the module that asked. */
ModuleLog log();
}
@@ -1,11 +1,19 @@
package com.volmit.tooling;
/**
* Where a module adds its tools to the studio, given in {@link com.volmit.ModuleSetup#tooling()} and accepted only while
* Where a module adds its tools, given in {@link com.volmit.ModuleSetup#tooling()} and accepted only while
* {@link com.volmit.IrisModule#setup} runs. A view's id is the module's id or starts with it and {@code /}; a second
* view with an id already registered, of either kind, fails the pack load, naming both modules.
* view with an id already registered, of either kind, fails the pack load, naming both modules. A host without tooling,
* such as a build check, accepts the registrations and ignores them.
*/
public interface ToolingRegistry {
/** Adds a view to the studio: block scenes such as the pack's objects, or block patterns such as its palettes. */
void registerView(StudioView view);
/**
* Mounts {@code command} under the host's command root, such as {@code /iris structure}. The command's name, and each
* of its aliases, is a root name; one that another module of the pack took already fails the pack load, naming
* both modules.
*/
void registerCommand(Command command);
}
@@ -0,0 +1,132 @@
package com.volmit.tooling;
import com.volmit.config.Reference;
import com.volmit.resource.PackResources;
import com.volmit.resource.PlatformRegistries;
import com.volmit.resource.ResourceId;
import com.volmit.resource.ResourceKind;
import org.junit.jupiter.api.Test;
import java.lang.reflect.Proxy;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.*;
class ArgumentTest {
enum Mode { STRICT_SHAPE, LOOSE }
static final class Plan {}
private static final ResourceKind<Plan> PLANS = ResourceKind.of("test:plan", "plans", Plan.class);
private static PackResources resources() {
return (PackResources) Proxy.newProxyInstance(PackResources.class.getClassLoader(), new Class<?>[]{PackResources.class},
(proxy, method, arguments) -> switch (method.getName()) {
case "packId" -> ResourceId.parse("demo:pack");
case "idOf" -> ResourceId.ofPackKey("demo", (String) arguments[0]);
case "ids" -> List.of(ResourceId.parse("demo:villages/plains"), ResourceId.parse("demo:villages/desert"),
ResourceId.parse("other:castle"));
default -> throw new UnsupportedOperationException(method.getName());
});
}
private static CommandContext context(Optional<PlatformRegistries> platform) {
var pack = (ToolPack) Proxy.newProxyInstance(ToolPack.class.getClassLoader(), new Class<?>[]{ToolPack.class},
(proxy, method, arguments) -> method.getName().equals("resources") ? resources() : null);
return (CommandContext) Proxy.newProxyInstance(CommandContext.class.getClassLoader(), new Class<?>[]{CommandContext.class},
(proxy, method, arguments) -> switch (method.getName()) {
case "pack" -> pack;
case "platform" -> platform;
default -> throw new UnsupportedOperationException(method.getName());
});
}
private static CommandContext context() {
return context(Optional.empty());
}
@Test
void wordsAndTextTakeTheirTextAsIs() {
assertEquals("plains", Argument.word("structure").parse("plains", context()));
assertEquals("a b c", Argument.text("message").parse("a b c", context()));
assertTrue(Argument.text("message").takesRestOfLine());
assertFalse(Argument.word("structure").takesRestOfLine());
}
@Test
void integersAndDecimalsStayInTheirRange() {
var radius = Argument.integer("radius", 1, 100);
assertEquals(48L, radius.parse("48", context()));
assertEquals("radius must be a whole number from 1 to 100",
assertThrows(IllegalArgumentException.class, () -> radius.parse("101", context())).getMessage());
assertEquals("radius must be a whole number",
assertThrows(IllegalArgumentException.class, () -> radius.parse("many", context())).getMessage());
var scale = Argument.decimal("scale", 0.5, 2);
assertEquals(1.25, scale.parse("1.25", context()));
assertThrows(IllegalArgumentException.class, () -> scale.parse("NaN", context()));
assertThrows(IllegalArgumentException.class, () -> scale.parse("3", context()));
}
@Test
void flagsAcceptTrueAndFalseInAnyCase() {
var verbose = Argument.flag("verbose");
assertTrue(verbose.parse("TRUE", context()));
assertFalse(verbose.parse("false", context()));
assertThrows(IllegalArgumentException.class, () -> verbose.parse("yes", context()));
assertEquals(List.of("false"), verbose.complete("f", context()));
}
@Test
void choicesAreWrittenInLowerCaseWithDashesAndNameTheOptionsOnAMiss() {
var mode = Argument.choice("mode", Mode.class);
assertEquals(Mode.STRICT_SHAPE, mode.parse("strict-shape", context()));
assertEquals(Mode.LOOSE, mode.parse("LOOSE", context()));
var miss = assertThrows(IllegalArgumentException.class, () -> mode.parse("wide", context()));
assertEquals("mode must be one of strict-shape, loose", miss.getMessage());
assertEquals(List.of("strict-shape"), mode.complete("st", context()));
assertEquals(List.of("loose", "strict-shape"), mode.complete("", context()));
}
@Test
void resourcesAreWrittenAsThePacksKeyOrTheFullIdAndMustExist() {
var plan = Argument.resource("structure", PLANS);
assertEquals(ResourceId.parse("demo:villages/plains"), plan.parse("villages/plains", context()));
assertEquals(ResourceId.parse("other:castle"), plan.parse("other:castle", context()));
var missing = assertThrows(IllegalArgumentException.class, () -> plan.parse("villages/swamp", context()));
assertEquals("No plans resource 'villages/swamp' in this pack", missing.getMessage());
assertEquals(List.of("villages/desert", "villages/plains"), plan.complete("vil", context()));
assertEquals(List.of("other:castle"), plan.complete("oth", context()));
}
@Test
void registeredIdsComeFromThePlatformAndMayLeaveOutMinecraft() {
PlatformRegistries registries = registry -> registry == Reference.STRUCTURE
? Set.of(ResourceId.parse("minecraft:village_plains"), ResourceId.parse("mod:tower"))
: Set.of();
var structure = Argument.registered("structure", Reference.STRUCTURE);
var context = context(Optional.of(registries));
assertEquals(ResourceId.parse("minecraft:village_plains"), structure.parse("village_plains", context));
assertEquals(ResourceId.parse("mod:tower"), structure.parse("mod:tower", context));
assertEquals("No structure 'mod:keep' is registered",
assertThrows(IllegalArgumentException.class, () -> structure.parse("mod:keep", context)).getMessage());
assertEquals(List.of("village_plains"), structure.complete("vill", context));
assertEquals(List.of("mod:tower"), structure.complete("mod", context));
assertThrows(IllegalArgumentException.class, () -> structure.parse("village_plains", context()));
}
@Test
void anArgumentWithAFallbackIsOptionalAndCompletesWhatTheModuleSuggestsToo() {
var required = Argument.word("bay");
assertFalse(required.isOptional());
assertNull(required.fallback());
var bay = required.orElse("main").describe("The bay to open").suggesting(context -> List.of("north", "main", "north"));
assertTrue(bay.isOptional());
assertEquals("main", bay.fallback());
assertEquals("The bay to open", bay.description());
assertEquals(List.of("main", "north"), bay.complete("", context()));
assertEquals(List.of("north"), bay.complete("N", context()));
assertThrows(NullPointerException.class, () -> required.orElse(null));
}
}
@@ -0,0 +1,71 @@
package com.volmit.tooling;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
class CommandTest {
@Test
void namesAreLowerCaseWordsOfLettersDigitsAndDashes() {
assertEquals("verify-all", Command.named("verify-all").name());
assertThrows(IllegalArgumentException.class, () -> Command.named("Verify"));
assertThrows(IllegalArgumentException.class, () -> Command.named("two words"));
assertThrows(IllegalArgumentException.class, () -> Command.named(""));
assertThrows(IllegalArgumentException.class, () -> Command.named("a").alias("B"));
}
@Test
void aCommandAnswersToItsNameAndAliasesButNotToDuplicatesOfThem() {
var command = Command.named("structure").alias("struct", "str");
assertTrue(command.answersTo("structure") && command.answersTo("str"));
assertFalse(command.answersTo("list"));
assertEquals(List.of("structure", "struct", "str"), command.words());
assertThrows(IllegalArgumentException.class, () -> command.alias("structure"));
assertThrows(IllegalArgumentException.class, () -> command.alias("str"));
}
@Test
void methodsReturnChangedCopies() {
var plain = Command.named("list");
var described = plain.describe("Lists structures").openToEveryone().runs(context -> { });
assertEquals("", plain.description());
assertFalse(plain.isOpenToEveryone());
assertTrue(plain.action().isEmpty());
assertEquals("Lists structures", described.description());
assertTrue(described.isOpenToEveryone());
assertTrue(described.action().isPresent());
}
@Test
void childrenMayNotShareANameOrAliasWithTheirSiblings() {
var parent = Command.named("structure").child(Command.named("list").alias("ls"));
var clash = assertThrows(IllegalArgumentException.class, () -> parent.child(Command.named("ls")));
assertTrue(clash.getMessage().contains("ls"), clash.getMessage());
assertThrows(IllegalArgumentException.class, () -> parent.child(Command.named("other").alias("list")));
assertEquals(2, parent.child(Command.named("info")).children().size());
assertEquals(1, parent.children().size());
}
@Test
void anOptionalArgumentMayNotComeBeforeARequiredOne() {
var optional = Command.named("verify").argument(Argument.integer("radius", 1, 10).orElse(5L));
var late = assertThrows(IllegalArgumentException.class, () -> optional.argument(Argument.word("structure")));
assertTrue(late.getMessage().contains("follows the optional argument radius"), late.getMessage());
assertEquals(2, Command.named("verify").argument(Argument.word("structure"))
.argument(Argument.integer("radius", 1, 10).orElse(5L)).arguments().size());
}
@Test
void nothingFollowsTheArgumentThatTakesTheRestOfTheLine() {
var text = Command.named("say").argument(Argument.text("message"));
assertThrows(IllegalArgumentException.class, () -> text.argument(Argument.word("after").orElse("x")));
}
@Test
void argumentNamesAreUniqueWithinACommand() {
var one = Command.named("copy").argument(Argument.word("name"));
assertThrows(IllegalArgumentException.class, () -> one.argument(Argument.word("name")));
}
}
@@ -0,0 +1,19 @@
package com.volmit.host;
import com.volmit.tooling.Command;
import java.util.Objects;
/** A root command and the module that registered it, which the host names when two modules claim one root name and
* which owns the log and the failures of the command's actions.
*/
public record CommandRegistration(Command command, DiscoveredModule module) {
public CommandRegistration {
Objects.requireNonNull(command, "command");
Objects.requireNonNull(module, "module");
}
@Override
public String toString() {
return command + " of module " + module;
}
}
@@ -39,6 +39,7 @@ public final class FeatureCatalog {
private final Map<Class<?>, List<?>> providersByService;
private final Optional<PlacementTypeRegistration> placementType;
private final List<StudioViewRegistration> studioViews;
private final List<CommandRegistration> commands;
FeatureCatalog(
Map<Class<?>, FeatureDescriptor<?>> settings,
@@ -48,9 +49,11 @@ public final class FeatureCatalog {
List<LifecycleRegistration> lifecycles,
List<ServiceRegistration> services,
PlacementTypeRegistration placementType,
Collection<StudioViewRegistration> studioViews) {
Collection<StudioViewRegistration> studioViews,
Collection<CommandRegistration> commands) {
this.placementType = Optional.ofNullable(placementType);
this.studioViews = sorted(studioViews, registration -> registration.view().id());
this.commands = sorted(commands, registration -> registration.command().name());
this.settings = Map.copyOf(settings);
this.mantle = Map.copyOf(mantle);
this.resourceKinds = sorted(resourceKinds, registration -> registration.kind().id());
@@ -89,6 +92,11 @@ public final class FeatureCatalog {
return studioViews;
}
/** The root commands modules registered, by command name; hosts with tooling mount them, other hosts ignore them. */
public List<CommandRegistration> commands() {
return commands;
}
/** The lifecycle hooks modules registered, by module id, each module's in the order it registered them. */
public List<LifecycleRegistration> lifecycles() {
return lifecycles;
@@ -10,6 +10,7 @@ import com.volmit.mantle.MantleLifetime;
import com.volmit.resource.ResourceId;
import com.volmit.resource.ResourceKind;
import com.volmit.service.Providers;
import com.volmit.tooling.Command;
import com.volmit.tooling.StudioView;
import com.volmit.tooling.ToolingRegistry;
import com.volmit.validation.Validator;
@@ -30,7 +31,8 @@ import java.util.Set;
* settings ids must be the registering module's id or start with it and '/' ({@link com.volmit.ModuleInfo#ownsId}).
* Resource kinds have unique ids, types and folders, and no kind may read a folder the host reserves for its own
* files. Lifecycle hooks and service providers are registered by the module that owns them; a service whose providers
* are {@link Providers#ONE} has at most one. Studio views have ids unique across their kinds that the registering module owns. A failed
* are {@link Providers#ONE} has at most one. Studio views have ids unique across their kinds that the registering module owns.
* Root commands have names and aliases unique across the pack's modules. A failed
* registration leaves the registry unchanged. A failed module callback invalidates the host's whole build. This does
* not decode JSON, discover modules or instantiate settings.
*/
@@ -46,6 +48,7 @@ public final class ModuleRegistry implements FeatureRegistry, ToolingRegistry {
private final List<LifecycleRegistration> lifecycles = new ArrayList<>();
private final List<ServiceRegistration> services = new ArrayList<>();
private final Map<ResourceId, StudioViewRegistration> studioViews = new HashMap<>();
private final List<CommandRegistration> commands = new ArrayList<>();
private final Set<String> reservedFolders;
private final List<DiscoveredModule> registered = new ArrayList<>();
private PlacementTypeRegistration placementType;
@@ -194,6 +197,26 @@ public final class ModuleRegistry implements FeatureRegistry, ToolingRegistry {
studioViews.put(id, added);
}
@Override
public void registerCommand(Command command) {
checkOpen();
Objects.requireNonNull(command, "command");
requireRegistering("Command " + command.name());
var added = new CommandRegistration(command, registering);
for (var existing : commands) {
requireDistinctRootNames(existing, added);
}
commands.add(added);
}
private static void requireDistinctRootNames(CommandRegistration existing, CommandRegistration added) {
for (var word : added.command().words()) {
if (!existing.command().answersTo(word)) continue;
throw new IllegalArgumentException("Command root " + word + " is registered by module " + existing.module()
+ " already, and module " + added.module() + " registers it too; give one of them another name or alias");
}
}
/** Catalogs a settings type named by a stage's when(...), whose owner {@link StageGraphBuilder}
* has checked. Several stages, and the owner's {@link #registerSettings}, may name one type. Call
* it after every module has registered, so the owner is known.
@@ -215,7 +238,7 @@ public final class ModuleRegistry implements FeatureRegistry, ToolingRegistry {
public FeatureCatalog freeze() {
if (catalog == null) {
catalog = new FeatureCatalog(settings, mantle, resourceKinds.values(), validators, lifecycles, services,
placementType, studioViews.values());
placementType, studioViews.values(), commands);
}
return catalog;
}
@@ -132,6 +132,56 @@ class ModuleRegistryTest {
assertTrue(views.get(1).toString().startsWith("pattern view iris:objects/footprints of module"), views.get(1).toString());
}
private static IrisModule commandModule(String id, com.volmit.tooling.Command... roots) {
return new IrisModule() {
public ModuleInfo info() { return ModuleInfo.of(id, id, "1"); }
public void setup(ModuleSetup setup) {
for (var root : roots) setup.tooling().registerCommand(root);
}
};
}
@Test
void rootCommandsAreCataloguedByNameAndKeepTheirModule() {
var registry = new ModuleRegistry();
ModuleSetups.run(DiscoveredModule.builtIn(commandModule("test:b",
com.volmit.tooling.Command.named("zeta"))), new StageGraphBuilder(), registry);
ModuleSetups.run(DiscoveredModule.builtIn(commandModule("test:a",
com.volmit.tooling.Command.named("alpha").alias("a"))), new StageGraphBuilder(), registry);
var commands = registry.freeze().commands();
assertEquals(List.of("alpha", "zeta"), commands.stream().map(root -> root.command().name()).toList());
assertEquals("test:a", commands.getFirst().module().info().id().toString());
assertThrows(IllegalStateException.class,
() -> registry.registerCommand(com.volmit.tooling.Command.named("late")));
}
@Test
void twoModulesClaimingOneRootNameOrAliasFailNamingBoth() {
var registry = new ModuleRegistry();
ModuleSetups.run(DiscoveredModule.builtIn(commandModule("test:first",
com.volmit.tooling.Command.named("structure").alias("str"))), new StageGraphBuilder(), registry);
var sameName = assertThrows(IllegalArgumentException.class, () -> ModuleSetups.run(DiscoveredModule.builtIn(
commandModule("test:second", com.volmit.tooling.Command.named("structure"))), new StageGraphBuilder(), registry));
assertTrue(sameName.getMessage().contains("Command root structure is registered by module"), sameName.getMessage());
assertTrue(sameName.getMessage().contains("test:first") && sameName.getMessage().contains("test:second"), sameName.getMessage());
var aliasOfFirst = assertThrows(IllegalArgumentException.class, () -> ModuleSetups.run(DiscoveredModule.builtIn(
commandModule("test:third", com.volmit.tooling.Command.named("str"))), new StageGraphBuilder(), registry));
assertTrue(aliasOfFirst.getMessage().contains("Command root str is registered by module"), aliasOfFirst.getMessage());
assertEquals(1, registry.freeze().commands().size());
}
@Test
void aPackLoadFailsWhenTwoModulesClaimOneRootName() {
var failure = assertThrows(ModuleLoadException.class, () -> LoadedModules.load(List.of(
DiscoveredModule.builtIn(commandModule("test:first", com.volmit.tooling.Command.named("tools"))),
DiscoveredModule.builtIn(commandModule("test:second", com.volmit.tooling.Command.named("tools")))),
Map.of(), List.of(), List.of()));
assertTrue(failure.getMessage().contains("test:first") && failure.getMessage().contains("test:second"), failure.getMessage());
}
private static com.volmit.tooling.PatternView patternView(String id) {
return new com.volmit.tooling.PatternView() {
public com.volmit.resource.ResourceId id() { return com.volmit.resource.ResourceId.parse(id); }