Add mod validation for annotations: schemas, migrations, configuration bounds, listener methods, and commands.
This commit is contained in:
1 parent
9af951b4be
commit
c79a90b88f
10 files changed
+389
-18
No files matched your search
@@ -485,6 +485,13 @@ mod and its libraries. The server does not start when a mod
|
||||
3. uses ZomboidForge classes outside the API, or
|
||||
4. contains classes in a ZomboidForge package, or a class with the name of a game class.
|
||||
|
||||
While it loads a mod, the server also checks the annotations: the entry point's listener and
|
||||
scheduled methods, `@Schema`/`@Migrate`/`@Key`/`@Min`/`@Max` on records, and the
|
||||
`@RegisterCommand` classes. `checkMod` runs the same rules on the built jar (records only when
|
||||
they carry one of these annotations), loading the classes without running any of their code.
|
||||
Objects passed to `events().register(...)` are only checked on the server, when they are
|
||||
registered.
|
||||
|
||||
Every problem of every mod is listed in the log.
|
||||
|
||||
## What a mod can see
|
||||
|
||||
@@ -95,6 +95,26 @@ public final class RecordBinder
|
||||
return keys;
|
||||
}
|
||||
|
||||
/**
|
||||
* The problems of the {@link Key}, {@link Min}, and {@link Max} annotations of {@code type}'s
|
||||
* components, as {@link #keys} and binding report them; empty when there are none. For
|
||||
* build-time checks.
|
||||
*/
|
||||
public static List<String> check(Class<? extends Record> type)
|
||||
{
|
||||
List<String> problems = new ArrayList<>();
|
||||
|
||||
try { RecordBinder.keys(type); }
|
||||
catch (IllegalArgumentException e) { problems.add(e.getMessage()); }
|
||||
|
||||
for (RecordComponent component : type.getRecordComponents()) {
|
||||
try { RecordBinder.bounds(component); }
|
||||
catch (IllegalArgumentException e) { problems.add(e.getMessage()); }
|
||||
}
|
||||
|
||||
return List.copyOf(problems);
|
||||
}
|
||||
|
||||
/** A record of {@code type} from {@code table}, or {@code null} when a problem was found. */
|
||||
public <T extends Record> @Nullable T record(Map<String, Object> table, Class<T> type, String path)
|
||||
{
|
||||
|
||||
@@ -43,8 +43,10 @@ import java.util.function.Consumer;
|
||||
* with a filter in front: only the commands of its module (and command) reach it. An
|
||||
* {@link EveryNTicks} method is a main-thread listener for {@link TickEvent} that only every n-th
|
||||
* tick reaches. {@link Every} methods are returned as schedules.
|
||||
*
|
||||
* <p>{@link #check} runs the same rules on a class without an object, for build-time checks.
|
||||
*/
|
||||
final class ListenerScanner
|
||||
public final class ListenerScanner
|
||||
{
|
||||
/** What {@link #scan} found, each list in registration order. */
|
||||
record Found(List<ListenerMethod> listeners, List<ScheduledMethod> schedules) {}
|
||||
@@ -83,11 +85,40 @@ final class ListenerScanner
|
||||
*/
|
||||
static Found scan(Object target)
|
||||
{
|
||||
Map<Class<?>, Method[]> hierarchy = ListenerScanner.declaredMethods(target.getClass());
|
||||
List<String> problems = new ArrayList<>();
|
||||
Found found = ListenerScanner.scan(target.getClass(), target, problems);
|
||||
|
||||
if (!problems.isEmpty()) throw new IllegalArgumentException(String.join(" ", problems));
|
||||
|
||||
return found;
|
||||
}
|
||||
|
||||
/**
|
||||
* The problems that {@code Events.register(Object)} reports for an object of {@code type}, one
|
||||
* per method or class; empty when there are none. Nothing is called.
|
||||
*/
|
||||
public static List<String> check(Class<?> type)
|
||||
{
|
||||
List<String> problems = new ArrayList<>();
|
||||
|
||||
try { ListenerScanner.scan(type, null, problems); }
|
||||
catch (IllegalArgumentException e) { problems.add(e.getMessage()); }
|
||||
|
||||
return List.copyOf(problems);
|
||||
}
|
||||
|
||||
/**
|
||||
* The annotated methods of {@code type}, bound to {@code target}; without a target, their
|
||||
* actions do nothing. Adds the problems to {@code problems}.
|
||||
*
|
||||
* @throws IllegalArgumentException when the methods of a class cannot be read
|
||||
*/
|
||||
private static Found scan(Class<?> type, @Nullable Object target, List<String> problems)
|
||||
{
|
||||
Map<Class<?>, Method[]> hierarchy = ListenerScanner.declaredMethods(type);
|
||||
List<Class<?>> types = List.copyOf(hierarchy.keySet());
|
||||
List<ListenerMethod> listeners = new ArrayList<>();
|
||||
List<ScheduledMethod> schedules = new ArrayList<>();
|
||||
List<String> problems = new ArrayList<>();
|
||||
|
||||
for (int i = 0; i < types.size(); i++)
|
||||
{
|
||||
@@ -128,8 +159,6 @@ final class ListenerScanner
|
||||
}
|
||||
}
|
||||
|
||||
if (!problems.isEmpty()) throw new IllegalArgumentException(String.join(" ", problems));
|
||||
|
||||
return new Found(List.copyOf(listeners), List.copyOf(schedules));
|
||||
}
|
||||
|
||||
@@ -189,7 +218,7 @@ final class ListenerScanner
|
||||
}
|
||||
|
||||
/** The listener for {@code method}, or {@code null} after adding its problems to {@code problems}. */
|
||||
private static @Nullable ListenerMethod listener(Object target, Method method, boolean modThread, @Nullable OnClientCommand clientCommand, String where, List<String> problems)
|
||||
private static @Nullable ListenerMethod listener(@Nullable Object target, Method method, boolean modThread, @Nullable OnClientCommand clientCommand, String where, List<String> problems)
|
||||
{
|
||||
Class<?>[] parameters = method.getParameterTypes();
|
||||
int before = problems.size();
|
||||
@@ -230,7 +259,7 @@ final class ListenerScanner
|
||||
}
|
||||
|
||||
/** The {@link TickEvent} listener for an {@link EveryNTicks} method, or {@code null} after adding its problems to {@code problems}. */
|
||||
private static @Nullable ListenerMethod everyNTicks(Object target, Method method, EveryNTicks annotation, String where, List<String> problems)
|
||||
private static @Nullable ListenerMethod everyNTicks(@Nullable Object target, Method method, EveryNTicks annotation, String where, List<String> problems)
|
||||
{
|
||||
int before = problems.size();
|
||||
int n = annotation.value();
|
||||
@@ -252,7 +281,7 @@ final class ListenerScanner
|
||||
}
|
||||
|
||||
/** The schedule of an {@link Every} method, or {@code null} after adding its problems to {@code problems}. */
|
||||
private static @Nullable ScheduledMethod every(Object target, Method method, Every annotation, String where, List<String> problems)
|
||||
private static @Nullable ScheduledMethod every(@Nullable Object target, Method method, Every annotation, String where, List<String> problems)
|
||||
{
|
||||
int before = problems.size();
|
||||
|
||||
@@ -300,13 +329,16 @@ final class ListenerScanner
|
||||
|
||||
/**
|
||||
* A handle for {@code method} of type {@code type}, bound to {@code target} for an instance
|
||||
* method, or {@code null} after adding the problem to {@code problems}.
|
||||
* method, or {@code null} after adding the problem to {@code problems}. Without a target, the
|
||||
* access is checked and the handle does nothing.
|
||||
*/
|
||||
private static @Nullable MethodHandle handle(Object target, Method method, MethodType type, String where, List<String> problems)
|
||||
private static @Nullable MethodHandle handle(@Nullable Object target, Method method, MethodType type, String where, List<String> problems)
|
||||
{
|
||||
try
|
||||
{
|
||||
MethodHandle handle = MethodHandles.privateLookupIn(method.getDeclaringClass(), MethodHandles.lookup()).unreflect(method);
|
||||
|
||||
if (target == null) return MethodHandles.empty(type);
|
||||
if (!Modifier.isStatic(method.getModifiers())) handle = handle.bindTo(target);
|
||||
|
||||
return handle.asType(type);
|
||||
|
||||
@@ -27,13 +27,25 @@ import java.util.function.Function;
|
||||
* @param version from {@link Schema}, or 1 without it
|
||||
* @param migrations stored schema version to migration, from the {@link Migrate} methods
|
||||
*/
|
||||
record RecordSchema<R extends Record>(int version, Map<Integer, Function<Row, R>> migrations)
|
||||
public record RecordSchema<R extends Record>(int version, Map<Integer, Function<Row, R>> migrations)
|
||||
{
|
||||
RecordSchema
|
||||
public RecordSchema
|
||||
{
|
||||
migrations = Map.copyOf(migrations);
|
||||
}
|
||||
|
||||
/**
|
||||
* The problems that {@link #of} reports for {@code type}, in one message; empty when there are
|
||||
* none. For build-time checks.
|
||||
*/
|
||||
public static List<String> check(Class<? extends Record> type)
|
||||
{
|
||||
try { RecordSchema.of(type); }
|
||||
catch (IllegalArgumentException e) { return List.of(e.getMessage()); }
|
||||
|
||||
return List.of();
|
||||
}
|
||||
|
||||
/** @throws IllegalArgumentException listing every invalid annotation of {@code type} */
|
||||
static <R extends Record> RecordSchema<R> of(Class<R> type)
|
||||
{
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package dev.overlord.zomboidforge.tools;
|
||||
|
||||
import dev.overlord.zomboidforge.api.GameVersion;
|
||||
import dev.overlord.zomboidforge.core.config.RecordBinder;
|
||||
import dev.overlord.zomboidforge.core.config.TomlTree;
|
||||
import dev.overlord.zomboidforge.core.mods.GameClasses;
|
||||
import dev.overlord.zomboidforge.core.mods.ModDescriptor;
|
||||
@@ -8,16 +9,24 @@ import dev.overlord.zomboidforge.core.mods.ModDiscovery;
|
||||
import dev.overlord.zomboidforge.core.mods.ModLoadException;
|
||||
import dev.overlord.zomboidforge.core.mods.ModVerifier;
|
||||
import dev.overlord.zomboidforge.core.mods.ModVersion;
|
||||
import dev.overlord.zomboidforge.core.runtime.ListenerScanner;
|
||||
import dev.overlord.zomboidforge.core.storage.RecordSchema;
|
||||
import dev.overlord.zomboidforge.patcher.GameVersionReader;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.objectweb.asm.ClassReader;
|
||||
import org.objectweb.asm.Opcodes;
|
||||
import org.objectweb.asm.tree.AnnotationNode;
|
||||
import org.objectweb.asm.tree.ClassNode;
|
||||
import org.objectweb.asm.tree.MethodNode;
|
||||
import org.objectweb.asm.tree.RecordComponentNode;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URL;
|
||||
import java.net.URLClassLoader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
@@ -26,6 +35,8 @@ import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
import java.util.jar.JarEntry;
|
||||
import java.util.jar.JarFile;
|
||||
import java.util.zip.ZipEntry;
|
||||
|
||||
@@ -41,9 +52,18 @@ import java.util.zip.ZipEntry;
|
||||
* minimum version it satisfies;</li>
|
||||
* <li>the game jar is one of the declared {@code game} versions;</li>
|
||||
* <li>{@link ModVerifier}: game use requires {@code game} versions, every used game class
|
||||
* and member exists in the game jar, no ZomboidForge internals.</li>
|
||||
* and member exists in the game jar, no ZomboidForge internals;</li>
|
||||
* <li>the annotations the server reads while it loads the mod, through the server's own
|
||||
* rules: listener and scheduled methods of the entry point ({@link ListenerScanner}),
|
||||
* {@code @Schema}/{@code @Migrate} ({@link RecordSchema}) and {@code @Key}/{@code @Min}/
|
||||
* {@code @Max} ({@link RecordBinder}) on the jar's records that carry them, and the
|
||||
* {@code @RegisterCommand} classes.</li>
|
||||
* </ol>
|
||||
*
|
||||
* For the last check, the mod's classes are loaded without being initialized, so no mod code
|
||||
* runs. Objects that a mod passes to {@code Events.register} at runtime are only checked on the
|
||||
* server.
|
||||
*
|
||||
* <pre>
|
||||
* java -jar mod-tools.jar --jar <mod.jar> [--game-jar <projectzomboid.jar>]
|
||||
* [--library <jar>]... [--dependency <mod jar>]... [--report <file>]
|
||||
@@ -57,7 +77,15 @@ import java.util.zip.ZipEntry;
|
||||
*/
|
||||
public final class ModCheck
|
||||
{
|
||||
private static final String MOD_CLASS = "dev/overlord/zomboidforge/api/Mod";
|
||||
private static final String MOD_CLASS = "dev/overlord/zomboidforge/api/Mod";
|
||||
private static final String RECORD = "java/lang/Record";
|
||||
private static final String ANNOTATION = "Ldev/overlord/zomboidforge/api/annotations/";
|
||||
|
||||
/** Annotations that make a record worth loading for {@link #checkAnnotations}. */
|
||||
private static final Set<String> RECORD_ANNOTATIONS = Set.of(
|
||||
ModCheck.ANNOTATION + "Schema;", ModCheck.ANNOTATION + "Migrate;",
|
||||
ModCheck.ANNOTATION + "Key;", ModCheck.ANNOTATION + "Min;", ModCheck.ANNOTATION + "Max;"
|
||||
);
|
||||
|
||||
/** The command-line arguments. */
|
||||
public record Arguments(Path jar, @Nullable Path gameJar, List<Path> libraries, List<Path> dependencies, @Nullable Path report)
|
||||
@@ -201,7 +229,9 @@ public final class ModCheck
|
||||
{
|
||||
if (!descriptor.game().isEmpty()) problems.add("The mod declares " + descriptor.game() + ", so the check needs '--game-jar'.");
|
||||
|
||||
ModCheck.verify(candidates, GameClasses.none(), null, problems);
|
||||
Map<String, List<String>> commands = ModCheck.verify(candidates, GameClasses.none(), null, problems);
|
||||
ModCheck.checkAnnotations(arguments, descriptor, commands.getOrDefault(descriptor.id(), List.of()), problems);
|
||||
|
||||
return new Result(descriptor, null, problems);
|
||||
}
|
||||
|
||||
@@ -211,22 +241,147 @@ public final class ModCheck
|
||||
if (!descriptor.game().isEmpty() && descriptor.game().stream().noneMatch(gameVersion::matches))
|
||||
problems.add("The game jar '" + gameJar + "' is Project Zomboid " + gameVersion + ", but the mod declares " + descriptor.game() + "; the check needs a game jar of a declared version.");
|
||||
|
||||
Map<String, List<String>> commands = Map.of();
|
||||
|
||||
try (GameClasses game = GameClasses.open(gameJar))
|
||||
{
|
||||
ModCheck.verify(candidates, game, gameVersion, problems);
|
||||
commands = ModCheck.verify(candidates, game, gameVersion, problems);
|
||||
}
|
||||
catch (IOException e)
|
||||
{
|
||||
problems.add("Cannot read the game jar '" + gameJar + "': " + e.getMessage());
|
||||
}
|
||||
|
||||
ModCheck.checkAnnotations(arguments, descriptor, commands.getOrDefault(descriptor.id(), List.of()), problems);
|
||||
|
||||
return new Result(descriptor, gameVersion, problems);
|
||||
}
|
||||
|
||||
private static void verify(List<ModDiscovery.Candidate> candidates, GameClasses game, @Nullable GameVersion version, List<String> problems)
|
||||
/** @return mod id to its {@code @RegisterCommand} classes; empty when the verifier found problems */
|
||||
private static Map<String, List<String>> verify(List<ModDiscovery.Candidate> candidates, GameClasses game, @Nullable GameVersion version, List<String> problems)
|
||||
{
|
||||
try { ModVerifier.verify(candidates, game, version); }
|
||||
try { return ModVerifier.verify(candidates, game, version); }
|
||||
catch (ModLoadException e) { problems.addAll(e.problems()); }
|
||||
|
||||
return Map.of();
|
||||
}
|
||||
|
||||
/**
|
||||
* The annotation rules of the server, run on the mod's classes: the entry point's listener and
|
||||
* scheduled methods, the records in the jar that carry {@code @Schema}, {@code @Migrate},
|
||||
* {@code @Key}, {@code @Min}, or {@code @Max}, and the {@code @RegisterCommand} classes.
|
||||
* Runs only when every other check passed, since classes that do not link cannot be loaded.
|
||||
*
|
||||
* @param commands binary names of the mod's {@code @RegisterCommand} classes
|
||||
*/
|
||||
private static void checkAnnotations(Arguments arguments, ModDescriptor descriptor, List<String> commands, List<String> problems)
|
||||
{
|
||||
if (!problems.isEmpty()) return;
|
||||
|
||||
List<Path> jars = new ArrayList<>();
|
||||
jars.add(arguments.jar());
|
||||
jars.addAll(arguments.libraries());
|
||||
jars.addAll(arguments.dependencies());
|
||||
if (arguments.gameJar() != null) jars.add(arguments.gameJar());
|
||||
|
||||
try (URLClassLoader loader = new URLClassLoader("mod-check", jars.stream().map(ModCheck::url).toArray(URL[]::new), ModCheck.class.getClassLoader()))
|
||||
{
|
||||
Class<?> entrypoint = ModCheck.load(loader, descriptor.entrypoint(), problems);
|
||||
if (entrypoint != null) problems.addAll(ListenerScanner.check(entrypoint));
|
||||
|
||||
for (String name : ModCheck.annotatedRecords(arguments.jar(), problems))
|
||||
{
|
||||
Class<?> type = ModCheck.load(loader, name, problems);
|
||||
if (type == null || !type.isRecord()) continue;
|
||||
|
||||
problems.addAll(RecordSchema.check(type.asSubclass(Record.class)));
|
||||
problems.addAll(RecordBinder.check(type.asSubclass(Record.class)));
|
||||
}
|
||||
|
||||
for (String name : commands)
|
||||
{
|
||||
Class<?> type = ModCheck.load(loader, name, problems);
|
||||
if (type == null) continue;
|
||||
|
||||
int modifiers = type.getModifiers();
|
||||
|
||||
if (!Modifier.isPublic(modifiers)) problems.add("The command '" + name + "' (@RegisterCommand) is not public.");
|
||||
if (Modifier.isAbstract(modifiers) || type.isInterface()) problems.add("The command '" + name + "' (@RegisterCommand) is abstract.");
|
||||
if (descriptor.game().isEmpty()) problems.add("The command '" + name + "' (@RegisterCommand) needs Project Zomboid's command framework, so 'mod.toml' needs 'game' versions.");
|
||||
}
|
||||
}
|
||||
catch (IOException e)
|
||||
{
|
||||
problems.add("Cannot close the class loader of the check: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/** The class {@code name}, loaded without initializing it, or {@code null} after adding the problem. */
|
||||
private static @Nullable Class<?> load(ClassLoader loader, String name, List<String> problems)
|
||||
{
|
||||
try
|
||||
{
|
||||
return Class.forName(name, false, loader);
|
||||
}
|
||||
catch (ClassNotFoundException | LinkageError e)
|
||||
{
|
||||
problems.add("Cannot load '" + name + "' to check its annotations: " + e + ".");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Binary names of the records in {@code jar} that carry one of {@link #RECORD_ANNOTATIONS}, on the record, a component, or a method. */
|
||||
private static Set<String> annotatedRecords(Path jar, List<String> problems)
|
||||
{
|
||||
Set<String> records = new TreeSet<>();
|
||||
|
||||
try (JarFile file = new JarFile(jar.toFile()))
|
||||
{
|
||||
for (JarEntry entry : file.stream().toList())
|
||||
{
|
||||
String name = entry.getName();
|
||||
if (!name.endsWith(".class") || name.startsWith("META-INF/")) continue;
|
||||
|
||||
ClassNode node = new ClassNode();
|
||||
try (InputStream in = file.getInputStream(entry)) { new ClassReader(in.readAllBytes()).accept(node, ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES); }
|
||||
|
||||
if (ModCheck.RECORD.equals(node.superName) && ModCheck.carriesRecordAnnotation(node)) records.add(node.name.replace('/', '.'));
|
||||
}
|
||||
}
|
||||
catch (IOException e)
|
||||
{
|
||||
problems.add("Cannot read '" + jar + "': " + e.getMessage());
|
||||
}
|
||||
|
||||
return records;
|
||||
}
|
||||
|
||||
private static boolean carriesRecordAnnotation(ClassNode node)
|
||||
{
|
||||
if (ModCheck.anyRecordAnnotation(node.visibleAnnotations)) return true;
|
||||
|
||||
for (MethodNode method : node.methods) {
|
||||
if (ModCheck.anyRecordAnnotation(method.visibleAnnotations)) return true;
|
||||
}
|
||||
|
||||
if (node.recordComponents != null) {
|
||||
for (RecordComponentNode component : node.recordComponents) {
|
||||
if (ModCheck.anyRecordAnnotation(component.visibleAnnotations)) return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static boolean anyRecordAnnotation(@Nullable List<AnnotationNode> annotations)
|
||||
{
|
||||
return annotations != null && annotations.stream().anyMatch(annotation -> ModCheck.RECORD_ANNOTATIONS.contains(annotation.desc));
|
||||
}
|
||||
|
||||
private static URL url(Path path)
|
||||
{
|
||||
try { return path.toUri().toURL(); }
|
||||
catch (MalformedURLException e) { throw new IllegalArgumentException("'" + path + "' has no URL.", e); }
|
||||
}
|
||||
|
||||
private static ModDiscovery.Candidate candidate(Path jar, List<Path> libraries, ModDescriptor descriptor)
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
package checkmods;
|
||||
|
||||
import dev.overlord.zomboidforge.api.annotations.RegisterCommand;
|
||||
|
||||
/** A command class that tests package into a mod jar: neither public nor concrete. */
|
||||
@RegisterCommand
|
||||
abstract class AbstractCommand {}
|
||||
@@ -0,0 +1,16 @@
|
||||
package checkmods;
|
||||
|
||||
import dev.overlord.zomboidforge.api.Mod;
|
||||
import dev.overlord.zomboidforge.api.annotations.Every;
|
||||
import dev.overlord.zomboidforge.api.annotations.OnMain;
|
||||
|
||||
/** Entry point that tests package into a mod jar; its annotated methods break the rules. */
|
||||
@SuppressWarnings("unused")
|
||||
public class InvalidEntry extends Mod
|
||||
{
|
||||
@OnMain
|
||||
void tick(String text) {}
|
||||
|
||||
@Every(0)
|
||||
void report() {}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package checkmods;
|
||||
|
||||
import dev.overlord.zomboidforge.api.annotations.Key;
|
||||
import dev.overlord.zomboidforge.api.annotations.Max;
|
||||
import dev.overlord.zomboidforge.api.annotations.Min;
|
||||
import dev.overlord.zomboidforge.api.annotations.Schema;
|
||||
|
||||
/** Records that tests package into a mod jar, with valid and invalid annotations. */
|
||||
public final class Records
|
||||
{
|
||||
public record Fine(@Key("ok") @Min(1) int amount) {}
|
||||
|
||||
@Schema(version = 0)
|
||||
public record BadSchema(long amount) {}
|
||||
|
||||
public record BadKey(@Key("Bad Key") int amount) {}
|
||||
|
||||
public record BadBounds(@Min(5) @Max(1) int amount) {}
|
||||
|
||||
private Records() {}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package checkmods;
|
||||
|
||||
import dev.overlord.zomboidforge.api.Mod;
|
||||
import dev.overlord.zomboidforge.api.TickEvent;
|
||||
import dev.overlord.zomboidforge.api.annotations.Every;
|
||||
import dev.overlord.zomboidforge.api.annotations.EveryNTicks;
|
||||
import dev.overlord.zomboidforge.api.annotations.OnMain;
|
||||
|
||||
/** Entry point that tests package into a mod jar; every annotated method follows the rules. */
|
||||
@SuppressWarnings("unused")
|
||||
public class ValidEntry extends Mod
|
||||
{
|
||||
@OnMain
|
||||
void tick(TickEvent event) {}
|
||||
|
||||
@Every(1)
|
||||
void report() {}
|
||||
|
||||
@EveryNTicks(2)
|
||||
void sweep() {}
|
||||
}
|
||||
@@ -1,5 +1,9 @@
|
||||
package dev.overlord.zomboidforge.tools;
|
||||
|
||||
import checkmods.InvalidEntry;
|
||||
import checkmods.Records;
|
||||
import checkmods.ValidEntry;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
@@ -7,6 +11,7 @@ import org.objectweb.asm.ClassWriter;
|
||||
import org.objectweb.asm.MethodVisitor;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
@@ -17,6 +22,7 @@ import java.util.jar.JarEntry;
|
||||
import java.util.jar.JarOutputStream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.objectweb.asm.Opcodes.ACC_PUBLIC;
|
||||
import static org.objectweb.asm.Opcodes.ALOAD;
|
||||
import static org.objectweb.asm.Opcodes.INVOKESPECIAL;
|
||||
@@ -67,6 +73,80 @@ class ModCheckTest
|
||||
assertEquals(List.of("The entry point 'a.Main' does not extend 'dev.overlord.zomboidforge.api.Mod'."), result.problems());
|
||||
}
|
||||
|
||||
@Test
|
||||
void passesValidAnnotations() throws IOException
|
||||
{
|
||||
Path mod = this.jar("shop.jar", ModCheckTest.toml(ValidEntry.class), Map.of(
|
||||
"checkmods/ValidEntry", ModCheckTest.classFile(ValidEntry.class),
|
||||
"checkmods/Records$Fine", ModCheckTest.classFile(Records.Fine.class)
|
||||
));
|
||||
|
||||
ModCheck.Result result = ModCheck.check(new ModCheck.Arguments(mod, null, List.of(), List.of(), null));
|
||||
|
||||
assertEquals(List.of(), result.problems());
|
||||
}
|
||||
|
||||
@Test
|
||||
void reportsListenerAndScheduledMethodsThatBreakTheRules() throws IOException
|
||||
{
|
||||
Path mod = this.jar("shop.jar", ModCheckTest.toml(InvalidEntry.class), Map.of("checkmods/InvalidEntry", ModCheckTest.classFile(InvalidEntry.class)));
|
||||
|
||||
String problems = String.join("\n", ModCheck.check(new ModCheck.Arguments(mod, null, List.of(), List.of(), null)).problems());
|
||||
|
||||
ModCheckTest.assertContainsAll(problems, "checkmods.InvalidEntry.tick", "java.lang.String", "checkmods.InvalidEntry.report");
|
||||
}
|
||||
|
||||
@Test
|
||||
void reportsRecordAnnotationsThatBreakTheRules() throws IOException
|
||||
{
|
||||
Path mod = this.jar("shop.jar", ModCheckTest.toml(ValidEntry.class), Map.of(
|
||||
"checkmods/ValidEntry", ModCheckTest.classFile(ValidEntry.class),
|
||||
"checkmods/Records$Fine", ModCheckTest.classFile(Records.Fine.class),
|
||||
"checkmods/Records$BadSchema", ModCheckTest.classFile(Records.BadSchema.class),
|
||||
"checkmods/Records$BadKey", ModCheckTest.classFile(Records.BadKey.class),
|
||||
"checkmods/Records$BadBounds", ModCheckTest.classFile(Records.BadBounds.class)
|
||||
));
|
||||
|
||||
List<String> problems = ModCheck.check(new ModCheck.Arguments(mod, null, List.of(), List.of(), null)).problems();
|
||||
|
||||
assertEquals(3, problems.size(), String.valueOf(problems));
|
||||
ModCheckTest.assertContainsAll(String.join("\n", problems), "Records$BadSchema", "Records$BadKey", "Bad Key", "Records$BadBounds");
|
||||
}
|
||||
|
||||
@Test
|
||||
void reportsRegisteredCommandsThatCannotBeRegistered() throws IOException
|
||||
{
|
||||
Path mod = this.jar("shop.jar", ModCheckTest.toml(ValidEntry.class), Map.of(
|
||||
"checkmods/ValidEntry", ModCheckTest.classFile(ValidEntry.class),
|
||||
"checkmods/AbstractCommand", ModCheckTest.classFile("checkmods/AbstractCommand")
|
||||
));
|
||||
|
||||
String problems = String.join("\n", ModCheck.check(new ModCheck.Arguments(mod, null, List.of(), List.of(), null)).problems());
|
||||
|
||||
ModCheckTest.assertContainsAll(problems, "checkmods.AbstractCommand", "not public", "abstract", "'game'");
|
||||
}
|
||||
|
||||
/** {@link #TOML} with {@code entrypoint} as the entry point. */
|
||||
private static String toml(Class<?> entrypoint) { return ModCheckTest.TOML.replace("a.Main", entrypoint.getName()); }
|
||||
|
||||
/** The class file of a class on the test class path. */
|
||||
private static byte[] classFile(Class<?> type) throws IOException { return ModCheckTest.classFile(type.getName().replace('.', '/')); }
|
||||
|
||||
/** The class file of the class {@code internalName} on the test class path. */
|
||||
private static byte[] classFile(String internalName) throws IOException
|
||||
{
|
||||
try (InputStream in = ModCheckTest.class.getResourceAsStream("/" + internalName + ".class"))
|
||||
{
|
||||
if (in == null) throw new IOException("No class file for '" + internalName + "'.");
|
||||
return in.readAllBytes();
|
||||
}
|
||||
}
|
||||
|
||||
private static void assertContainsAll(String message, String... parts)
|
||||
{
|
||||
for (String part : parts) assertTrue(message.contains(part), "'" + part + "' missing in: " + message);
|
||||
}
|
||||
|
||||
/** A public class extending {@code superName} with a public constructor without parameters. */
|
||||
private static byte[] type(String name, String superName)
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user