Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions src/main/java/io/github/misode/packtest/PackTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
import net.fabricmc.api.ModInitializer;
import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents;
import net.minecraft.util.FileUtil;
import net.minecraft.util.Util;
import net.minecraft.commands.CommandBuildContext;
Expand Down Expand Up @@ -56,8 +57,19 @@ public void onInitialize() {
CommandRegistrationCallback.EVENT.register((dispatcher, buildContext, environment) ->
registerCommands(dispatcher, buildContext)
);
ServerLifecycleEvents.SERVER_STARTED.register(server ->
server.execute(() -> loadTests(server)));
ServerLifecycleEvents.END_DATA_PACK_RELOAD.register((server, resourceManager, success) -> {
if (success) {
server.execute(() -> loadTests(server));
}
});
}

private static void loadTests(net.minecraft.server.MinecraftServer server) {
new PackTestLibrary(server.registryAccess()).load(server);
}

public static void generateCommandsReport() {
Path path = Paths.get("generated", "reports", "commands.json");
CommandDispatcher<CommandSourceStack> dispatcher = new CommandDispatcher<>();
Expand Down
11 changes: 10 additions & 1 deletion src/main/java/io/github/misode/packtest/PackTestExecutor.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import io.github.misode.packtest.commands.assertions.AssertResult;
import io.github.misode.packtest.dummy.Dummy;
import net.minecraft.commands.CommandResultCallback;
import net.minecraft.commands.CommandSource;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.arguments.coordinates.Coordinates;
Expand All @@ -15,6 +16,7 @@
import net.minecraft.world.phys.Vec2;
import net.minecraft.world.phys.Vec3;
import org.jetbrains.annotations.Nullable;
import org.jspecify.annotations.NonNull;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
Expand All @@ -24,6 +26,13 @@
public class PackTestExecutor {
private static final SimpleCommandExceptionType ERROR_NOT_IN_TEST = new SimpleCommandExceptionType(
Component.literal("Command can only be used inside a test"));
private static final CommandSource SILENT_SOURCE = new CommandSource() {
@Override public void sendSystemMessage(@NonNull Component message) {}
@Override public boolean acceptsSuccess() { return true; }
@Override public boolean acceptsFailure() { return true; }
@Override public boolean shouldInformAdmins() { return false; }
@Override public boolean alwaysAccepts() { return true; }
};
private static @Nullable PackTestExecutor current;

private final List<Supplier<Boolean>> awaits = new ArrayList<>();
Expand Down Expand Up @@ -78,7 +87,7 @@ private CommandSourceStack createCommandSourceStack(PackTestFunction function) {
CommandSourceStack source = helper.getLevel().getServer().createCommandSourceStack()
.withLevel(helper.getLevel())
.withPosition(helper.absoluteVec(Vec3.ZERO))
.withSuppressedOutput();
.withSource(SILENT_SOURCE);

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What issue is this intended to solve? Why did withSuppressedOutput not work?


Optional<Coordinates> coordinates = function.directives().dummy();
if (coordinates.isPresent()) {
Expand Down
84 changes: 28 additions & 56 deletions src/main/java/io/github/misode/packtest/PackTestLibrary.java
Original file line number Diff line number Diff line change
@@ -1,91 +1,63 @@
package io.github.misode.packtest;

import com.google.common.collect.*;
import com.mojang.brigadier.CommandDispatcher;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.core.*;
import net.minecraft.resources.FileToIdConverter;
import net.minecraft.resources.Identifier;
import net.minecraft.server.packs.resources.PreparableReloadListener;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.packs.resources.Resource;
import net.minecraft.server.packs.resources.ResourceManager;
import net.minecraft.server.permissions.PermissionSet;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.Executor;
import java.util.concurrent.ForkJoinPool;

public class PackTestLibrary implements PreparableReloadListener {
public class PackTestLibrary {
Comment on lines -25 to +21

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[PreparableReloadListener] I intend on attempting this soon

Do you realize that it was already using this, and your PR would switch away from using that?

private static final FileToIdConverter LISTER = new FileToIdConverter("test", ".mcfunction");

private static final Map<Identifier, PackTestFunction> LOADED = new HashMap<>();

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A static map of loaded functions is a really bad idea. Tests are already stored in the registry.


private final PackTestRegistries registries;
private final PermissionSet testCompilationPermissions;
private final CommandDispatcher<CommandSourceStack> dispatcher;

public PackTestLibrary(
HolderLookup.Provider registries,
PermissionSet testCompilationPermissions,
CommandDispatcher<CommandSourceStack> dispatcher) {
public PackTestLibrary(HolderLookup.Provider registries) {
this.registries = new PackTestRegistries(registries);
this.testCompilationPermissions = testCompilationPermissions;
this.dispatcher = dispatcher;
}

@Override
public @NotNull CompletableFuture<Void> reload(
@NotNull SharedState currentReload,
@NotNull Executor taskExecutor,
PreparationBarrier preparationBarrier,
@NotNull Executor reloadExecutor) {
ResourceManager manager = currentReload.resourceManager();
CompletableFuture<RegistryAccess.Frozen> registryLoad = this.registries.load(manager, taskExecutor);

CompletableFuture<Map<Identifier, CompletableFuture<PackTestFunction>>> testFunctions = CompletableFuture
.supplyAsync(() -> LISTER.listMatchingResources(manager), taskExecutor)
.thenComposeAsync(map -> prepareTestFunctions(map, taskExecutor));

return CompletableFuture.allOf(registryLoad, testFunctions)
.thenCompose(preparationBarrier::wait)
.thenAcceptAsync((_) ->
this.registries.register(registryLoad.join(), collectTestFunctions(testFunctions.join())),
reloadExecutor);
public static @Nullable PackTestFunction getLoaded(Identifier id) {
return LOADED.get(id);
}

private CompletableFuture<Map<Identifier, CompletableFuture<PackTestFunction>>> prepareTestFunctions(
Map<Identifier, Resource> resources,
Executor taskExecutor) {
Map<Identifier, CompletableFuture<PackTestFunction>> result = new HashMap<>();
CommandSourceStack compilationContext = Commands.createCompilationContext(this.testCompilationPermissions);
public void load(MinecraftServer server) {
ResourceManager manager = server.getResourceManager();
RegistryAccess.Frozen registryLookup = this.registries
.load(manager, ForkJoinPool.commonPool())
.join();
CommandDispatcher<CommandSourceStack> dispatcher = server.getCommands().getDispatcher();
CommandSourceStack source = server.createCommandSourceStack();

Map<Identifier, Resource> resources = LISTER.listMatchingResources(manager);
Map<Identifier, PackTestFunction> loaded = new HashMap<>();
for (Map.Entry<Identifier, Resource> entry : resources.entrySet()) {
Identifier id = LISTER.fileToId(entry.getKey());
result.put(id, CompletableFuture.supplyAsync(() -> {
try {
List<String> lines = readLines(entry.getValue());
return PackTestFunction.fromLines(this.dispatcher, compilationContext, lines);
}, taskExecutor));
}

return CompletableFuture.allOf(result.values().toArray(new CompletableFuture[0])).handle((_, _) -> result);
}

private static Map<Identifier, PackTestFunction> collectTestFunctions(Map<Identifier, CompletableFuture<PackTestFunction>> futures) {
ImmutableMap.Builder<Identifier, PackTestFunction> result = ImmutableMap.builder();
futures.forEach((id, future) -> future.handle((test, e) -> {
if (e == null) {
result.put(id, test);
} else {
PackTestFunction fn = PackTestFunction.fromLines(dispatcher, source, lines);
loaded.put(id, fn);
} catch (Exception e) {
PackTest.LOGGER.error("Failed to load test {}", id, e);
}
return null;
}).join());
return result.build();
}

LOADED.clear();
LOADED.putAll(loaded);
this.registries.register(registryLookup, loaded);
PackTest.LOGGER.info("Loaded {} test functions", loaded.size());
}

private static List<String> readLines(Resource resource) {
Expand Down

This file was deleted.

1 change: 0 additions & 1 deletion src/main/resources/packtest.mixins.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
"MappedRegistryMixin",
"PackMixin",
"PlayerListMixin",
"ReloadableServerResourcesMixin",
"ServerFunctionLibraryMixin",
"ServerPlayerMixin",
"SimpleJsonResourceReloadListenerMixin",
Expand Down