Introduce gradle-plugin and mod-tools modules. Add ZomboidForge Gradle plugin for building, checking, and packaging mods. Include support for local test servers, automated game jar downloads, and mod descriptor generation. Add mod-tools for runtime mod checks and validations.
This commit is contained in:
1 parent
68cd9fc4f9
commit
063ad8a3e1
27 files changed
+1976
-30
No files matched your search
@@ -0,0 +1,46 @@
|
||||
// Gradle plugin for mod authors (id dev.overlord.zomboidforge.mod): dependencies, mod.toml,
|
||||
// build-time checks, packaging, and a local test server. Runs inside the mod's Gradle JVM, so
|
||||
// it targets Java 17; the checks run in a separate Java 25 process (mod-tools).
|
||||
|
||||
plugins {
|
||||
id("zomboidforge.java-conventions")
|
||||
id("zomboidforge.publishing")
|
||||
`java-gradle-plugin`
|
||||
}
|
||||
|
||||
tasks.withType<JavaCompile>().configureEach {
|
||||
options.release = 17
|
||||
}
|
||||
|
||||
gradlePlugin {
|
||||
plugins {
|
||||
create("mod") {
|
||||
id = "dev.overlord.zomboidforge.mod"
|
||||
implementationClass = "dev.overlord.zomboidforge.gradle.ZomboidForgeModPlugin"
|
||||
displayName = "ZomboidForge mod"
|
||||
description = "Builds, checks, and packages server-side Java mods for ZomboidForge."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
tasks.processResources {
|
||||
// The plugin resolves api and mod-tools in its own version.
|
||||
val pluginVersion = project.version.toString()
|
||||
inputs.property("version", pluginVersion)
|
||||
filesMatching("**/plugin.properties") { expand("version" to pluginVersion) }
|
||||
}
|
||||
|
||||
dependencies {
|
||||
testImplementation(libs.bundles.asm)
|
||||
testImplementation(platform(libs.junit.bom))
|
||||
testImplementation(libs.junit.jupiter)
|
||||
testRuntimeOnly(libs.junit.platform.launcher)
|
||||
}
|
||||
|
||||
tasks.test {
|
||||
// The functional tests resolve api and mod-tools from the repository in build/repo.
|
||||
dependsOn(":api:publishAllPublicationsToBuildRepository", ":mod-tools:publishAllPublicationsToBuildRepository")
|
||||
|
||||
val repository = layout.settingsDirectory.dir("build/repo").asFile.absolutePath
|
||||
systemProperty("zomboidforge.testRepository", repository)
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package dev.overlord.zomboidforge.gradle;
|
||||
|
||||
import org.gradle.api.file.ConfigurableFileCollection;
|
||||
import org.gradle.api.file.RegularFileProperty;
|
||||
import org.gradle.api.tasks.Classpath;
|
||||
import org.gradle.api.tasks.InputFile;
|
||||
import org.gradle.api.tasks.Optional;
|
||||
import org.gradle.api.tasks.OutputFile;
|
||||
import org.gradle.api.tasks.PathSensitive;
|
||||
import org.gradle.api.tasks.PathSensitivity;
|
||||
import org.gradle.process.CommandLineArgumentProvider;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* The command line of {@code mod-tools} for the {@code checkMod} task. Its properties are the
|
||||
* task's inputs and output, so the check only runs again when one of them changed.
|
||||
*/
|
||||
public abstract class CheckModArguments implements CommandLineArgumentProvider
|
||||
{
|
||||
@InputFile
|
||||
@PathSensitive(PathSensitivity.NONE)
|
||||
public abstract RegularFileProperty getJar();
|
||||
|
||||
/** The mod's runtime libraries, which go into {@code lib/}. */
|
||||
@Classpath
|
||||
public abstract ConfigurableFileCollection getLibraries();
|
||||
|
||||
/** Jars of other mods the mod compiles against. */
|
||||
@Classpath
|
||||
public abstract ConfigurableFileCollection getDependencies();
|
||||
|
||||
/** Absent for mods that declare no game versions. */
|
||||
@InputFile
|
||||
@Optional
|
||||
@PathSensitive(PathSensitivity.NONE)
|
||||
public abstract RegularFileProperty getGameJar();
|
||||
|
||||
@OutputFile
|
||||
public abstract RegularFileProperty getReport();
|
||||
|
||||
@Override
|
||||
public Iterable<String> asArguments()
|
||||
{
|
||||
List<String> arguments = new ArrayList<>(List.of("--jar", this.getJar().get().getAsFile().getAbsolutePath()));
|
||||
|
||||
for (File library : this.getLibraries()) arguments.addAll(List.of("--library", library.getAbsolutePath()));
|
||||
for (File mod : this.getDependencies()) arguments.addAll(List.of("--dependency", mod.getAbsolutePath()));
|
||||
if (this.getGameJar().isPresent()) arguments.addAll(List.of("--game-jar", this.getGameJar().get().getAsFile().getAbsolutePath()));
|
||||
|
||||
arguments.addAll(List.of("--report", this.getReport().get().getAsFile().getAbsolutePath()));
|
||||
|
||||
return arguments;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package dev.overlord.zomboidforge.gradle;
|
||||
|
||||
import org.gradle.api.DefaultTask;
|
||||
import org.gradle.api.GradleException;
|
||||
import org.gradle.api.file.DirectoryProperty;
|
||||
import org.gradle.api.provider.Property;
|
||||
import org.gradle.api.tasks.Input;
|
||||
import org.gradle.api.tasks.Internal;
|
||||
import org.gradle.api.tasks.Optional;
|
||||
import org.gradle.api.tasks.TaskAction;
|
||||
import org.gradle.api.tasks.UntrackedTask;
|
||||
import org.gradle.process.ExecOperations;
|
||||
import org.gradle.process.ExecResult;
|
||||
|
||||
import javax.inject.Inject;
|
||||
import java.io.File;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Installs the Project Zomboid dedicated server (Steam app 380870) with an anonymous steamcmd
|
||||
* login, for its {@code java/projectzomboid.jar}. Uses {@code steamcmd} when installed, else the
|
||||
* {@code steamcmd/steamcmd} image with podman or docker. The download is a few gigabytes and
|
||||
* happens once per branch: the installation stays in the Gradle user home.
|
||||
*/
|
||||
@UntrackedTask(because = "Installs into the Gradle user home; skipped when the jar is there")
|
||||
public abstract class DownloadGame extends DefaultTask
|
||||
{
|
||||
/** Relative path of the jar in the installation. */
|
||||
static final String JAR = "java/projectzomboid.jar";
|
||||
|
||||
private static final String APP_ID = "380870";
|
||||
private static final String IMAGE = "docker.io/steamcmd/steamcmd:latest";
|
||||
private static final int MAX_ATTEMPTS = 3;
|
||||
|
||||
@Internal
|
||||
public abstract DirectoryProperty getInstallDirectory();
|
||||
|
||||
@Input
|
||||
public abstract Property<String> getBranch();
|
||||
|
||||
@Input
|
||||
@Optional
|
||||
public abstract Property<String> getContainerEngine();
|
||||
|
||||
@Inject
|
||||
protected abstract ExecOperations getExecOperations();
|
||||
|
||||
@TaskAction
|
||||
public void download() throws Exception
|
||||
{
|
||||
File directory = this.getInstallDirectory().get().getAsFile();
|
||||
Path jar = directory.toPath().resolve(DownloadGame.JAR);
|
||||
|
||||
if (Files.isRegularFile(jar)) return;
|
||||
|
||||
Files.createDirectories(directory.toPath());
|
||||
this.getLogger().lifecycle("Downloading the Project Zomboid dedicated server (branch {}) into {}; this happens once and takes a few gigabytes.", this.getBranch().get(), directory);
|
||||
|
||||
// steamcmd can fail with "Missing configuration" right after it updated itself; a repeated attempt succeeds.
|
||||
for (int attempt = 1; attempt <= DownloadGame.MAX_ATTEMPTS && !Files.isRegularFile(jar); attempt++)
|
||||
{
|
||||
List<String> command = this.command(directory);
|
||||
|
||||
ExecResult result = this.getExecOperations().exec(spec ->
|
||||
{
|
||||
spec.commandLine(command);
|
||||
spec.setIgnoreExitValue(true);
|
||||
});
|
||||
|
||||
if (result.getExitValue() != 0) this.getLogger().warn("steamcmd exited with {} (attempt {} of {}).", result.getExitValue(), attempt, DownloadGame.MAX_ATTEMPTS);
|
||||
}
|
||||
|
||||
if (!Files.isRegularFile(jar))
|
||||
throw new GradleException("steamcmd did not install '" + jar + "'. Set zomboidForge.gameJar (or the Gradle property zomboidforge.gameJar) to a projectzomboid.jar instead.");
|
||||
}
|
||||
|
||||
private List<String> command(File directory)
|
||||
{
|
||||
List<String> command = new ArrayList<>();
|
||||
Path steamcmd = Executables.find("steamcmd");
|
||||
String installDir = directory.getAbsolutePath();
|
||||
|
||||
if (steamcmd != null)
|
||||
{
|
||||
command.add(steamcmd.toString());
|
||||
}
|
||||
else
|
||||
{
|
||||
String engine = Executables.containerEngine(this.getContainerEngine().getOrNull());
|
||||
|
||||
command.addAll(List.of(engine, "run", "--rm", "--volume", installDir + ":/server:Z", DownloadGame.IMAGE));
|
||||
installDir = "/server";
|
||||
}
|
||||
|
||||
command.addAll(List.of("+force_install_dir", installDir, "+login", "anonymous", "+app_update", DownloadGame.APP_ID));
|
||||
|
||||
String branch = this.getBranch().get();
|
||||
if (!branch.equals("public")) command.addAll(List.of("-beta", branch));
|
||||
|
||||
command.addAll(List.of("validate", "+quit"));
|
||||
return command;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package dev.overlord.zomboidforge.gradle;
|
||||
|
||||
import org.gradle.api.GradleException;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.io.File;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
|
||||
/** Programs on the {@code PATH}. */
|
||||
final class Executables
|
||||
{
|
||||
private Executables() {}
|
||||
|
||||
/** The program {@code name} on the {@code PATH}, or {@code null}. */
|
||||
static @Nullable Path find(String name)
|
||||
{
|
||||
String path = System.getenv("PATH");
|
||||
if (path == null) return null;
|
||||
|
||||
boolean windows = System.getProperty("os.name").toLowerCase(Locale.ROOT).contains("win");
|
||||
List<String> names = windows ? List.of(name + ".exe", name + ".cmd", name) : List.of(name);
|
||||
|
||||
for (String directory : path.split(File.pathSeparator))
|
||||
{
|
||||
for (String candidate : names)
|
||||
{
|
||||
Path file = Path.of(directory, candidate);
|
||||
if (Files.isRegularFile(file) && Files.isExecutable(file)) return file;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/** {@code configured} when set, else podman or docker, whichever is installed. */
|
||||
static String containerEngine(@Nullable String configured)
|
||||
{
|
||||
if (configured != null && !configured.isBlank()) return configured;
|
||||
|
||||
for (String engine : List.of("podman", "docker")) {
|
||||
if (Executables.find(engine) != null) return engine;
|
||||
}
|
||||
|
||||
throw new GradleException("Neither podman nor docker is installed; set zomboidForge.containerEngine or install one of them.");
|
||||
}
|
||||
}
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
package dev.overlord.zomboidforge.gradle;
|
||||
|
||||
import org.gradle.api.DefaultTask;
|
||||
import org.gradle.api.GradleException;
|
||||
import org.gradle.api.file.ConfigurableFileCollection;
|
||||
import org.gradle.api.file.DirectoryProperty;
|
||||
import org.gradle.api.provider.ListProperty;
|
||||
import org.gradle.api.provider.MapProperty;
|
||||
import org.gradle.api.provider.Property;
|
||||
import org.gradle.api.tasks.Input;
|
||||
import org.gradle.api.tasks.InputFiles;
|
||||
import org.gradle.api.tasks.OutputDirectory;
|
||||
import org.gradle.api.tasks.PathSensitive;
|
||||
import org.gradle.api.tasks.PathSensitivity;
|
||||
import org.gradle.api.tasks.TaskAction;
|
||||
import org.gradle.work.DisableCachingByDefault;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* Writes {@code META-INF/zomboidforge/mod.toml} from the {@code zomboidForge { }} block. Fails
|
||||
* when the resources contain a hand-written one.
|
||||
*/
|
||||
@DisableCachingByDefault(because = "Writes one small file")
|
||||
public abstract class GenerateModDescriptor extends DefaultTask
|
||||
{
|
||||
/** Location of the descriptor inside the jar. */
|
||||
static final String PATH = "META-INF/zomboidforge/mod.toml";
|
||||
|
||||
@Input
|
||||
public abstract Property<String> getModId();
|
||||
|
||||
@Input
|
||||
public abstract Property<String> getModName();
|
||||
|
||||
@Input
|
||||
public abstract Property<String> getModVersion();
|
||||
|
||||
@Input
|
||||
public abstract Property<String> getEntrypoint();
|
||||
|
||||
@Input
|
||||
public abstract Property<String> getApi();
|
||||
|
||||
@Input
|
||||
public abstract ListProperty<String> getGame();
|
||||
|
||||
@Input
|
||||
public abstract ListProperty<String> getPreviousIds();
|
||||
|
||||
@Input
|
||||
public abstract MapProperty<String, String> getDependencies();
|
||||
|
||||
/** Where a hand-written {@code mod.toml} would be in the resource directories; none of them may exist. */
|
||||
@InputFiles
|
||||
@PathSensitive(PathSensitivity.ABSOLUTE)
|
||||
public abstract ConfigurableFileCollection getHandWritten();
|
||||
|
||||
@OutputDirectory
|
||||
public abstract DirectoryProperty getOutputDirectory();
|
||||
|
||||
@TaskAction
|
||||
public void generate() throws IOException
|
||||
{
|
||||
for (File file : this.getHandWritten())
|
||||
{
|
||||
if (file.exists())
|
||||
throw new GradleException("'" + file + "' is written by hand; the ZomboidForge plugin generates mod.toml from zomboidForge { }.");
|
||||
}
|
||||
|
||||
Path descriptor = this.getOutputDirectory().get().getAsFile().toPath().resolve(GenerateModDescriptor.PATH);
|
||||
Files.createDirectories(descriptor.getParent());
|
||||
Files.writeString(descriptor, this.toml(), StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
private String toml()
|
||||
{
|
||||
StringBuilder toml = new StringBuilder();
|
||||
|
||||
toml.append("id = ").append(GenerateModDescriptor.string(this.getModId().get())).append('\n');
|
||||
toml.append("name = ").append(GenerateModDescriptor.string(this.getModName().get())).append('\n');
|
||||
toml.append("version = ").append(GenerateModDescriptor.string(this.getModVersion().get())).append('\n');
|
||||
toml.append("entrypoint = ").append(GenerateModDescriptor.string(this.getEntrypoint().get())).append('\n');
|
||||
toml.append("api = ").append(GenerateModDescriptor.string(this.getApi().get())).append('\n');
|
||||
|
||||
List<String> game = this.getGame().get();
|
||||
if (!game.isEmpty()) toml.append("game = ").append(GenerateModDescriptor.list(game)).append('\n');
|
||||
|
||||
List<String> previousIds = this.getPreviousIds().get();
|
||||
if (!previousIds.isEmpty()) toml.append("previous_ids = ").append(GenerateModDescriptor.list(previousIds)).append('\n');
|
||||
|
||||
Map<String, String> dependencies = new TreeMap<>(this.getDependencies().get());
|
||||
|
||||
if (!dependencies.isEmpty())
|
||||
{
|
||||
toml.append("\n[dependencies]\n");
|
||||
dependencies.forEach((id, version) -> toml.append(id).append(" = ").append(GenerateModDescriptor.string(version)).append('\n'));
|
||||
}
|
||||
|
||||
return toml.toString();
|
||||
}
|
||||
|
||||
private static String list(List<String> values) { return values.stream().map(GenerateModDescriptor::string).collect(Collectors.joining(", ", "[", "]")); }
|
||||
|
||||
/** A TOML basic string. */
|
||||
private static String string(String value) { return "\"" + value.replace("\\", "\\\\").replace("\"", "\\\"") + "\""; }
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package dev.overlord.zomboidforge.gradle;
|
||||
|
||||
import org.gradle.api.provider.ValueSource;
|
||||
import org.gradle.api.provider.ValueSourceParameters;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* The {@code projectzomboid.jar} of a local Steam installation: the dedicated server (app 380870)
|
||||
* first, then the game. Looks in every Steam library listed in {@code libraryfolders.vdf} of the
|
||||
* usual Steam folders. A {@link ValueSource}, so the configuration cache looks again on every
|
||||
* build.
|
||||
*/
|
||||
public abstract class LocalGameJar implements ValueSource<String, ValueSourceParameters.None>
|
||||
{
|
||||
private static final Pattern LIBRARY_PATH = Pattern.compile("\"path\"\\s+\"(.*)\"");
|
||||
|
||||
/** Where the jar is inside {@code steamapps/common}, most specific first. */
|
||||
private static final List<String> JARS = List.of(
|
||||
"Project Zomboid Dedicated Server/java/projectzomboid.jar",
|
||||
"ProjectZomboid/projectzomboid/projectzomboid.jar",
|
||||
"ProjectZomboid/java/projectzomboid.jar",
|
||||
"ProjectZomboid/projectzomboid.jar"
|
||||
);
|
||||
|
||||
/** The jar's absolute path, or {@code null} when none is installed. */
|
||||
@Override
|
||||
public @Nullable String obtain()
|
||||
{
|
||||
for (Path library : LocalGameJar.libraries())
|
||||
{
|
||||
for (String jar : LocalGameJar.JARS)
|
||||
{
|
||||
Path candidate = library.resolve("steamapps").resolve("common").resolve(jar);
|
||||
if (Files.isRegularFile(candidate)) return candidate.toAbsolutePath().toString();
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Steam folders, then the libraries their {@code libraryfolders.vdf} lists. */
|
||||
private static Set<Path> libraries()
|
||||
{
|
||||
Set<Path> libraries = new LinkedHashSet<>();
|
||||
|
||||
for (Path root : LocalGameJar.steamRoots())
|
||||
{
|
||||
if (!Files.isDirectory(root)) continue;
|
||||
|
||||
libraries.add(root);
|
||||
libraries.addAll(LocalGameJar.listedLibraries(root.resolve("steamapps").resolve("libraryfolders.vdf")));
|
||||
}
|
||||
|
||||
return libraries;
|
||||
}
|
||||
|
||||
private static List<Path> steamRoots()
|
||||
{
|
||||
String home = System.getProperty("user.home");
|
||||
String os = System.getProperty("os.name").toLowerCase(Locale.ROOT);
|
||||
List<Path> roots = new ArrayList<>();
|
||||
|
||||
if (os.contains("win"))
|
||||
{
|
||||
String programFilesX86 = System.getenv("ProgramFiles(x86)");
|
||||
|
||||
roots.add(Path.of(programFilesX86 == null ? "C:\\Program Files (x86)" : programFilesX86, "Steam"));
|
||||
roots.add(Path.of("C:\\Program Files", "Steam"));
|
||||
}
|
||||
else if (os.contains("mac"))
|
||||
{
|
||||
roots.add(Path.of(home, "Library", "Application Support", "Steam"));
|
||||
}
|
||||
else
|
||||
{
|
||||
roots.add(Path.of(home, ".local", "share", "Steam"));
|
||||
roots.add(Path.of(home, ".steam", "steam"));
|
||||
roots.add(Path.of(home, ".var", "app", "com.valvesoftware.Steam", "data", "Steam"));
|
||||
}
|
||||
|
||||
return roots;
|
||||
}
|
||||
|
||||
private static List<Path> listedLibraries(Path vdf)
|
||||
{
|
||||
List<Path> libraries = new ArrayList<>();
|
||||
if (!Files.isRegularFile(vdf)) return libraries;
|
||||
|
||||
try
|
||||
{
|
||||
Matcher matcher = LocalGameJar.LIBRARY_PATH.matcher(Files.readString(vdf, StandardCharsets.UTF_8));
|
||||
while (matcher.find()) libraries.add(Path.of(matcher.group(1).replace("\\\\", "\\")));
|
||||
}
|
||||
catch (IOException e)
|
||||
{
|
||||
// An unreadable list leaves the library folder itself, which is already listed.
|
||||
}
|
||||
|
||||
return libraries;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package dev.overlord.zomboidforge.gradle;
|
||||
|
||||
import org.gradle.api.DefaultTask;
|
||||
import org.gradle.api.GradleException;
|
||||
import org.gradle.api.file.DirectoryProperty;
|
||||
import org.gradle.api.provider.Property;
|
||||
import org.gradle.api.tasks.Input;
|
||||
import org.gradle.api.tasks.Internal;
|
||||
import org.gradle.api.tasks.Optional;
|
||||
import org.gradle.api.tasks.TaskAction;
|
||||
import org.gradle.api.tasks.UntrackedTask;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* Runs a ZomboidForge server in a container with the built mod mounted at
|
||||
* {@code /forge/mods} (read-only, so the server uses the mod's default settings). The world and
|
||||
* server config stay in a named volume between runs.
|
||||
*
|
||||
* <p>Cancelling the build (Ctrl+C) stops the container with {@code <engine> stop}, which lets the
|
||||
* server save the world; so does stopping the container from outside. Either way the task ends
|
||||
* without an error.
|
||||
*/
|
||||
@UntrackedTask(because = "Runs a server")
|
||||
public abstract class RunServer extends DefaultTask
|
||||
{
|
||||
/** Exit codes of a server that was stopped: 0, and 128 + SIGINT or SIGTERM. */
|
||||
private static final Set<Integer> STOPPED = Set.of(0, 130, 143);
|
||||
|
||||
/** Seconds the server gets to save the world after a stop request. */
|
||||
private static final int STOP_TIMEOUT = 120;
|
||||
|
||||
/** Contains one folder per mod, as in {@code <forge>/mods}. */
|
||||
@Internal
|
||||
public abstract DirectoryProperty getModsDirectory();
|
||||
|
||||
@Input
|
||||
public abstract Property<String> getImage();
|
||||
|
||||
@Input
|
||||
public abstract Property<String> getContainerName();
|
||||
|
||||
@Input
|
||||
public abstract Property<String> getDataVolume();
|
||||
|
||||
@Input
|
||||
public abstract Property<String> getAdminPassword();
|
||||
|
||||
@Input
|
||||
@Optional
|
||||
public abstract Property<String> getContainerEngine();
|
||||
|
||||
@TaskAction
|
||||
public void run() throws IOException
|
||||
{
|
||||
String engine = Executables.containerEngine(this.getContainerEngine().getOrNull());
|
||||
String name = this.getContainerName().get();
|
||||
|
||||
List<String> command = List.of(
|
||||
engine, "run", "--rm",
|
||||
"--name", name,
|
||||
"--publish", "16261:16261/udp",
|
||||
"--publish", "16262:16262/udp",
|
||||
"--env", "ADMIN_PASSWORD=" + this.getAdminPassword().get(),
|
||||
"--volume", this.getDataVolume().get() + ":/data",
|
||||
"--volume", this.getModsDirectory().get().getAsFile().getAbsolutePath() + ":/forge/mods:ro,Z",
|
||||
this.getImage().get()
|
||||
);
|
||||
|
||||
this.getLogger().lifecycle("Starting {} with the mod; connect to localhost:16261. Cancel the build (Ctrl+C) to stop the server.", this.getImage().get());
|
||||
|
||||
Process process = new ProcessBuilder(command).redirectErrorStream(true).start();
|
||||
Thread output = new Thread(() -> RunServer.forward(process), "runServer output");
|
||||
|
||||
output.setDaemon(true);
|
||||
output.start();
|
||||
|
||||
try
|
||||
{
|
||||
int exit = process.waitFor();
|
||||
if (!RunServer.STOPPED.contains(exit)) throw new GradleException("The server container exited with " + exit + ".");
|
||||
}
|
||||
catch (InterruptedException e)
|
||||
{
|
||||
// The build was cancelled: stop the container so the server saves the world.
|
||||
this.getLogger().lifecycle("Stopping the server.");
|
||||
RunServer.stop(engine, name, process);
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
|
||||
/** Copies the container's output to the build output, line by line. */
|
||||
private static void forward(Process process)
|
||||
{
|
||||
try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8)))
|
||||
{
|
||||
for (String line = reader.readLine(); line != null; line = reader.readLine()) System.out.println(line);
|
||||
}
|
||||
catch (IOException e)
|
||||
{
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private static void stop(String engine, String name, Process process)
|
||||
{
|
||||
try
|
||||
{
|
||||
Process stop = new ProcessBuilder(engine, "stop", "--time", String.valueOf(RunServer.STOP_TIMEOUT), name).inheritIO().start();
|
||||
|
||||
stop.waitFor(RunServer.STOP_TIMEOUT + 30, TimeUnit.SECONDS);
|
||||
process.waitFor(30, TimeUnit.SECONDS);
|
||||
}
|
||||
catch (IOException | InterruptedException e)
|
||||
{
|
||||
process.destroy();
|
||||
}
|
||||
}
|
||||
}
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
package dev.overlord.zomboidforge.gradle;
|
||||
|
||||
import org.gradle.api.file.DirectoryProperty;
|
||||
import org.gradle.api.file.RegularFileProperty;
|
||||
import org.gradle.api.provider.ListProperty;
|
||||
import org.gradle.api.provider.MapProperty;
|
||||
import org.gradle.api.provider.Property;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
/**
|
||||
* The {@code zomboidForge { }} block of a mod's build:
|
||||
*
|
||||
* <pre>{@code
|
||||
* zomboidForge {
|
||||
* id = "shop"
|
||||
* entrypoint = "com.example.shop.ShopMod"
|
||||
* game("42.21") // only when the mod uses game classes
|
||||
* dependsOn("economy", "2.1") // other mods, id and minimum version
|
||||
* }
|
||||
* }</pre>
|
||||
*
|
||||
* The values become the mod's {@code META-INF/zomboidforge/mod.toml}.
|
||||
*/
|
||||
public abstract class ZomboidForgeExtension
|
||||
{
|
||||
/** The mod id: lowercase letters, digits, and single underscores, at most 32 characters. */
|
||||
public abstract Property<String> getId();
|
||||
|
||||
/** Display name. Default: the id. */
|
||||
public abstract Property<String> getName();
|
||||
|
||||
/** The mod's version. Default: the project version. */
|
||||
public abstract Property<String> getVersion();
|
||||
|
||||
/** The class that extends {@code dev.overlord.zomboidforge.api.Mod}. */
|
||||
public abstract Property<String> getEntrypoint();
|
||||
|
||||
/** ZomboidForge API version the mod is built against. Default: the plugin's version. */
|
||||
public abstract Property<String> getApi();
|
||||
|
||||
/** Project Zomboid versions the mod supports, as prefixes ("42", "42.21", "42.21.0"); empty when it uses no game classes. */
|
||||
public abstract ListProperty<String> getGame();
|
||||
|
||||
/** Earlier ids of the mod, whose stored tables move to the current id. */
|
||||
public abstract ListProperty<String> getPreviousIds();
|
||||
|
||||
/** Mod id to minimum version of every mod this one needs. */
|
||||
public abstract MapProperty<String, String> getDependencies();
|
||||
|
||||
/**
|
||||
* The {@code projectzomboid.jar} to compile and check against. Default: the Gradle property
|
||||
* {@code zomboidforge.gameJar}, else a local Steam installation of the dedicated server or
|
||||
* the game, else a download of the dedicated server with steamcmd.
|
||||
*/
|
||||
public abstract RegularFileProperty getGameJar();
|
||||
|
||||
/** Steam branch for the download: "public", "unstable", or a version branch such as "42.19". Default: "public". */
|
||||
public abstract Property<String> getSteamBranch();
|
||||
|
||||
/** Container engine for the download and {@code runServer}: "podman" or "docker". Default: the first one installed. */
|
||||
public abstract Property<String> getContainerEngine();
|
||||
|
||||
/** Image for {@code runServer}. Default: the ZomboidForge image tagged "latest". */
|
||||
public abstract Property<String> getServerImage();
|
||||
|
||||
/** Admin password of the {@code runServer} server. Default: "admin". */
|
||||
public abstract Property<String> getAdminPassword();
|
||||
|
||||
/** Volume for the {@code runServer} server's /data (world, config). Default: "zomboidforge-<id>". */
|
||||
public abstract Property<String> getDataVolume();
|
||||
|
||||
/** A server's {@code <forge>/mods} directory that {@code deployMod} copies the mod into. */
|
||||
public abstract DirectoryProperty getDeployDirectory();
|
||||
|
||||
/** Adds Project Zomboid versions the mod supports. */
|
||||
public void game(String... prefixes) { this.getGame().addAll(Arrays.asList(prefixes)); }
|
||||
|
||||
/** Adds earlier ids of the mod. */
|
||||
public void previousIds(String... ids) { this.getPreviousIds().addAll(Arrays.asList(ids)); }
|
||||
|
||||
/** Declares that the mod needs the mod {@code id} in {@code minimumVersion} or newer. */
|
||||
public void dependsOn(String id, String minimumVersion) { this.getDependencies().put(id, minimumVersion); }
|
||||
}
|
||||
+263
@@ -0,0 +1,263 @@
|
||||
package dev.overlord.zomboidforge.gradle;
|
||||
|
||||
import org.gradle.api.GradleException;
|
||||
import org.gradle.api.Plugin;
|
||||
import org.gradle.api.Project;
|
||||
import org.gradle.api.artifacts.Configuration;
|
||||
import org.gradle.api.artifacts.Dependency;
|
||||
import org.gradle.api.artifacts.dsl.DependencyHandler;
|
||||
import org.gradle.api.file.ProjectLayout;
|
||||
import org.gradle.api.file.RegularFile;
|
||||
import org.gradle.api.plugins.JavaPlugin;
|
||||
import org.gradle.api.plugins.JavaPluginExtension;
|
||||
import org.gradle.api.provider.Provider;
|
||||
import org.gradle.api.tasks.JavaExec;
|
||||
import org.gradle.api.tasks.SourceSet;
|
||||
import org.gradle.api.tasks.Sync;
|
||||
import org.gradle.api.tasks.TaskProvider;
|
||||
import org.gradle.api.tasks.bundling.Jar;
|
||||
import org.gradle.api.tasks.bundling.Zip;
|
||||
import org.gradle.jvm.toolchain.JavaLanguageVersion;
|
||||
import org.gradle.jvm.toolchain.JavaToolchainService;
|
||||
import org.gradle.language.base.plugins.LifecycleBasePlugin;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.List;
|
||||
import java.util.Properties;
|
||||
|
||||
/**
|
||||
* The plugin {@code dev.overlord.zomboidforge.mod}. Applies {@code java} and adds:
|
||||
*
|
||||
* <ul>
|
||||
* <li>dependencies: {@code dev.overlord.zomboidforge:api} (compile only), the game jar for
|
||||
* mods that declare {@code game} versions (compile only), and the configuration
|
||||
* {@code forgeMods} for other mods the mod compiles against;</li>
|
||||
* <li>{@code generateModDescriptor}: {@code mod.toml} from {@code zomboidForge { }};</li>
|
||||
* <li>{@code checkMod}: the server's load checks against the game jar (part of {@code check});</li>
|
||||
* <li>{@code modFolder}: {@code build/mod/<id>/} with {@code <id>.jar} and {@code lib/}, and
|
||||
* {@code modZip}: the same as {@code build/distributions/<id>-<version>.zip} (both part of
|
||||
* {@code assemble});</li>
|
||||
* <li>{@code runServer}: a ZomboidForge server in a container with the mod;
|
||||
* {@code deployMod}: copies the mod into a server's mods directory;</li>
|
||||
* <li>{@code downloadGame}: installs the dedicated server with steamcmd when no game jar is
|
||||
* configured or installed.</li>
|
||||
* </ul>
|
||||
*
|
||||
* Java compiles for Java 25 (the game's runtime) unless the build sets another toolchain.
|
||||
*/
|
||||
public final class ZomboidForgeModPlugin implements Plugin<Project>
|
||||
{
|
||||
public static final String GROUP = "zomboidforge";
|
||||
|
||||
private static final String API = "dev.overlord.zomboidforge:api:";
|
||||
private static final String TOOLS = "dev.overlord.zomboidforge:mod-tools:";
|
||||
private static final String TOOLS_MAIN = "dev.overlord.zomboidforge.tools.ModCheck";
|
||||
private static final String DEFAULT_IMAGE = "git.security-command.org/overlord/zomboidforge:latest";
|
||||
private static final int JAVA = 25;
|
||||
|
||||
@Override
|
||||
public void apply(Project project)
|
||||
{
|
||||
project.getPluginManager().apply(JavaPlugin.class);
|
||||
|
||||
String version = ZomboidForgeModPlugin.version();
|
||||
ProjectLayout layout = project.getLayout();
|
||||
DependencyHandler handler = project.getDependencies();
|
||||
ZomboidForgeExtension extension = project.getExtensions().create("zomboidForge", ZomboidForgeExtension.class);
|
||||
|
||||
extension.getName().convention(extension.getId());
|
||||
extension.getVersion().convention(project.provider(() -> project.getVersion().toString()));
|
||||
extension.getApi().convention(version);
|
||||
extension.getSteamBranch().convention("public");
|
||||
extension.getServerImage().convention(ZomboidForgeModPlugin.DEFAULT_IMAGE);
|
||||
extension.getAdminPassword().convention("admin");
|
||||
extension.getDataVolume().convention(extension.getId().map(id -> "zomboidforge-" + id));
|
||||
extension.getGameJar().convention(layout.file(project.getProviders().gradleProperty("zomboidforge.gameJar").map(File::new)));
|
||||
|
||||
JavaPluginExtension java = project.getExtensions().getByType(JavaPluginExtension.class);
|
||||
java.getToolchain().getLanguageVersion().convention(JavaLanguageVersion.of(ZomboidForgeModPlugin.JAVA));
|
||||
|
||||
// Game jar: configured, else installed, else downloaded.
|
||||
Provider<String> branch = extension.getSteamBranch();
|
||||
File cache = new File(project.getGradle().getGradleUserHomeDir(), "caches/zomboidforge/server");
|
||||
Provider<File> installed = project.getProviders().of(LocalGameJar.class, spec -> {}).map(File::new);
|
||||
Provider<File> download = branch.map(name -> new File(new File(cache, name), DownloadGame.JAR));
|
||||
Provider<File> gameJar = extension.getGameJar().map(RegularFile::getAsFile).orElse(installed).orElse(download);
|
||||
|
||||
TaskProvider<DownloadGame> downloadGame = project.getTasks().register("downloadGame", DownloadGame.class, task ->
|
||||
{
|
||||
task.setGroup(ZomboidForgeModPlugin.GROUP);
|
||||
task.setDescription("Installs the Project Zomboid dedicated server with steamcmd for its projectzomboid.jar, when no game jar is configured or installed.");
|
||||
task.getInstallDirectory().set(layout.dir(branch.map(name -> new File(cache, name))));
|
||||
task.getBranch().set(branch);
|
||||
task.getContainerEngine().set(extension.getContainerEngine());
|
||||
|
||||
Provider<Boolean> missing = extension.getGameJar().map(file -> false).orElse(installed.map(file -> false)).orElse(true);
|
||||
Provider<Boolean> needed = extension.getGame().map(game -> !game.isEmpty()).zip(missing, (uses, absent) -> uses && absent);
|
||||
task.onlyIf("the mod declares game versions and no game jar is configured or installed", element -> needed.get());
|
||||
});
|
||||
|
||||
Provider<Boolean> usesGame = extension.getGame().map(game -> !game.isEmpty());
|
||||
Provider<File> noJar = project.getObjects().property(File.class);
|
||||
|
||||
// Dependencies.
|
||||
Configuration forgeMods = project.getConfigurations().create("forgeMods", configuration ->
|
||||
{
|
||||
configuration.setDescription("Other ZomboidForge mods this mod compiles against; declare them in zomboidForge.dependsOn as well.");
|
||||
configuration.setCanBeConsumed(false);
|
||||
configuration.setCanBeResolved(false);
|
||||
});
|
||||
|
||||
Configuration forgeModJars = project.getConfigurations().create("forgeModJars", configuration ->
|
||||
{
|
||||
configuration.setDescription("The jars of forgeMods, for checkMod.");
|
||||
configuration.setCanBeConsumed(false);
|
||||
configuration.setTransitive(false);
|
||||
configuration.extendsFrom(forgeMods);
|
||||
});
|
||||
|
||||
Configuration tools = project.getConfigurations().create("zomboidForgeTools", configuration ->
|
||||
{
|
||||
configuration.setDescription("The ZomboidForge mod tools that checkMod runs.");
|
||||
configuration.setCanBeConsumed(false);
|
||||
configuration.getDependencies().add(handler.create(ZomboidForgeModPlugin.TOOLS + version));
|
||||
});
|
||||
|
||||
for (String name : List.of(JavaPlugin.COMPILE_ONLY_CONFIGURATION_NAME, JavaPlugin.TEST_IMPLEMENTATION_CONFIGURATION_NAME))
|
||||
{
|
||||
Configuration configuration = project.getConfigurations().getByName(name);
|
||||
|
||||
configuration.extendsFrom(forgeMods);
|
||||
configuration.getDependencies().add(handler.create(ZomboidForgeModPlugin.API + version));
|
||||
}
|
||||
|
||||
for (String name : List.of(JavaPlugin.COMPILE_ONLY_CONFIGURATION_NAME, JavaPlugin.TEST_COMPILE_ONLY_CONFIGURATION_NAME))
|
||||
{
|
||||
project.getConfigurations().getByName(name).getDependencies().addAllLater(usesGame.map(uses -> uses
|
||||
? List.<Dependency>of(handler.create(project.files(gameJar).builtBy(downloadGame)))
|
||||
: List.<Dependency>of()
|
||||
));
|
||||
}
|
||||
|
||||
// mod.toml.
|
||||
SourceSet main = java.getSourceSets().getByName(SourceSet.MAIN_SOURCE_SET_NAME);
|
||||
File generated = layout.getBuildDirectory().dir("generated/zomboidforge/descriptor").get().getAsFile();
|
||||
|
||||
TaskProvider<GenerateModDescriptor> generate = project.getTasks().register("generateModDescriptor", GenerateModDescriptor.class, task ->
|
||||
{
|
||||
task.setGroup(ZomboidForgeModPlugin.GROUP);
|
||||
task.setDescription("Writes META-INF/zomboidforge/mod.toml from zomboidForge { }.");
|
||||
task.getModId().set(extension.getId());
|
||||
task.getModName().set(extension.getName());
|
||||
task.getModVersion().set(extension.getVersion());
|
||||
task.getEntrypoint().set(extension.getEntrypoint());
|
||||
task.getApi().set(extension.getApi());
|
||||
task.getGame().set(extension.getGame());
|
||||
task.getPreviousIds().set(extension.getPreviousIds());
|
||||
task.getDependencies().set(extension.getDependencies());
|
||||
task.getOutputDirectory().set(generated);
|
||||
task.getHandWritten().from(project.provider(() -> main.getResources().getSrcDirs().stream()
|
||||
.filter(directory -> !directory.equals(generated))
|
||||
.map(directory -> new File(directory, GenerateModDescriptor.PATH))
|
||||
.toList()));
|
||||
});
|
||||
|
||||
main.getResources().srcDir(generate);
|
||||
|
||||
// Checks.
|
||||
TaskProvider<Jar> jar = project.getTasks().named(JavaPlugin.JAR_TASK_NAME, Jar.class);
|
||||
Configuration runtime = project.getConfigurations().getByName(JavaPlugin.RUNTIME_CLASSPATH_CONFIGURATION_NAME);
|
||||
JavaToolchainService toolchains = project.getExtensions().getByType(JavaToolchainService.class);
|
||||
|
||||
TaskProvider<JavaExec> checkMod = project.getTasks().register("checkMod", JavaExec.class, task ->
|
||||
{
|
||||
task.setGroup(LifecycleBasePlugin.VERIFICATION_GROUP);
|
||||
task.setDescription("Checks the mod the way the server does when it loads it, against the game jar.");
|
||||
task.getMainClass().set(ZomboidForgeModPlugin.TOOLS_MAIN);
|
||||
task.setClasspath(tools);
|
||||
task.getJavaLauncher().set(toolchains.launcherFor(spec -> spec.getLanguageVersion().set(JavaLanguageVersion.of(ZomboidForgeModPlugin.JAVA))));
|
||||
task.dependsOn(downloadGame);
|
||||
|
||||
CheckModArguments arguments = project.getObjects().newInstance(CheckModArguments.class);
|
||||
arguments.getJar().set(jar.flatMap(Jar::getArchiveFile));
|
||||
arguments.getLibraries().from(runtime);
|
||||
arguments.getDependencies().from(forgeModJars);
|
||||
arguments.getGameJar().set(layout.file(usesGame.flatMap(uses -> uses ? gameJar : noJar)));
|
||||
arguments.getReport().set(layout.getBuildDirectory().file("zomboidforge/check.txt"));
|
||||
|
||||
task.getArgumentProviders().add(arguments);
|
||||
});
|
||||
|
||||
project.getTasks().named(LifecycleBasePlugin.CHECK_TASK_NAME, task -> task.dependsOn(checkMod));
|
||||
|
||||
// Packaging.
|
||||
Provider<String> id = extension.getId().orElse(project.provider(() ->
|
||||
{
|
||||
throw new GradleException("zomboidForge.id is not set; every mod needs an id, e.g. zomboidForge { id = \"shop\" }.");
|
||||
}));
|
||||
|
||||
TaskProvider<Sync> modFolder = project.getTasks().register("modFolder", Sync.class, task ->
|
||||
{
|
||||
task.setGroup(ZomboidForgeModPlugin.GROUP);
|
||||
task.setDescription("Assembles build/mod/<id>/ with <id>.jar and lib/, as a server expects it in <forge>/mods.");
|
||||
task.dependsOn(checkMod);
|
||||
task.into(layout.getBuildDirectory().dir(id.map(name -> "mod/" + name)));
|
||||
task.from(jar, spec -> spec.rename(name -> id.get() + ".jar"));
|
||||
task.from(runtime, spec -> spec.into("lib"));
|
||||
});
|
||||
|
||||
TaskProvider<Zip> modZip = project.getTasks().register("modZip", Zip.class, task ->
|
||||
{
|
||||
task.setGroup(ZomboidForgeModPlugin.GROUP);
|
||||
task.setDescription("Packs the mod folder as build/distributions/<id>-<version>.zip, ready to unpack into <forge>/mods.");
|
||||
task.from(modFolder, spec -> spec.into(id));
|
||||
task.getArchiveFileName().set(id.zip(extension.getVersion(), (name, modVersion) -> name + "-" + modVersion + ".zip"));
|
||||
task.getDestinationDirectory().set(layout.getBuildDirectory().dir("distributions"));
|
||||
});
|
||||
|
||||
project.getTasks().named(LifecycleBasePlugin.ASSEMBLE_TASK_NAME, task -> task.dependsOn(modFolder, modZip));
|
||||
|
||||
// Trying the mod.
|
||||
project.getTasks().register("runServer", RunServer.class, task ->
|
||||
{
|
||||
task.setGroup(ZomboidForgeModPlugin.GROUP);
|
||||
task.setDescription("Runs a ZomboidForge server in a container with this mod; stop the build to stop the server.");
|
||||
task.dependsOn(modFolder);
|
||||
task.getModsDirectory().set(layout.getBuildDirectory().dir("mod"));
|
||||
task.getImage().set(extension.getServerImage());
|
||||
task.getContainerName().set(id.map(name -> "zomboidforge-" + name));
|
||||
task.getDataVolume().set(extension.getDataVolume());
|
||||
task.getAdminPassword().set(extension.getAdminPassword());
|
||||
task.getContainerEngine().set(extension.getContainerEngine());
|
||||
});
|
||||
|
||||
project.getTasks().register("deployMod", Sync.class, task ->
|
||||
{
|
||||
task.setGroup(ZomboidForgeModPlugin.GROUP);
|
||||
task.setDescription("Copies the mod folder into zomboidForge.deployDirectory (a server's mods directory).");
|
||||
task.from(modFolder);
|
||||
task.into(extension.getDeployDirectory().dir(id).orElse(layout.getBuildDirectory().dir("deploy-not-configured")));
|
||||
task.onlyIf("zomboidForge.deployDirectory is set", element -> extension.getDeployDirectory().isPresent());
|
||||
});
|
||||
}
|
||||
|
||||
/** The plugin's version, which is also the version of the API and mod tools it uses. */
|
||||
static String version()
|
||||
{
|
||||
try (InputStream in = ZomboidForgeModPlugin.class.getResourceAsStream("plugin.properties"))
|
||||
{
|
||||
if (in == null) throw new GradleException("The ZomboidForge plugin has no plugin.properties.");
|
||||
|
||||
Properties properties = new Properties();
|
||||
properties.load(in);
|
||||
|
||||
return properties.getProperty("version");
|
||||
}
|
||||
catch (IOException e)
|
||||
{
|
||||
throw new GradleException("Cannot read the ZomboidForge plugin version.", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
/**
|
||||
* The ZomboidForge Gradle plugin for mod authors. Targets Java 17: it runs in the mod's
|
||||
* Gradle JVM.
|
||||
*
|
||||
* @noinspection UnstableApiUsage, RedundantSuppression
|
||||
*/
|
||||
@NotNullByDefault
|
||||
package dev.overlord.zomboidforge.gradle;
|
||||
|
||||
import org.jetbrains.annotations.NotNullByDefault;
|
||||
@@ -0,0 +1 @@
|
||||
version=${version}
|
||||
+255
@@ -0,0 +1,255 @@
|
||||
package dev.overlord.zomboidforge.gradle;
|
||||
|
||||
import org.gradle.testkit.runner.BuildResult;
|
||||
import org.gradle.testkit.runner.GradleRunner;
|
||||
import org.gradle.testkit.runner.TaskOutcome;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.objectweb.asm.ClassWriter;
|
||||
import org.objectweb.asm.MethodVisitor;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.jar.JarEntry;
|
||||
import java.util.jar.JarFile;
|
||||
import java.util.jar.JarOutputStream;
|
||||
import java.util.zip.ZipFile;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.objectweb.asm.Opcodes.ACC_FINAL;
|
||||
import static org.objectweb.asm.Opcodes.ACC_PRIVATE;
|
||||
import static org.objectweb.asm.Opcodes.ACC_PUBLIC;
|
||||
import static org.objectweb.asm.Opcodes.ACC_STATIC;
|
||||
import static org.objectweb.asm.Opcodes.ARETURN;
|
||||
import static org.objectweb.asm.Opcodes.BIPUSH;
|
||||
import static org.objectweb.asm.Opcodes.DUP;
|
||||
import static org.objectweb.asm.Opcodes.INVOKESPECIAL;
|
||||
import static org.objectweb.asm.Opcodes.NEW;
|
||||
import static org.objectweb.asm.Opcodes.PUTSTATIC;
|
||||
import static org.objectweb.asm.Opcodes.RETURN;
|
||||
import static org.objectweb.asm.Opcodes.V25;
|
||||
|
||||
/** Builds mod projects with the plugin, against api and mod-tools published to build/repo. */
|
||||
class ZomboidForgeModPluginTest
|
||||
{
|
||||
private static final String REPOSITORY = System.getProperty("zomboidforge.testRepository");
|
||||
|
||||
@TempDir
|
||||
Path project;
|
||||
|
||||
private void write(String path, String content) throws IOException
|
||||
{
|
||||
Path file = this.project.resolve(path);
|
||||
Files.createDirectories(file.getParent());
|
||||
Files.writeString(file, content);
|
||||
}
|
||||
|
||||
/** A mod project {@code shop} with {@code extra} in {@code zomboidForge { }} and {@code body} in the entry point. */
|
||||
private void modProject(String extra, String body) throws IOException
|
||||
{
|
||||
this.write("settings.gradle.kts", """
|
||||
rootProject.name = "shop"
|
||||
|
||||
dependencyResolutionManagement {
|
||||
repositories {
|
||||
maven { url = uri("%s") }
|
||||
}
|
||||
}
|
||||
""".formatted(Path.of(ZomboidForgeModPluginTest.REPOSITORY).toUri()));
|
||||
|
||||
this.write("build.gradle.kts", """
|
||||
plugins {
|
||||
id("dev.overlord.zomboidforge.mod")
|
||||
}
|
||||
|
||||
version = "1.2.0"
|
||||
|
||||
zomboidForge {
|
||||
id = "shop"
|
||||
entrypoint = "com.example.shop.ShopMod"
|
||||
%s
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation(files("libs/util.jar"))
|
||||
}
|
||||
""".formatted(extra));
|
||||
|
||||
this.write("src/main/java/com/example/shop/ShopMod.java", """
|
||||
package com.example.shop;
|
||||
|
||||
import dev.overlord.zomboidforge.api.Mod;
|
||||
|
||||
public final class ShopMod extends Mod
|
||||
{
|
||||
@Override
|
||||
public void onLoad() { %s }
|
||||
}
|
||||
""".formatted(body));
|
||||
|
||||
Files.createDirectories(this.project.resolve("libs"));
|
||||
ZomboidForgeModPluginTest.jar(this.project.resolve("libs/util.jar"), Map.of("util/Util.class", ZomboidForgeModPluginTest.emptyClass("util/Util")));
|
||||
}
|
||||
|
||||
private GradleRunner runner(String... arguments)
|
||||
{
|
||||
List<String> all = new ArrayList<>(List.of(arguments));
|
||||
all.add("--stacktrace");
|
||||
|
||||
return GradleRunner.create().withProjectDir(this.project.toFile()).withPluginClasspath().withArguments(all).forwardOutput();
|
||||
}
|
||||
|
||||
@Test
|
||||
void buildsChecksAndPackagesAnApiOnlyMod() throws IOException
|
||||
{
|
||||
this.modProject("", "this.logger().log(System.Logger.Level.INFO, \"hi\");");
|
||||
|
||||
BuildResult result = this.runner("build", "--configuration-cache").build();
|
||||
|
||||
assertEquals(TaskOutcome.SKIPPED, result.task(":downloadGame").getOutcome());
|
||||
assertTrue(result.getOutput().contains("Mod 'shop' 1.2.0 passed the checks (no game jar: the mod declares no game versions)."), "the check ran");
|
||||
|
||||
Path folder = this.project.resolve("build/mod/shop");
|
||||
assertTrue(Files.isRegularFile(folder.resolve("lib/util.jar")));
|
||||
|
||||
try (JarFile jar = new JarFile(folder.resolve("shop.jar").toFile()))
|
||||
{
|
||||
String toml = new String(jar.getInputStream(jar.getEntry("META-INF/zomboidforge/mod.toml")).readAllBytes(), StandardCharsets.UTF_8);
|
||||
|
||||
assertTrue(toml.contains("id = \"shop\""), toml);
|
||||
assertTrue(toml.contains("version = \"1.2.0\""), toml);
|
||||
assertTrue(toml.contains("entrypoint = \"com.example.shop.ShopMod\""), toml);
|
||||
assertTrue(jar.getEntry("com/example/shop/ShopMod.class") != null);
|
||||
}
|
||||
|
||||
try (ZipFile zip = new ZipFile(this.project.resolve("build/distributions/shop-1.2.0.zip").toFile()))
|
||||
{
|
||||
assertTrue(zip.getEntry("shop/shop.jar") != null);
|
||||
assertTrue(zip.getEntry("shop/lib/util.jar") != null);
|
||||
}
|
||||
|
||||
BuildResult again = this.runner("build", "--configuration-cache").build();
|
||||
assertTrue(again.getOutput().contains("Configuration cache entry reused."), "the plugin works with the configuration cache");
|
||||
assertEquals(TaskOutcome.UP_TO_DATE, again.task(":checkMod").getOutcome());
|
||||
}
|
||||
|
||||
@Test
|
||||
void checksAGameModAgainstTheGameJar() throws IOException
|
||||
{
|
||||
this.gameJar(42, 21);
|
||||
this.modProject("""
|
||||
game("42.21")
|
||||
gameJar = file("game/projectzomboid.jar")
|
||||
dependsOn("economy", "2.0")
|
||||
""", "String version = zombie.core.Core.versionText();");
|
||||
|
||||
BuildResult result = this.runner("build").build();
|
||||
|
||||
assertTrue(result.getOutput().contains("Mod 'shop' 1.2.0 passed the checks against Project Zomboid 42.21.0."), "the check ran against the game jar");
|
||||
|
||||
try (JarFile jar = new JarFile(this.project.resolve("build/mod/shop/shop.jar").toFile()))
|
||||
{
|
||||
String toml = new String(jar.getInputStream(jar.getEntry("META-INF/zomboidforge/mod.toml")).readAllBytes(), StandardCharsets.UTF_8);
|
||||
|
||||
assertTrue(toml.contains("game = [\"42.21\"]"), toml);
|
||||
assertTrue(toml.contains("[dependencies]\neconomy = \"2.0\""), toml);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void failsWhenTheGameJarIsNotADeclaredVersion() throws IOException
|
||||
{
|
||||
this.gameJar(42, 21);
|
||||
this.modProject("""
|
||||
game("42.20")
|
||||
gameJar = file("game/projectzomboid.jar")
|
||||
""", "");
|
||||
|
||||
BuildResult result = this.runner("build").buildAndFail();
|
||||
|
||||
assertEquals(TaskOutcome.FAILED, result.task(":checkMod").getOutcome());
|
||||
assertTrue(result.getOutput().contains("is Project Zomboid 42.21.0, but the mod declares [42.20]"), result.getOutput());
|
||||
}
|
||||
|
||||
@Test
|
||||
void failsForAHandWrittenDescriptor() throws IOException
|
||||
{
|
||||
this.modProject("", "");
|
||||
this.write("src/main/resources/META-INF/zomboidforge/mod.toml", "id = \"shop\"\n");
|
||||
|
||||
BuildResult result = this.runner("build").buildAndFail();
|
||||
|
||||
assertTrue(result.getOutput().contains("is written by hand; the ZomboidForge plugin generates mod.toml from zomboidForge { }."), result.getOutput());
|
||||
}
|
||||
|
||||
@Test
|
||||
void failsWhenTheEntryPointIsMissing() throws IOException
|
||||
{
|
||||
this.modProject("", "");
|
||||
this.write("build.gradle.kts", Files.readString(this.project.resolve("build.gradle.kts")).replace("com.example.shop.ShopMod", "com.example.shop.Missing"));
|
||||
|
||||
BuildResult result = this.runner("build").buildAndFail();
|
||||
|
||||
assertTrue(result.getOutput().contains("The entry point 'com.example.shop.Missing' is not in 'shop-1.2.0.jar'."), result.getOutput());
|
||||
}
|
||||
|
||||
/** {@code game/projectzomboid.jar} with a {@code zombie/core/Core} that reports {@code major.minor} and has {@code versionText()}. */
|
||||
private void gameJar(int major, int minor) throws IOException
|
||||
{
|
||||
ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
|
||||
writer.visit(V25, ACC_PUBLIC, "zombie/core/Core", null, "java/lang/Object", null);
|
||||
writer.visitField(ACC_PRIVATE | ACC_STATIC | ACC_FINAL, "gameVersion", "Lzombie/core/GameVersion;", null, null);
|
||||
writer.visitField(ACC_PRIVATE | ACC_STATIC | ACC_FINAL, "buildVersion", "I", null, 0);
|
||||
|
||||
MethodVisitor clinit = writer.visitMethod(ACC_STATIC, "<clinit>", "()V", null, null);
|
||||
clinit.visitTypeInsn(NEW, "zombie/core/GameVersion");
|
||||
clinit.visitInsn(DUP);
|
||||
clinit.visitIntInsn(BIPUSH, major);
|
||||
clinit.visitIntInsn(BIPUSH, minor);
|
||||
clinit.visitLdcInsn("");
|
||||
clinit.visitMethodInsn(INVOKESPECIAL, "zombie/core/GameVersion", "<init>", "(IILjava/lang/String;)V", false);
|
||||
clinit.visitFieldInsn(PUTSTATIC, "zombie/core/Core", "gameVersion", "Lzombie/core/GameVersion;");
|
||||
clinit.visitInsn(RETURN);
|
||||
clinit.visitMaxs(0, 0);
|
||||
|
||||
MethodVisitor versionText = writer.visitMethod(ACC_PUBLIC | ACC_STATIC, "versionText", "()Ljava/lang/String;", null, null);
|
||||
versionText.visitLdcInsn(major + "." + minor);
|
||||
versionText.visitInsn(ARETURN);
|
||||
versionText.visitMaxs(0, 0);
|
||||
|
||||
writer.visitEnd();
|
||||
|
||||
Path jar = this.project.resolve("game/projectzomboid.jar");
|
||||
Files.createDirectories(jar.getParent());
|
||||
ZomboidForgeModPluginTest.jar(jar, Map.of("zombie/core/Core.class", writer.toByteArray()));
|
||||
}
|
||||
|
||||
private static byte[] emptyClass(String name)
|
||||
{
|
||||
ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
|
||||
writer.visit(V25, ACC_PUBLIC, name, null, "java/lang/Object", null);
|
||||
writer.visitEnd();
|
||||
|
||||
return writer.toByteArray();
|
||||
}
|
||||
|
||||
private static void jar(Path jar, Map<String, byte[]> entries) throws IOException
|
||||
{
|
||||
try (OutputStream file = Files.newOutputStream(jar); JarOutputStream out = new JarOutputStream(file))
|
||||
{
|
||||
for (Map.Entry<String, byte[]> entry : entries.entrySet())
|
||||
{
|
||||
out.putNextEntry(new JarEntry(entry.getKey()));
|
||||
out.write(entry.getValue());
|
||||
out.closeEntry();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user