Add mod command integration for Build 42: command hooks, lookup extensions, registry, and validation mechanisms. Include corresponding tests and documentation.

This commit is contained in:
Overlord committed 2026-10-03 11:27:06 +02:00
1 parent 22077514fe
commit af7174e128
26 files changed
+1117 -30

No files matched your search

@@ -6,6 +6,7 @@ import dev.overlord.zomboidforge.api.Mod;
import dev.overlord.zomboidforge.api.TickEvent;
import dev.overlord.zomboidforge.api.ZomboidForge;
import dev.overlord.zomboidforge.api.storage.StorageException;
import dev.overlord.zomboidforge.core.commands.CommandRegistry;
import dev.overlord.zomboidforge.core.config.ForgeSettings;
import dev.overlord.zomboidforge.core.mods.GameClasses;
import dev.overlord.zomboidforge.core.mods.ModDiscovery;
@@ -52,6 +53,7 @@ public final class Forge
private final Path directory;
private final @Nullable ModVersion api;
private final CommandRegistry commands;
private volatile List<ModLoader.LoadedMod> mods = List.of();
private volatile ForgeSettings settings = ForgeSettings.DEFAULTS;
@@ -61,32 +63,41 @@ public final class Forge
* @param directory the ZomboidForge directory
* @param api the API version mods are checked against, or {@code null} to skip the
* check
* @param commands checks the command classes that mods register against the running game
* version
*/
public Forge(Path directory, @Nullable ModVersion api)
public Forge(Path directory, @Nullable ModVersion api, CommandRegistry.Validator commands)
{
this.directory = directory;
this.api = api;
this.commands = new CommandRegistry(commands, this::commandsOpen);
}
/**
* Directory from {@value #DIRECTORY_PROPERTY} (default {@value #DEFAULT_DIRECTORY}); API
* version from {@link ZomboidForge#VERSION}. Builds without a release version ({@code dev},
* {@code 0.0.0-...}) skip the API check.
*
* @param commands checks the command classes that mods register against the running game
* version
*/
public static Forge fromSystemProperties()
public static Forge fromSystemProperties(CommandRegistry.Validator commands)
{
Path directory = Path.of(System.getProperty(Forge.DIRECTORY_PROPERTY, Forge.DEFAULT_DIRECTORY));
ModVersion api = ModVersion.tryParse(ZomboidForge.VERSION)
.filter(version -> version.major() != 0 || version.minor() != 0 || version.patch() != 0)
.orElse(null);
return new Forge(directory, api);
return new Forge(directory, api, commands);
}
public Lifecycle.Phase phase() { return this.lifecycle.phase(); }
public List<ModLoader.LoadedMod> mods() { return this.mods; }
/** The admin command classes that mods registered, in registration order. */
public List<Class<?>> commands() { return this.commands.classes(); }
/**
* Reads {@code forge.toml}, then discovers, checks, and loads every mod in
* {@code <directory>/mods}. Called once on the main thread, which becomes the thread of
@@ -246,6 +257,9 @@ public final class Forge
catch (StorageException e) { this.logger.log(System.Logger.Level.ERROR, "Closing the storage failed.", e); }
}
/** Mods register commands on the main thread while they load. */
private boolean commandsOpen() { return this.queue.isMainThread() && this.lifecycle.phase() == Lifecycle.Phase.BOOTING; }
/** The main thread may use storage only before the main loop runs. */
private boolean storageForbidden() { return this.queue.isMainThread() && this.lifecycle.phase() == Lifecycle.Phase.RUNNING; }
@@ -260,7 +274,8 @@ public final class Forge
this.queue.forMod(id, logger),
executors.modThread(),
executors.async(),
new ModTables(id, storage, logger)
new ModTables(id, storage, logger),
this.commands.forMod(logger)
);
}
}
@@ -0,0 +1,74 @@
package dev.overlord.zomboidforge.core.commands;
import dev.overlord.zomboidforge.api.Commands;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.function.BooleanSupplier;
/**
* The admin command classes that mods registered, in registration order. What a command class
* has to look like depends on the Project Zomboid version, so a {@link Validator} from the compat
* module checks every class. Registration happens only while the mods load, on the main thread;
* the compat hooks read {@link #classes()} on the main thread afterwards.
*/
public final class CommandRegistry
{
/** Checks a command class against the command framework of the running game version. */
@FunctionalInterface
public interface Validator
{
/**
* @param registered the classes registered before, by any mod
* @throws IllegalArgumentException naming what is wrong with {@code command}
*/
void check(Class<?> command, List<Class<?>> registered);
}
private final Validator validator;
private final BooleanSupplier open;
private volatile List<Class<?>> classes = List.of();
/** @param open whether registration is allowed now, on the calling thread */
public CommandRegistry(Validator validator, BooleanSupplier open)
{
this.validator = Objects.requireNonNull(validator);
this.open = Objects.requireNonNull(open);
}
/** Every registered class, in registration order. */
public List<Class<?>> classes() { return this.classes; }
/**
* Registration for one mod; registered classes are logged with {@code logger}. Exceptions do
* not name the mod: one thrown in the mod's {@code onLoad()} is reported with its id.
*/
public Commands forMod(System.Logger logger)
{
return command ->
{
this.register(command);
logger.log(System.Logger.Level.INFO, "Registered the command class '" + command.getName() + "'.");
};
}
private synchronized void register(Class<?> command)
{
Objects.requireNonNull(command, "command");
if (!this.open.getAsBoolean())
throw new IllegalStateException("Commands can only be registered on the main thread while the mod loads (constructor or onLoad()).");
if (this.classes.contains(command))
throw new IllegalArgumentException("The command class '" + command.getName() + "' is registered already.");
this.validator.check(command, this.classes);
List<Class<?>> updated = new ArrayList<>(this.classes);
updated.add(command);
this.classes = List.copyOf(updated);
}
}
@@ -0,0 +1,9 @@
/**
* Admin commands of loaded mods: the registry that the compat hooks consult.
*
* @noinspection UnstableApiUsage, RedundantSuppression
*/
@NotNullByDefault
package dev.overlord.zomboidforge.core.commands;
import org.jetbrains.annotations.NotNullByDefault;
@@ -1,6 +1,7 @@
package dev.overlord.zomboidforge.core.mods;
import dev.overlord.zomboidforge.api.AsyncExecutor;
import dev.overlord.zomboidforge.api.Commands;
import dev.overlord.zomboidforge.api.Events;
import dev.overlord.zomboidforge.api.GameVersion;
import dev.overlord.zomboidforge.api.MainThread;
@@ -46,7 +47,8 @@ public final class ModLoader
MainThread main,
ModThread modThread,
AsyncExecutor async,
ModStorage storage
ModStorage storage,
Commands commands
) implements ModContext {}
private ModLoader() {}
@@ -93,7 +95,8 @@ public final class ModLoader
provided.main(),
provided.modThread(),
provided.async(),
provided.storage()
provided.storage(),
provided.commands()
);
loaded.add(new LoadedMod(descriptor, candidate.directory(), loader, ModLoader.create(descriptor, loader, context)));
@@ -1,13 +1,14 @@
package dev.overlord.zomboidforge.core.mods;
import dev.overlord.zomboidforge.api.AsyncExecutor;
import dev.overlord.zomboidforge.api.Commands;
import dev.overlord.zomboidforge.api.Events;
import dev.overlord.zomboidforge.api.MainThread;
import dev.overlord.zomboidforge.api.ModThread;
import dev.overlord.zomboidforge.api.storage.ModStorage;
/** The threads, event registration, and storage of one mod, created before its entry point. */
public record ModServices(Events events, MainThread main, ModThread modThread, AsyncExecutor async, ModStorage storage)
/** The threads, event and command registration, and storage of one mod, created before its entry point. */
public record ModServices(Events events, MainThread main, ModThread modThread, AsyncExecutor async, ModStorage storage, Commands commands)
{
/** Creates the services of one mod. */
@FunctionalInterface
@@ -11,6 +11,7 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import testmods.CommandMod;
import testmods.ContextMod;
import testmods.ErrorMod;
import testmods.Recorder;
@@ -19,6 +20,7 @@ import testmods.ThreadMod;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
@@ -27,6 +29,7 @@ import java.util.function.BooleanSupplier;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -45,6 +48,9 @@ class ForgeTest
private Path gameJar;
private Path storageFile;
/** Classes that mods registered as commands, as {@code "<name> after <registered count>"}; every class is accepted. */
private final List<String> checkedCommands = new ArrayList<>();
@BeforeEach
void setUp() throws IOException
{
@@ -56,7 +62,10 @@ class ForgeTest
Recorder.EVENTS.clear();
}
private Forge forge() { return new Forge(this.directory, ModVersion.parse("0.3.0")); }
private Forge forge()
{
return new Forge(this.directory, ModVersion.parse("0.3.0"), (command, registered) -> this.checkedCommands.add(command.getName() + " after " + registered.size()));
}
private Forge load() throws ModLoadException
{
@@ -105,6 +114,25 @@ class ForgeTest
);
}
@Test
void modsRegisterCommandsOnlyWhileTheyLoad() throws Exception
{
TestMods.folder(this.mods, "commands", TestMods.toml("commands", CommandMod.class.getName(), ""), Map.of(
"testmods/CommandMod", TestMods.classFile(CommandMod.class),
"testmods/CommandMod$Command", TestMods.classFile(CommandMod.Command.class)
));
Forge forge = this.load();
assertEquals(List.of("testmods.CommandMod$Command"), forge.commands().stream().map(Class::getName).toList());
assertEquals(List.of("testmods.CommandMod$Command after 0"), this.checkedCommands);
forge.started();
assertInstanceOf(IllegalStateException.class, ForgeTest.field(forge.mods().getFirst().mod(), "lateRegistration"));
assertEquals(1, forge.commands().size());
}
@Test
void modsSeeTheirContextAndSettingsInTheConstructor() throws Exception
{
@@ -0,0 +1,78 @@
package dev.overlord.zomboidforge.core.commands;
import dev.overlord.zomboidforge.api.Commands;
import dev.overlord.zomboidforge.core.RecordingLogger;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
class CommandRegistryTest
{
private final List<String> checked = new ArrayList<>();
private final AtomicBoolean open = new AtomicBoolean(true);
private final RecordingLogger logger = new RecordingLogger();
/** Records every check as {@code "<simple name> after <registered count>"} and rejects {@link Integer}. */
private final CommandRegistry registry = new CommandRegistry(
(command, registered) ->
{
this.checked.add(command.getSimpleName() + " after " + registered.size());
if (command == Integer.class) throw new IllegalArgumentException("'java.lang.Integer' cannot be a command.");
},
this.open::get
);
private final Commands commands = this.registry.forMod(this.logger);
@Test
void registersInOrderAndShowsTheValidatorTheEarlierClasses()
{
this.commands.register(String.class);
this.commands.register(Long.class);
assertEquals(List.of(String.class, Long.class), this.registry.classes());
assertEquals(List.of("String after 0", "Long after 1"), this.checked);
assertEquals(
List.of("INFO: Registered the command class 'java.lang.String'.", "INFO: Registered the command class 'java.lang.Long'."),
this.logger.messages
);
}
@Test
void rejectedClassesAreNotRegistered()
{
IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> this.commands.register(Integer.class));
assertEquals("'java.lang.Integer' cannot be a command.", e.getMessage());
assertEquals(List.of(), this.registry.classes());
assertEquals(List.of(), this.logger.messages);
}
@Test
void rejectsTheSameClassTwice()
{
this.commands.register(String.class);
IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> this.commands.register(String.class));
assertEquals("The command class 'java.lang.String' is registered already.", e.getMessage());
assertEquals(List.of(String.class), this.registry.classes());
}
@Test
void rejectsRegistrationWhileClosed()
{
this.open.set(false);
IllegalStateException e = assertThrows(IllegalStateException.class, () -> this.commands.register(String.class));
assertEquals("Commands can only be registered on the main thread while the mod loads (constructor or onLoad()).", e.getMessage());
assertEquals(List.of(), this.checked);
}
}
@@ -0,0 +1,27 @@
package testmods;
import dev.overlord.zomboidforge.api.Mod;
import org.jetbrains.annotations.Nullable;
/**
* Entry point that tests package into a mod jar. Registers {@link Command} in {@code onLoad()}
* and tries again in {@code onServerStarted()}, which is too late.
*/
public final class CommandMod extends Mod
{
/** Stands in for a command class; the tests' validator accepts any class. */
public static final class Command {}
public volatile @Nullable RuntimeException lateRegistration;
@Override
public void onLoad() { this.commands().register(CommandMod.Command.class); }
@Override
public void onServerStarted()
{
try { this.commands().register(CommandMod.Command.class); }
catch (RuntimeException e) { this.lateRegistration = e; }
}
}