Add mod setup tools and project initialization support.

This commit is contained in:
Overlord committed 2026-10-10 19:16:56 +02:00
1 parent a5766f3a1b
commit 32fab0c1d4
9 files changed
+674 -45

No files matched your search

+51 -36
View File
@@ -5,54 +5,68 @@ described in the [README](README.md#mods).
## Project setup ## Project setup
A mod is a normal Gradle project with the ZomboidForge plugin. It needs JDK 25 (Project A mod project starts as one file. It needs JDK 25 (Project Zomboid's runtime); the plugin sets
Zomboid's runtime); the plugin sets the Java toolchain to 25. the Java toolchain to 25.
`settings.gradle.kts`: 1. Create a directory with this `settings.gradle.kts`, with your mod's id, version, and entry
point:
```kotlin ```kotlin
pluginManagement { pluginManagement {
repositories { repositories { maven("https://git.security-command.org/api/packages/overlord/maven") }
maven("https://git.security-command.org/api/packages/overlord/maven")
gradlePluginPortal()
} }
}
dependencyResolutionManagement { plugins {
repositories { id("dev.overlord.zomboidforge") version "0.6.0" // the plugin's version is the API version
maven("https://git.security-command.org/api/packages/overlord/maven")
mavenCentral() // the API depends on org.jetbrains:annotations
} }
}
rootProject.name = "shop" zomboidForge {
id = "shop"
version = "1.0.0"
entrypoint = "com.example.shop.ShopMod"
}
```
2. Run in that directory (Linux, macOS, Windows; on Windows PowerShell 5.1 write `curl.exe`):
```
curl -fsSL https://git.security-command.org/Overlord/ZomboidForge/raw/branch/master/zomboidforge.jsh | jshell -
```
The command sets the newest ZomboidForge version in `settings.gradle.kts`, writes the Gradle
wrapper (`gradlew`, `gradlew.bat`, `gradle/wrapper/`), creates `.gitignore` and the entry point
class when they are missing, and builds the mod. It needs no installed Gradle.
The same command updates a project to the newest version; a given version goes in
`-R-Dzomboidforge.version`:
```
curl -fsSL https://git.security-command.org/Overlord/ZomboidForge/raw/branch/master/zomboidforge.jsh | jshell -R-Dzomboidforge.version=0.7.0 -
``` ```
`build.gradle.kts`: It prints links to this document in the new version and to the changes since the old one, and
ends with a build, so code that the new version breaks shows at once. Files other than the
version line in `settings.gradle.kts` and the wrapper stay as they are.
The root project is named after the mod id. The plugin adds the API
(`dev.overlord.zomboidforge:api`) as a compile-only dependency, and the game jar for mods that
declare `game` versions. Default settings go into
`src/main/resources/META-INF/zomboidforge/config.toml`.
Libraries and other mods go into an optional `build.gradle.kts`, which can also set any
`zomboidForge { }` setting:
```kotlin ```kotlin
plugins {
id("dev.overlord.zomboidforge.mod") version "0.6.0" // the plugin's version is the API version
}
version = "1.2.0"
zomboidForge {
id = "shop"
entrypoint = "com.example.shop.ShopMod"
game("42") // only when the mod uses game classes
dependsOn("economy", "2.1") // other mods: id and minimum version
}
dependencies { dependencies {
implementation("com.google.code.gson:gson:2.11.0") // libraries go into the mod's lib/ implementation("com.google.code.gson:gson:2.11.0") // libraries go into the mod's lib/
forgeMods("com.example:economy:2.1") // other mods to compile against forgeMods("com.example:economy:2.1") // other mods to compile against
} }
```
The plugin adds the API (`dev.overlord.zomboidforge:api`) as a compile-only dependency, and the zomboidForge {
game jar for mods that declare `game` versions. Default settings go into game("42") // only when the mod uses game classes
`src/main/resources/META-INF/zomboidforge/config.toml`. dependsOn("economy", "2.1") // other mods: id and minimum version
}
```
### `zomboidForge { }` ### `zomboidForge { }`
@@ -61,7 +75,7 @@ game jar for mods that declare `game` versions. Default settings go into
| `id` | (required) | lowercase letters, digits, single underscores; at most 32 characters | | `id` | (required) | lowercase letters, digits, single underscores; at most 32 characters |
| `entrypoint` | (required) | the class that extends `Mod` | | `entrypoint` | (required) | the class that extends `Mod` |
| `name` | the id | display name | | `name` | the id | display name |
| `version` | the project version | the mod's version | | `version` | (required) | the mod's version, such as `1.2.0` |
| `api` | the plugin's version | ZomboidForge API version the mod is built against | | `api` | the plugin's version | ZomboidForge API version the mod is built against |
| `game(...)` | none | supported Project Zomboid versions: `"42"`, `"42.21"`, `"42.21.0"` | | `game(...)` | none | supported Project Zomboid versions: `"42"`, `"42.21"`, `"42.21.0"` |
| `dependsOn(id, version)` | none | another mod this one needs, with its minimum version | | `dependsOn(id, version)` | none | another mod this one needs, with its minimum version |
@@ -99,14 +113,15 @@ The game jar has to be one of the declared `game` versions; the check below fail
### Tasks ### Tasks
| Task | Does | | Task | Does |
|----------------|---------------------------------------------------------------------------------------------| |---------------------|---------------------------------------------------------------------------------------------|
| `build` | compiles, runs `checkMod`, and assembles the mod | | `build` | compiles, runs `checkMod`, and assembles the mod |
| `checkMod` | the server's load checks, at build time (see [Checks at startup](#checks-at-startup)) | | `checkMod` | the server's load checks, at build time (see [checks at startup](#checks-at-startup)) |
| `modFolder` | `build/mod/<id>/` with `<id>.jar` and `lib/`, as a server expects it in `<forge>/mods` | | `modFolder` | `build/mod/<id>/` with `<id>.jar` and `lib/`, as a server expects it in `<forge>/mods` |
| `modZip` | the same as `build/distributions/<id>-<version>.zip` | | `modZip` | the same as `build/distributions/<id>-<version>.zip` |
| `runServer` | a ZomboidForge server in a container with the mod; Ctrl+C stops it after it saved the world | | `runServer` | a ZomboidForge server in a container with the mod; Ctrl+C stops it after it saved the world |
| `deployMod` | copies the mod folder into `deployDirectory`; keeps the server's `config.toml` of the mod | | `deployMod` | copies the mod folder into `deployDirectory`; keeps the server's `config.toml` of the mod |
| `downloadGame` | installs the dedicated server for its game jar; runs only when needed | | `downloadGame` | installs the dedicated server for its game jar; runs only when needed |
| `zomboidForgeSetup` | creates `.gitignore` and the entry point class when they are missing |
`runServer` is reachable from this machine only, unless `serverAddress` says otherwise. Without `runServer` is reachable from this machine only, unless `serverAddress` says otherwise. Without
`adminPassword`, the first run generates a random admin password for the volume, prints it, and `adminPassword`, the first run generates a random admin password for the volume, prints it, and
+2 -2
View File
@@ -1,8 +1,8 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# #
# Publishes the mod API (dev.overlord.zomboidforge:api), the mod tools (mod-tools), and the # Publishes the mod API (dev.overlord.zomboidforge:api), the mod tools (mod-tools), and the
# Gradle plugin (dev.overlord.zomboidforge.mod) to the Maven registry of the ZomboidForge Gitea, # Gradle plugins (dev.overlord.zomboidforge, dev.overlord.zomboidforge.mod) to the Maven registry
# in the version of the v* git tag on HEAD, without the "v". # of the ZomboidForge Gitea, in the version of the v* git tag on HEAD, without the "v".
# #
# A pre-release version (containing "-", e.g. 0.3.0-rc.1) is built and tested but never # A pre-release version (containing "-", e.g. 0.3.0-rc.1) is built and tested but never
# published. Without a v* tag on HEAD nothing is published. # published. Without a v* tag on HEAD nothing is published.
+23 -5
View File
@@ -1,6 +1,7 @@
// Gradle plugin for mod authors (id dev.overlord.zomboidforge.mod): dependencies, mod.toml, // Gradle plugins for mod authors (ids dev.overlord.zomboidforge for settings.gradle.kts and
// build-time checks, packaging, and a local test server. Runs inside the mod's Gradle JVM, so // dev.overlord.zomboidforge.mod): dependencies, mod.toml, build-time checks, packaging, and a
// it targets Java 17; the checks run in a separate Java 25 process (mod-tools). // 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 { plugins {
id("zomboidforge.java-conventions") id("zomboidforge.java-conventions")
@@ -20,6 +21,13 @@ gradlePlugin {
displayName = "ZomboidForge mod" displayName = "ZomboidForge mod"
description = "Builds, checks, and packages server-side Java mods for ZomboidForge." description = "Builds, checks, and packages server-side Java mods for ZomboidForge."
} }
create("settings") {
id = "dev.overlord.zomboidforge"
implementationClass = "dev.overlord.zomboidforge.gradle.ZomboidForgeSettingsPlugin"
displayName = "ZomboidForge mod project"
description = "Makes a ZomboidForge mod project a single settings.gradle.kts."
}
} }
} }
@@ -38,9 +46,19 @@ dependencies {
} }
tasks.test { tasks.test {
// The functional tests resolve api and mod-tools from the repository in build/repo. // The functional tests resolve api and mod-tools from the repository in build/repo, the
dependsOn(":api:publishAllPublicationsToBuildRepository", ":mod-tools:publishAllPublicationsToBuildRepository") // updater tests the plugin as well.
dependsOn(
":api:publishAllPublicationsToBuildRepository",
":mod-tools:publishAllPublicationsToBuildRepository",
"publishAllPublicationsToBuildRepository",
)
val repository = layout.settingsDirectory.dir("build/repo").asFile.absolutePath val repository = layout.settingsDirectory.dir("build/repo").asFile.absolutePath
systemProperty("zomboidforge.testRepository", repository) systemProperty("zomboidforge.testRepository", repository)
// The updater tests run zomboidforge.jsh with the wrapper of the repository root.
val root = layout.settingsDirectory.asFile.absolutePath
inputs.file(layout.settingsDirectory.file("zomboidforge.jsh"))
systemProperty("zomboidforge.root", root)
} }
@@ -0,0 +1,66 @@
package dev.overlord.zomboidforge.gradle;
import org.gradle.api.DefaultTask;
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.TaskAction;
import org.gradle.api.tasks.UntrackedTask;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
/**
* Creates the files a new mod project needs and does not have yet: {@code .gitignore} and the
* entry point class with an empty {@code onLoad()}. Existing files stay as they are.
*/
@UntrackedTask(because = "Creates missing files once and never changes existing ones")
public abstract class SetupMod extends DefaultTask
{
private static final String GITIGNORE = """
.gradle/
build/
""";
private static final String ENTRY_POINT = """
%simport dev.overlord.zomboidforge.api.Mod;
public final class %s extends Mod
{
@Override
public void onLoad() {}
}
""";
@Internal
public abstract DirectoryProperty getProjectDirectory();
@Input
public abstract Property<String> getEntrypoint();
@TaskAction
public void setup() throws IOException
{
Path directory = this.getProjectDirectory().get().getAsFile().toPath();
String entrypoint = this.getEntrypoint().get();
int dot = entrypoint.lastIndexOf('.');
String packageLine = dot < 0 ? "" : "package " + entrypoint.substring(0, dot) + ";\n\n";
String className = entrypoint.substring(dot + 1);
this.create(directory, ".gitignore", SetupMod.GITIGNORE);
this.create(directory, "src/main/java/" + entrypoint.replace('.', '/') + ".java", SetupMod.ENTRY_POINT.formatted(packageLine, className));
}
private void create(Path directory, String path, String content) throws IOException
{
Path file = directory.resolve(path);
if (Files.exists(file)) return;
Files.createDirectories(file.getParent());
Files.writeString(file, content);
this.getLogger().lifecycle("Created '{}'.", path);
}
}
@@ -42,14 +42,20 @@ import java.util.Properties;
* <li>{@code runServer}: a ZomboidForge server in a container with the mod; * <li>{@code runServer}: a ZomboidForge server in a container with the mod;
* {@code deployMod}: copies the mod into a server's mods directory;</li> * {@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 * <li>{@code downloadGame}: installs the dedicated server with steamcmd when no game jar is
* configured or installed.</li> * configured or installed;</li>
* <li>{@code zomboidForgeSetup}: creates {@code .gitignore} and the entry point class when
* they are missing.</li>
* </ul> * </ul>
* *
* Uses the {@code zomboidForge { }} of {@code dev.overlord.zomboidforge} when the settings
* apply it.
*
* Java compiles for Java 25 (the game's runtime) unless the build sets another toolchain. * Java compiles for Java 25 (the game's runtime) unless the build sets another toolchain.
*/ */
public final class ZomboidForgeModPlugin implements Plugin<Project> public final class ZomboidForgeModPlugin implements Plugin<Project>
{ {
public static final String GROUP = "zomboidforge"; public static final String GROUP = "zomboidforge";
public static final String EXTENSION = "zomboidForge";
private static final String API = "dev.overlord.zomboidforge:api:"; private static final String API = "dev.overlord.zomboidforge:api:";
private static final String TOOLS = "dev.overlord.zomboidforge:mod-tools:"; private static final String TOOLS = "dev.overlord.zomboidforge:mod-tools:";
@@ -66,7 +72,7 @@ public final class ZomboidForgeModPlugin implements Plugin<Project>
String version = ZomboidForgeModPlugin.version(); String version = ZomboidForgeModPlugin.version();
ProjectLayout layout = project.getLayout(); ProjectLayout layout = project.getLayout();
DependencyHandler handler = project.getDependencies(); DependencyHandler handler = project.getDependencies();
ZomboidForgeExtension extension = project.getExtensions().create("zomboidForge", ZomboidForgeExtension.class); ZomboidForgeExtension extension = ZomboidForgeModPlugin.extension(project);
extension.getName().convention(extension.getId()); extension.getName().convention(extension.getId());
extension.getVersion().convention(project.provider(() -> project.getVersion().toString())); extension.getVersion().convention(project.provider(() -> project.getVersion().toString()));
@@ -247,6 +253,25 @@ public final class ZomboidForgeModPlugin implements Plugin<Project>
task.into(extension.getDeployDirectory().dir(id).orElse(layout.getBuildDirectory().dir("deploy-not-configured"))); task.into(extension.getDeployDirectory().dir(id).orElse(layout.getBuildDirectory().dir("deploy-not-configured")));
task.onlyIf("zomboidForge.deployDirectory is set", element -> extension.getDeployDirectory().isPresent()); task.onlyIf("zomboidForge.deployDirectory is set", element -> extension.getDeployDirectory().isPresent());
}); });
// Project setup.
TaskProvider<SetupMod> setup = project.getTasks().register("zomboidForgeSetup", SetupMod.class, task ->
{
task.setGroup(ZomboidForgeModPlugin.GROUP);
task.setDescription("Creates .gitignore and the entry point class when they are missing.");
task.getProjectDirectory().set(layout.getProjectDirectory());
task.getEntrypoint().set(extension.getEntrypoint());
});
project.getTasks().named(JavaPlugin.COMPILE_JAVA_TASK_NAME, task -> task.mustRunAfter(setup));
}
/** The {@code zomboidForge { }} of the settings plugin, else a new one. */
private static ZomboidForgeExtension extension(Project project)
{
ZomboidForgeExtension shared = project.getExtensions().findByType(ZomboidForgeExtension.class);
return shared != null ? shared : project.getExtensions().create(ZomboidForgeModPlugin.EXTENSION, ZomboidForgeExtension.class);
} }
/** The plugin's version, which is also the version of the API and mod tools it uses. */ /** The plugin's version, which is also the version of the API and mod tools it uses. */
@@ -0,0 +1,50 @@
package dev.overlord.zomboidforge.gradle;
import org.gradle.api.Plugin;
import org.gradle.api.initialization.Settings;
import org.gradle.api.provider.Provider;
/**
* The plugin {@code dev.overlord.zomboidforge} for {@code settings.gradle.kts}, which makes a
* mod project a single file:
*
* <pre>{@code
* plugins {
* id("dev.overlord.zomboidforge") version "0.6.0"
* }
*
* zomboidForge {
* id = "shop"
* entrypoint = "com.example.shop.ShopMod"
* }
* }</pre>
*
* Adds {@code zomboidForge { }} to the settings and names the root project after the mod id.
* The root project gets the ZomboidForge Maven registry and Maven Central as repositories, and
* {@code dev.overlord.zomboidforge.mod} with the same {@code zomboidForge { }}. The Gradle
* property {@code zomboidforge.repository} replaces the registry's URL.
*/
public final class ZomboidForgeSettingsPlugin implements Plugin<Settings>
{
static final String REPOSITORY = "https://git.security-command.org/api/packages/overlord/maven";
@Override
public void apply(Settings settings)
{
ZomboidForgeExtension extension = settings.getExtensions().create(ZomboidForgeModPlugin.EXTENSION, ZomboidForgeExtension.class);
Provider<String> repository = settings.getProviders().gradleProperty("zomboidforge.repository").orElse(ZomboidForgeSettingsPlugin.REPOSITORY);
settings.getGradle().settingsEvaluated(evaluated ->
{
if (extension.getId().isPresent()) evaluated.getRootProject().setName(extension.getId().get());
});
settings.getGradle().rootProject(project ->
{
project.getRepositories().maven(maven -> maven.setUrl(repository.get()));
project.getRepositories().mavenCentral();
project.getExtensions().add(ZomboidForgeExtension.class, ZomboidForgeModPlugin.EXTENSION, extension);
project.getPluginManager().apply(ZomboidForgeModPlugin.class);
});
}
}
@@ -0,0 +1,129 @@
package dev.overlord.zomboidforge.gradle;
import org.gradle.testkit.runner.BuildResult;
import org.gradle.testkit.runner.GradleRunner;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
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.jar.JarFile;
import java.util.jar.JarOutputStream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** Builds mod projects that consist of a settings.gradle.kts with dev.overlord.zomboidforge. */
class ZomboidForgeSettingsPluginTest
{
private static final String REPOSITORY = System.getProperty("zomboidforge.testRepository");
private static final String SETTINGS = """
plugins {
id("dev.overlord.zomboidforge")
}
zomboidForge {
id = "shop"
version = "1.0.0"
entrypoint = "com.example.shop.ShopMod"
}
""";
@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);
}
private GradleRunner runner(String... arguments)
{
List<String> all = new ArrayList<>(List.of(arguments));
all.add("-Pzomboidforge.repository=" + Path.of(ZomboidForgeSettingsPluginTest.REPOSITORY).toUri());
all.add("--stacktrace");
return GradleRunner.create().withProjectDir(this.project.toFile()).withPluginClasspath().withArguments(all).forwardOutput();
}
@Test
void buildsAProjectOfOneFile() throws IOException
{
this.write("settings.gradle.kts", ZomboidForgeSettingsPluginTest.SETTINGS);
BuildResult result = this.runner("zomboidForgeSetup", "build", "--configuration-cache").build();
assertTrue(result.getOutput().contains("Created '.gitignore'."), result.getOutput());
assertTrue(result.getOutput().contains("Mod 'shop' 1.0.0 passed the checks"), result.getOutput());
assertTrue(Files.readString(this.project.resolve(".gitignore")).contains("build/"));
assertTrue(Files.readString(this.project.resolve("src/main/java/com/example/shop/ShopMod.java")).contains("public final class ShopMod extends Mod"));
assertTrue(Files.isRegularFile(this.project.resolve("build/distributions/shop-1.0.0.zip")), "the root project is named after the mod id");
BuildResult again = this.runner("zomboidForgeSetup", "build", "--configuration-cache").build();
assertTrue(again.getOutput().contains("Configuration cache entry reused."), again.getOutput());
assertFalse(again.getOutput().contains("Created '"), "existing files stay");
}
@Test
void setupKeepsExistingFiles() throws IOException
{
this.write("settings.gradle.kts", ZomboidForgeSettingsPluginTest.SETTINGS);
this.write(".gitignore", "out/\n");
this.write("src/main/java/com/example/shop/ShopMod.java", "// own\n");
BuildResult result = this.runner("zomboidForgeSetup").build();
assertFalse(result.getOutput().contains("Created '"), result.getOutput());
assertEquals("out/\n", Files.readString(this.project.resolve(".gitignore")));
assertEquals("// own\n", Files.readString(this.project.resolve("src/main/java/com/example/shop/ShopMod.java")));
}
@Test
void setupCreatesAnEntryPointWithoutPackage() throws IOException
{
this.write("settings.gradle.kts", ZomboidForgeSettingsPluginTest.SETTINGS.replace("com.example.shop.ShopMod", "ShopMod"));
this.runner("zomboidForgeSetup", "compileJava").build();
String source = Files.readString(this.project.resolve("src/main/java/ShopMod.java"));
assertTrue(source.startsWith("import dev.overlord.zomboidforge.api.Mod;"), source);
}
@Test
void buildScriptSharesTheSettings() throws IOException
{
this.write("settings.gradle.kts", ZomboidForgeSettingsPluginTest.SETTINGS);
this.write("build.gradle.kts", """
zomboidForge {
name = "Shop"
}
dependencies {
implementation(files("libs/util.jar"))
}
""");
Files.createDirectories(this.project.resolve("libs"));
try (OutputStream file = Files.newOutputStream(this.project.resolve("libs/util.jar"))) { new JarOutputStream(file).close(); }
this.runner("zomboidForgeSetup", "modFolder", "-x", "checkMod").build();
assertTrue(Files.isRegularFile(this.project.resolve("build/mod/shop/lib/util.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("\"shop\""), toml);
assertTrue(toml.contains("\"Shop\""), toml);
}
}
}
@@ -0,0 +1,159 @@
package dev.overlord.zomboidforge.gradle;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
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.List;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** Runs zomboidforge.jsh with JShell against build/repo and the wrapper of the repository root. */
class ZomboidForgeUpdaterTest
{
private static final Path ROOT = Path.of(System.getProperty("zomboidforge.root"));
private static final Path REPOSITORY = Path.of(System.getProperty("zomboidforge.testRepository"));
private static final String VERSION = ZomboidForgeModPlugin.version();
@TempDir
Path directory;
private record Run(int exit, String output) {}
/** A project of one settings.gradle.kts in {@code project/}, declaring {@code version}. */
private Path project(String version) throws IOException
{
Path project = this.directory.resolve("project");
Files.createDirectories(project);
Files.writeString(project.resolve("settings.gradle.kts"), """
pluginManagement {
repositories { maven("%s") }
}
plugins {
id("dev.overlord.zomboidforge") version "%s"
}
zomboidForge {
id = "shop"
version = "1.0.0"
entrypoint = "com.example.shop.ShopMod"
}
""".formatted(ZomboidForgeUpdaterTest.REPOSITORY.toUri(), version));
Files.writeString(project.resolve("gradle.properties"), "zomboidforge.repository=" + ZomboidForgeUpdaterTest.REPOSITORY.toUri() + "\n");
return project;
}
/** {@code files/v<version>/} with the wrapper of the repository root, as a release tag has it. */
private Path files(String version) throws IOException
{
Path files = this.directory.resolve("files");
for (String path : List.of("gradlew", "gradlew.bat", "gradle/wrapper/gradle-wrapper.jar", "gradle/wrapper/gradle-wrapper.properties"))
{
Path target = files.resolve("v" + version).resolve(path);
Files.createDirectories(target.getParent());
Files.copy(ZomboidForgeUpdaterTest.ROOT.resolve(path), target);
}
return files;
}
private Run run(Path project, Path repository, Path files, String... properties) throws Exception
{
Path jshell = Path.of(System.getProperty("java.home"), "bin", "jshell");
List<String> command = new ArrayList<>(List.of(jshell.toString()));
command.add("-R-Dzomboidforge.repository=" + repository.toUri());
command.add("-R-Dzomboidforge.files=" + files.toUri());
for (String property : properties) command.add("-R-D" + property);
command.add("-");
Process process = new ProcessBuilder(command)
.directory(project.toFile())
.redirectErrorStream(true)
.redirectInput(ZomboidForgeUpdaterTest.ROOT.resolve("zomboidforge.jsh").toFile())
.start();
String output = new String(process.getInputStream().readAllBytes(), StandardCharsets.UTF_8);
assertTrue(process.waitFor(5, TimeUnit.MINUTES), output);
System.out.println(output);
return new Run(process.exitValue(), output);
}
@Test
void setsUpAndBuildsAProject() throws Exception
{
Path project = this.project("0.0.1");
Run run = this.run(project, ZomboidForgeUpdaterTest.REPOSITORY, this.files(ZomboidForgeUpdaterTest.VERSION), "zomboidforge.version=" + ZomboidForgeUpdaterTest.VERSION);
assertEquals(0, run.exit(), run.output());
assertTrue(run.output().contains("(was 0.0.1)"), run.output());
assertTrue(run.output().contains("Created 'src/main/java/com/example/shop/ShopMod.java'."), run.output());
assertTrue(Files.readString(project.resolve("settings.gradle.kts")).contains("version \"" + ZomboidForgeUpdaterTest.VERSION + "\""));
assertTrue(Files.isExecutable(project.resolve("gradlew")));
assertTrue(Files.isRegularFile(project.resolve("gradle/wrapper/gradle-wrapper.jar")));
assertTrue(Files.isRegularFile(project.resolve("build/distributions/shop-1.0.0.zip")));
}
@Test
void takesTheNewestVersionAndChangesNothingWhenADownloadFails() throws Exception
{
Path repository = this.directory.resolve("repository");
Path metadata = repository.resolve("dev/overlord/zomboidforge/dev.overlord.zomboidforge.gradle.plugin/maven-metadata.xml");
Files.createDirectories(metadata.getParent());
Files.writeString(metadata, "<metadata><versioning><release>9.9.0</release><versions><version>0.1.0</version><version>9.9.0</version></versions></versioning></metadata>");
Path project = this.project("0.1.0");
String settings = Files.readString(project.resolve("settings.gradle.kts"));
Run run = this.run(project, repository, this.directory.resolve("files"));
assertEquals(1, run.exit(), run.output());
assertTrue(run.output().contains("v9.9.0/gradlew"), run.output());
assertEquals(settings, Files.readString(project.resolve("settings.gradle.kts")));
assertTrue(Files.notExists(project.resolve("gradlew")));
}
@Test
void failsForAVersionThatIsNotPublished() throws Exception
{
Path project = this.project("0.0.1");
Run run = this.run(project, ZomboidForgeUpdaterTest.REPOSITORY, this.directory.resolve("files"), "zomboidforge.version=9.9.9");
assertEquals(1, run.exit(), run.output());
assertTrue(run.output().contains("'9.9.9'"), run.output());
}
@Test
void failsWithoutThePluginInTheSettings() throws Exception
{
Path project = this.project("0.0.1");
Files.writeString(project.resolve("settings.gradle.kts"), "rootProject.name = \"shop\"\n");
Run run = this.run(project, ZomboidForgeUpdaterTest.REPOSITORY, this.directory.resolve("files"));
assertEquals(1, run.exit(), run.output());
assertTrue(run.output().contains("dev.overlord.zomboidforge"), run.output());
}
@Test
void failsWithoutSettings() throws Exception
{
Path project = this.directory.resolve("empty");
Files.createDirectories(project);
Run run = this.run(project, ZomboidForgeUpdaterTest.REPOSITORY, this.directory.resolve("files"));
assertEquals(1, run.exit(), run.output());
assertTrue(run.output().contains("settings.gradle.kts"), run.output());
}
}
+167
View File
@@ -0,0 +1,167 @@
// Sets up or updates the ZomboidForge mod project in the current directory, whose
// settings.gradle.kts applies the plugin dev.overlord.zomboidforge. Runs with JShell (JDK 25),
// the same way on Linux, macOS, and Windows:
//
// curl -fsSL https://git.security-command.org/Overlord/ZomboidForge/raw/branch/master/zomboidforge.jsh | jshell -
// curl -fsSL https://git.security-command.org/Overlord/ZomboidForge/raw/branch/master/zomboidforge.jsh | jshell -R-Dzomboidforge.version=0.7.0 -
//
// Steps: sets the plugin version in settings.gradle.kts, writes the Gradle wrapper of that
// ZomboidForge version, then runs "gradlew zomboidForgeSetup build".
//
// System properties (-R-D<name>=<value>):
// zomboidforge.version the version to set; default: the newest published one
// zomboidforge.repository Maven repository with the plugin; default: the ZomboidForge registry
// zomboidforge.files base URL of the wrapper files, as <base>/v<version>/<path>;
// default: the release tags of the ZomboidForge repository
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class ZomboidForgeUpdater
{
static final String WEBSITE = "https://git.security-command.org/Overlord/ZomboidForge";
static final String REPOSITORY = ZomboidForgeUpdater.property("zomboidforge.repository", "https://git.security-command.org/api/packages/overlord/maven");
static final String FILES = ZomboidForgeUpdater.property("zomboidforge.files", ZomboidForgeUpdater.WEBSITE + "/raw/tag");
static final String METADATA = "/dev/overlord/zomboidforge/dev.overlord.zomboidforge.gradle.plugin/maven-metadata.xml";
static final Path SETTINGS = Path.of("settings.gradle.kts");
static final Pattern PLUGIN = Pattern.compile("id\\(\"dev\\.overlord\\.zomboidforge\"\\)\\s*version\\s*\"([^\"]*)\"");
static final Pattern VERSION = Pattern.compile("<version>([^<]+)</version>");
static final Pattern RELEASE = Pattern.compile("<release>([^<]+)</release>");
static final List<String> WRAPPER = List.of("gradlew", "gradlew.bat", "gradle/wrapper/gradle-wrapper.jar", "gradle/wrapper/gradle-wrapper.properties");
static final int TIMEOUT = 30_000;
static int run()
{
try
{
ZomboidForgeUpdater.update();
return 0;
}
catch (IOException e)
{
System.err.println("[zomboidforge] " + e.getMessage());
return 1;
}
catch (Exception e)
{
System.err.println("[zomboidforge] Unable to update: " + e);
return 1;
}
}
static void update() throws Exception
{
if (!Files.isRegularFile(ZomboidForgeUpdater.SETTINGS)) throw new IOException("Unable to update: no 'settings.gradle.kts' in '" + Path.of("").toAbsolutePath() + "'.");
String settings = Files.readString(ZomboidForgeUpdater.SETTINGS);
Matcher plugin = ZomboidForgeUpdater.PLUGIN.matcher(settings);
if (!plugin.find()) throw new IOException("Unable to update: 'settings.gradle.kts' has no 'id(\"dev.overlord.zomboidforge\") version \"...\"'.");
String current = plugin.group(1);
String target = ZomboidForgeUpdater.target();
// Every download finishes before the first file changes.
Map<String, byte[]> wrapper = new LinkedHashMap<>();
for (String path : ZomboidForgeUpdater.WRAPPER) wrapper.put(path, ZomboidForgeUpdater.download(ZomboidForgeUpdater.FILES + "/v" + target + "/" + path));
if (!current.equals(target)) Files.writeString(ZomboidForgeUpdater.SETTINGS, settings.substring(0, plugin.start(1)) + target + settings.substring(plugin.end(1)));
for (Map.Entry<String, byte[]> file : wrapper.entrySet())
{
Path path = Path.of(file.getKey());
if (path.getParent() != null) Files.createDirectories(path.getParent());
Files.write(path, file.getValue());
}
//noinspection ResultOfMethodCallIgnored
Path.of("gradlew").toFile().setExecutable(true);
System.out.println("[zomboidforge] ZomboidForge " + target + (current.equals(target) ? "" : " (was " + current + ")") + ".");
System.out.println("[zomboidforge] Documentation: " + ZomboidForgeUpdater.WEBSITE + "/src/tag/v" + target + "/MOD_DEVELOPMENT.md");
if (!current.equals(target)) System.out.println("[zomboidforge] Changes: " + ZomboidForgeUpdater.WEBSITE + "/compare/v" + current + "...v" + target);
int exit = ZomboidForgeUpdater.gradle("zomboidForgeSetup", "build");
if (exit != 0) throw new IOException("Unable to build the mod: 'gradlew zomboidForgeSetup build' exited with " + exit + ".");
}
/** The version from {@code zomboidforge.version}, else the newest one; either has to be published. */
static String target() throws IOException
{
String metadata = new String(ZomboidForgeUpdater.download(ZomboidForgeUpdater.REPOSITORY + ZomboidForgeUpdater.METADATA), StandardCharsets.UTF_8);
List<String> published = new ArrayList<>();
Matcher versions = ZomboidForgeUpdater.VERSION.matcher(metadata);
Matcher release = ZomboidForgeUpdater.RELEASE.matcher(metadata);
while (versions.find()) published.add(versions.group(1));
if (published.isEmpty()) throw new IOException("Unable to update: no published versions in '" + ZomboidForgeUpdater.REPOSITORY + ZomboidForgeUpdater.METADATA + "'.");
String newest = release.find() ? release.group(1) : published.getLast();
String target = ZomboidForgeUpdater.property("zomboidforge.version", newest);
if (!published.contains(target)) throw new IOException("Unable to update: version '" + target + "' is not published; published: " + published + ".");
return target;
}
static byte[] download(String url) throws IOException
{
try
{
URLConnection connection = URI.create(url).toURL().openConnection();
connection.setConnectTimeout(ZomboidForgeUpdater.TIMEOUT);
connection.setReadTimeout(ZomboidForgeUpdater.TIMEOUT);
try (InputStream in = connection.getInputStream()) { return in.readAllBytes(); }
}
catch (FileNotFoundException e)
{
throw new IOException("Unable to download '" + url + "': not found.", e);
}
catch (IOException e)
{
throw new IOException("Unable to download '" + url + "': " + e, e);
}
}
/** Runs the wrapper in the current directory and copies its output; JShell drops inherited output. */
static int gradle(String... tasks) throws IOException, InterruptedException
{
boolean windows = System.getProperty("os.name").startsWith("Windows");
List<String> command = new ArrayList<>();
command.add(Path.of(windows ? "gradlew.bat" : "gradlew").toAbsolutePath().toString());
command.addAll(List.of(tasks));
Process process = new ProcessBuilder(command).redirectErrorStream(true).start();
process.getOutputStream().close();
try (InputStream out = process.getInputStream()) { out.transferTo(System.out); }
return process.waitFor();
}
static String property(String name, String fallback)
{
String value = System.getProperty(name, "").strip();
return value.isEmpty() ? fallback : value.replaceAll("/+$", "");
}
}
int status = ZomboidForgeUpdater.run();
/exit status