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
+1974
-28
No files matched your search
@@ -9,6 +9,8 @@
|
|||||||
!compat/
|
!compat/
|
||||||
!agent/
|
!agent/
|
||||||
!patcher/
|
!patcher/
|
||||||
|
!mod-tools/
|
||||||
|
!gradle-plugin/
|
||||||
!docker/
|
!docker/
|
||||||
**/build/
|
**/build/
|
||||||
**/.gradle/
|
**/.gradle/
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
# Publishes the mod API, the mod tools, and the Gradle plugin to the Gitea Maven registry
|
||||||
|
# (https://git.security-command.org/api/packages/overlord/maven) for every release tag.
|
||||||
|
# Pre-release tags (containing "-") are tested but not published (see ci/publish.sh).
|
||||||
|
# Requires the repository secrets REGISTRY_USER and REGISTRY_TOKEN (a token with package
|
||||||
|
# write access), the same as the image release.
|
||||||
|
name: publish
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
tags:
|
||||||
|
- "v*"
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
maven:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
# publish.sh derives the version from the newest v* tag
|
||||||
|
fetch-depth: 0
|
||||||
|
|
||||||
|
- uses: actions/setup-java@v4
|
||||||
|
with:
|
||||||
|
distribution: temurin
|
||||||
|
java-version: "25"
|
||||||
|
|
||||||
|
- name: Test and publish
|
||||||
|
env:
|
||||||
|
ORG_GRADLE_PROJECT_giteaUsername: ${{ secrets.REGISTRY_USER }}
|
||||||
|
ORG_GRADLE_PROJECT_giteaPassword: ${{ secrets.REGISTRY_TOKEN }}
|
||||||
|
PUBLISH: "true"
|
||||||
|
run: ci/publish.sh
|
||||||
+3
-1
@@ -51,6 +51,8 @@ COPY core core
|
|||||||
COPY compat compat
|
COPY compat compat
|
||||||
COPY agent agent
|
COPY agent agent
|
||||||
COPY patcher patcher
|
COPY patcher patcher
|
||||||
|
COPY mod-tools mod-tools
|
||||||
|
COPY gradle-plugin gradle-plugin
|
||||||
COPY --from=server /server/java/projectzomboid.jar /pz/projectzomboid.jar
|
COPY --from=server /server/java/projectzomboid.jar /pz/projectzomboid.jar
|
||||||
|
|
||||||
# An empty PZ_VERSION keeps pz.version from gradle.properties. FORGE_VERSION always has a
|
# An empty PZ_VERSION keeps pz.version from gradle.properties. FORGE_VERSION always has a
|
||||||
@@ -63,7 +65,7 @@ RUN ./gradlew --no-daemon \
|
|||||||
${PZ_VERSION:+-Ppz.version=${PZ_VERSION}} \
|
${PZ_VERSION:+-Ppz.version=${PZ_VERSION}} \
|
||||||
${FORGE_VERSION:+-Pversion=${FORGE_VERSION}} \
|
${FORGE_VERSION:+-Pversion=${FORGE_VERSION}} \
|
||||||
${DISABLED_PATCHES:+-Pzf.disabledPatches=${DISABLED_PATCHES}} \
|
${DISABLED_PATCHES:+-Pzf.disabledPatches=${DISABLED_PATCHES}} \
|
||||||
build :patcher:patchServerJar
|
build -x :gradle-plugin:test :patcher:patchServerJar
|
||||||
|
|
||||||
# --- Stage 3: runtime ------------------------------------------------------------
|
# --- Stage 3: runtime ------------------------------------------------------------
|
||||||
FROM docker.io/library/debian:trixie-slim
|
FROM docker.io/library/debian:trixie-slim
|
||||||
|
|||||||
+109
-18
@@ -3,29 +3,119 @@
|
|||||||
How to write a server-side Java mod for ZomboidForge. Installing mods on a server is
|
How to write a server-side Java mod for ZomboidForge. Installing mods on a server is
|
||||||
described in the [README](README.md#mods).
|
described in the [README](README.md#mods).
|
||||||
|
|
||||||
## Building
|
## Project setup
|
||||||
|
|
||||||
A mod is a jar compiled against the `api` module (`./gradlew :api:jar`, then
|
A mod is a normal Gradle project with the ZomboidForge plugin. It needs JDK 25 (Project
|
||||||
`api/build/libs/`). A mod that also uses game classes compiles against
|
Zomboid's runtime); the plugin sets the Java toolchain to 25.
|
||||||
`projectzomboid.jar` and declares the game versions it supports.
|
|
||||||
|
|
||||||
## Descriptor
|
`settings.gradle.kts`:
|
||||||
|
|
||||||
`META-INF/zomboidforge/mod.toml` in the jar:
|
```kotlin
|
||||||
|
pluginManagement {
|
||||||
|
repositories {
|
||||||
|
maven("https://git.security-command.org/api/packages/overlord/maven")
|
||||||
|
gradlePluginPortal()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
```toml
|
dependencyResolutionManagement {
|
||||||
id = "shop" # lowercase, digits, single underscores; the folder name
|
repositories {
|
||||||
name = "Shop"
|
maven("https://git.security-command.org/api/packages/overlord/maven")
|
||||||
version = "1.2.0"
|
mavenCentral()
|
||||||
entrypoint = "com.example.shop.ShopMod"
|
}
|
||||||
api = "0.3" # ZomboidForge version the mod was built against
|
}
|
||||||
game = ["42.21"] # only when the mod uses game classes: "42", "42.21", "42.21.0"
|
|
||||||
|
|
||||||
[dependencies]
|
rootProject.name = "shop"
|
||||||
economy = "2.1" # mod id = minimum version; loaded first
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Default settings go into `META-INF/zomboidforge/config.toml` in the jar.
|
`build.gradle.kts`:
|
||||||
|
|
||||||
|
```kotlin
|
||||||
|
plugins {
|
||||||
|
id("dev.overlord.zomboidforge.mod") version "0.3.0" // the plugin's version is the API version
|
||||||
|
}
|
||||||
|
|
||||||
|
version = "1.2.0"
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
dependencies {
|
||||||
|
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
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
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`.
|
||||||
|
|
||||||
|
### `zomboidForge { }`
|
||||||
|
|
||||||
|
| Setting | Default | Meaning |
|
||||||
|
|--------------------------|------------------------------------------|-----------------------------------------------------------------------------------|
|
||||||
|
| `id` | (required) | lowercase letters, digits, single underscores; at most 32 characters |
|
||||||
|
| `entrypoint` | (required) | the class that extends `Mod` |
|
||||||
|
| `name` | the id | display name |
|
||||||
|
| `version` | the project version | the mod's version |
|
||||||
|
| `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"` |
|
||||||
|
| `dependsOn(id, version)` | none | another mod this one needs, with its minimum version |
|
||||||
|
| `previousIds(...)` | none | earlier ids of the mod; their storage moves to the current id |
|
||||||
|
| `gameJar` | see below | the `projectzomboid.jar` to compile and check against |
|
||||||
|
| `steamBranch` | `public` | Steam branch for the download: `public`, `unstable`, or a version such as `42.19` |
|
||||||
|
| `serverImage` | the ZomboidForge image, `latest` | image for `runServer` |
|
||||||
|
| `adminPassword` | `admin` | admin password of the `runServer` server |
|
||||||
|
| `dataVolume` | `zomboidforge-<id>` | volume for the `runServer` world and server config |
|
||||||
|
| `containerEngine` | podman or docker, whichever is installed | for `runServer` and the download |
|
||||||
|
| `deployDirectory` | none | a server's mods directory for `deployMod` |
|
||||||
|
|
||||||
|
The plugin generates `META-INF/zomboidforge/mod.toml` from these settings; a hand-written one
|
||||||
|
fails the build.
|
||||||
|
|
||||||
|
### The game jar
|
||||||
|
|
||||||
|
Mods that declare `game` versions compile against `projectzomboid.jar`, which cannot be
|
||||||
|
published. The plugin uses the first of:
|
||||||
|
|
||||||
|
1. `zomboidForge.gameJar`, or the Gradle property `zomboidforge.gameJar` (for example in
|
||||||
|
`~/.gradle/gradle.properties`);
|
||||||
|
2. a local Steam installation of the dedicated server or the game, in any Steam library;
|
||||||
|
3. a download of the dedicated server with steamcmd (`steamcmd` if installed, otherwise its
|
||||||
|
container image with podman or docker), once per Steam branch, into the Gradle user home.
|
||||||
|
It is a few gigabytes.
|
||||||
|
|
||||||
|
The game jar has to be one of the declared `game` versions; the check below fails otherwise.
|
||||||
|
|
||||||
|
### Tasks
|
||||||
|
|
||||||
|
| Task | Does |
|
||||||
|
|----------------|---------------------------------------------------------------------------------------------|
|
||||||
|
| `build` | compiles, runs `checkMod`, and assembles the mod |
|
||||||
|
| `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` |
|
||||||
|
| `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 |
|
||||||
|
| `deployMod` | copies the mod folder into `deployDirectory` |
|
||||||
|
| `downloadGame` | installs the dedicated server for its game jar; runs only when needed |
|
||||||
|
|
||||||
|
### Working on ZomboidForge itself
|
||||||
|
|
||||||
|
To build a mod against a local ZomboidForge checkout instead of a published version, include it
|
||||||
|
in `settings.gradle.kts`; Gradle then builds the plugin, the API, and the mod tools from the
|
||||||
|
checkout:
|
||||||
|
|
||||||
|
```kotlin
|
||||||
|
pluginManagement {
|
||||||
|
includeBuild("../ZomboidForge")
|
||||||
|
}
|
||||||
|
|
||||||
|
includeBuild("../ZomboidForge")
|
||||||
|
```
|
||||||
|
|
||||||
## Entry point
|
## Entry point
|
||||||
|
|
||||||
@@ -170,8 +260,9 @@ Things to know:
|
|||||||
|
|
||||||
## Checks at startup
|
## Checks at startup
|
||||||
|
|
||||||
Before any mod code runs, ZomboidForge reads every class of the mod and its libraries. The
|
`checkMod` runs these checks when the mod is built, so a mod that would not load fails its
|
||||||
server does not start when a mod
|
build instead. On the server, before any mod code runs, ZomboidForge reads every class of the
|
||||||
|
mod and its libraries. The server does not start when a mod
|
||||||
|
|
||||||
1. uses game classes without declaring `game` versions in `mod.toml`,
|
1. uses game classes without declaring `game` versions in `mod.toml`,
|
||||||
2. uses a game class, field, or method that does not exist in the running version,
|
2. uses a game class, field, or method that does not exist in the running version,
|
||||||
|
|||||||
@@ -133,4 +133,8 @@ server jar, `lib/server/java/projectzomboid.jar` by default (override with `-Ppz
|
|||||||
```
|
```
|
||||||
|
|
||||||
Game-specific code lives in `compat/b<major>/`; `api` and `core` are version-independent.
|
Game-specific code lives in `compat/b<major>/`; `api` and `core` are version-independent.
|
||||||
`pz.version` in `gradle.properties` selects the targeted version.
|
`pz.version` in `gradle.properties` selects the targeted version. `mod-tools` (the build-time
|
||||||
|
mod checks) and `gradle-plugin` (the plugin for mod authors) are for mod builds, not the server.
|
||||||
|
|
||||||
|
Release tags publish `api`, `mod-tools`, and the Gradle plugin to the Gitea Maven registry
|
||||||
|
(`.gitea/workflows/publish.yml`, `ci/publish.sh`); tags with a `-` are only tested.
|
||||||
@@ -15,6 +15,8 @@ tasks.jar {
|
|||||||
archiveBaseName = "zomboidforge-agent"
|
archiveBaseName = "zomboidforge-agent"
|
||||||
manifest.attributes("Premain-Class" to "dev.overlord.zomboidforge.agent.ForgeAgent")
|
manifest.attributes("Premain-Class" to "dev.overlord.zomboidforge.agent.ForgeAgent")
|
||||||
// The agent jar is appended to the system class path and includes api, core and compat runtime.
|
// The agent jar is appended to the system class path and includes api, core and compat runtime.
|
||||||
|
// Mapping the classpath to zip trees loses its task dependencies; the input restores them.
|
||||||
|
inputs.files(configurations.runtimeClasspath)
|
||||||
from(configurations.runtimeClasspath.map { classpath -> classpath.map { zipTree(it) } })
|
from(configurations.runtimeClasspath.map { classpath -> classpath.map { zipTree(it) } })
|
||||||
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
|
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
|
||||||
}
|
}
|
||||||
@@ -1,7 +1,34 @@
|
|||||||
// API for custom Java mods. Version-independent: no references to game classes.
|
// API for custom Java mods. Version-independent: no references to game classes.
|
||||||
|
// Published as dev.overlord.zomboidforge:api; mods compile against it.
|
||||||
|
|
||||||
plugins {
|
plugins {
|
||||||
id("zomboidforge.java-conventions")
|
id("zomboidforge.java-conventions")
|
||||||
|
id("zomboidforge.publishing")
|
||||||
|
`java-library`
|
||||||
|
}
|
||||||
|
|
||||||
|
java {
|
||||||
|
withSourcesJar()
|
||||||
|
withJavadocJar()
|
||||||
|
}
|
||||||
|
|
||||||
|
tasks.javadoc {
|
||||||
|
// api.internal connects the API to the runtime and is not part of the documented API.
|
||||||
|
exclude("dev/overlord/zomboidforge/api/internal/**")
|
||||||
|
|
||||||
|
(options as StandardJavadocDocletOptions).apply {
|
||||||
|
// IntelliJ's @noinspection in package-info.java is not a Javadoc tag.
|
||||||
|
tags("noinspection:X")
|
||||||
|
addStringOption("Xdoclint:all,-missing", "-quiet")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
publishing {
|
||||||
|
publications {
|
||||||
|
create<MavenPublication>("api") {
|
||||||
|
from(components["java"])
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
dependencies {
|
dependencies {
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
// Publishing to the Maven registry of the ZomboidForge Gitea. Credentials come from the Gradle
|
||||||
|
// properties giteaUsername and giteaPassword (or ORG_GRADLE_PROJECT_giteaUsername and
|
||||||
|
// ORG_GRADLE_PROJECT_giteaPassword), and are only read when a publish task runs.
|
||||||
|
|
||||||
|
plugins {
|
||||||
|
`maven-publish`
|
||||||
|
}
|
||||||
|
|
||||||
|
publishing {
|
||||||
|
repositories {
|
||||||
|
maven {
|
||||||
|
name = "gitea"
|
||||||
|
url = uri("https://git.security-command.org/api/packages/overlord/maven")
|
||||||
|
credentials(PasswordCredentials::class)
|
||||||
|
}
|
||||||
|
|
||||||
|
// build/repo of the root project: for the Gradle plugin's functional tests.
|
||||||
|
maven {
|
||||||
|
name = "build"
|
||||||
|
url = uri(layout.settingsDirectory.dir("build/repo"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Executable
+96
@@ -0,0 +1,96 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
#
|
||||||
|
# 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,
|
||||||
|
# in the version of the newest v* git tag reachable from HEAD, without the "v".
|
||||||
|
#
|
||||||
|
# A pre-release version (containing "-", e.g. 0.3.0-rc.1) is built and tested but never
|
||||||
|
# published. Without any v* tag nothing is published.
|
||||||
|
#
|
||||||
|
# Environment:
|
||||||
|
# ORG_GRADLE_PROJECT_giteaUsername Gitea user with package write access
|
||||||
|
# ORG_GRADLE_PROJECT_giteaPassword Token of that user
|
||||||
|
# PUBLISH true: publish after the tests. Default: false (test only)
|
||||||
|
|
||||||
|
set -o errexit
|
||||||
|
set -o nounset
|
||||||
|
set -o pipefail
|
||||||
|
|
||||||
|
REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||||
|
readonly REPO_ROOT
|
||||||
|
|
||||||
|
readonly REQUESTED_PUBLISH="${PUBLISH:-false}"
|
||||||
|
|
||||||
|
readonly MODULES=(
|
||||||
|
api
|
||||||
|
mod-tools
|
||||||
|
gradle-plugin
|
||||||
|
)
|
||||||
|
|
||||||
|
log() {
|
||||||
|
echo "[publish] $*" >&2
|
||||||
|
}
|
||||||
|
|
||||||
|
# Prints the newest v* tag reachable from HEAD without its "v", or nothing.
|
||||||
|
release_tag_version() {
|
||||||
|
local tag
|
||||||
|
|
||||||
|
if tag="$(git -C "${REPO_ROOT}" describe --tags --abbrev=0 --match 'v*' 2> /dev/null)"; then
|
||||||
|
echo "${tag#v}"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
# Gradle tasks for every module, e.g. ":api:check".
|
||||||
|
module_tasks() {
|
||||||
|
local task="$1"
|
||||||
|
local module
|
||||||
|
|
||||||
|
for module in "${MODULES[@]}"; do
|
||||||
|
echo ":${module}:${task}"
|
||||||
|
done
|
||||||
|
}
|
||||||
|
|
||||||
|
run_gradle() {
|
||||||
|
local version="$1"
|
||||||
|
shift
|
||||||
|
|
||||||
|
"${REPO_ROOT}/gradlew" \
|
||||||
|
--no-daemon \
|
||||||
|
--project-dir "${REPO_ROOT}" \
|
||||||
|
"-Pversion=${version}" \
|
||||||
|
"$@"
|
||||||
|
}
|
||||||
|
|
||||||
|
main() {
|
||||||
|
local version
|
||||||
|
local publish="${REQUESTED_PUBLISH}"
|
||||||
|
local check_tasks
|
||||||
|
local publish_tasks
|
||||||
|
|
||||||
|
version="$(release_tag_version)"
|
||||||
|
if [[ -z "${version}" ]]; then
|
||||||
|
log "No v* git tag found (shallow clone without tags?); nothing to publish."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
if [[ "${version}" == *-* ]]; then
|
||||||
|
publish=false
|
||||||
|
log "${version} is a pre-release version; nothing will be published."
|
||||||
|
fi
|
||||||
|
|
||||||
|
mapfile -t check_tasks < <(module_tasks check)
|
||||||
|
mapfile -t publish_tasks < <(module_tasks publishAllPublicationsToGiteaRepository)
|
||||||
|
|
||||||
|
log "Testing ZomboidForge ${version}: ${MODULES[*]}"
|
||||||
|
run_gradle "${version}" :core:check "${check_tasks[@]}"
|
||||||
|
|
||||||
|
if [[ "${publish}" != "true" ]]; then
|
||||||
|
log "Not publishing (PUBLISH=${REQUESTED_PUBLISH})."
|
||||||
|
return
|
||||||
|
fi
|
||||||
|
|
||||||
|
log "Publishing ZomboidForge ${version}"
|
||||||
|
run_gradle "${version}" "${publish_tasks[@]}"
|
||||||
|
log "Published ${MODULES[*]} ${version}"
|
||||||
|
}
|
||||||
|
|
||||||
|
main "$@"
|
||||||
@@ -22,11 +22,11 @@ public final class GameClasses implements AutoCloseable
|
|||||||
private static final String CLASS_SUFFIX = ".class";
|
private static final String CLASS_SUFFIX = ".class";
|
||||||
private static final Pattern VERSIONED = Pattern.compile("META-INF/versions/\\d+/(.+)");
|
private static final Pattern VERSIONED = Pattern.compile("META-INF/versions/\\d+/(.+)");
|
||||||
|
|
||||||
private final JarFile file;
|
private final @Nullable JarFile file;
|
||||||
private final Set<String> classes;
|
private final Set<String> classes;
|
||||||
private final Set<String> packages;
|
private final Set<String> packages;
|
||||||
|
|
||||||
private GameClasses(JarFile file, Set<String> classes, Set<String> packages)
|
private GameClasses(@Nullable JarFile file, Set<String> classes, Set<String> packages)
|
||||||
{
|
{
|
||||||
this.file = file;
|
this.file = file;
|
||||||
this.classes = Set.copyOf(classes);
|
this.classes = Set.copyOf(classes);
|
||||||
@@ -56,6 +56,9 @@ public final class GameClasses implements AutoCloseable
|
|||||||
return new GameClasses(file, classes, packages);
|
return new GameClasses(file, classes, packages);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** No game classes, for checking a mod that declares no {@code game} versions without a game jar. */
|
||||||
|
public static GameClasses none() { return new GameClasses(null, Set.of(), Set.of()); }
|
||||||
|
|
||||||
/** Whether the jar contains the class with this internal name, e.g. {@code zombie/core/Core}. */
|
/** Whether the jar contains the class with this internal name, e.g. {@code zombie/core/Core}. */
|
||||||
public boolean contains(String internalName) { return this.classes.contains(internalName); }
|
public boolean contains(String internalName) { return this.classes.contains(internalName); }
|
||||||
|
|
||||||
@@ -65,14 +68,21 @@ public final class GameClasses implements AutoCloseable
|
|||||||
/** The class file for the running Java version, or {@code null} when the jar has none. */
|
/** The class file for the running Java version, or {@code null} when the jar has none. */
|
||||||
byte @Nullable [] read(String internalName) throws IOException
|
byte @Nullable [] read(String internalName) throws IOException
|
||||||
{
|
{
|
||||||
JarEntry entry = this.file.getJarEntry(internalName + GameClasses.CLASS_SUFFIX);
|
JarFile file = this.file;
|
||||||
|
if (file == null) return null;
|
||||||
|
|
||||||
|
JarEntry entry = file.getJarEntry(internalName + GameClasses.CLASS_SUFFIX);
|
||||||
if (entry == null) return null;
|
if (entry == null) return null;
|
||||||
|
|
||||||
try (InputStream in = this.file.getInputStream(entry)) { return in.readAllBytes(); }
|
try (InputStream in = file.getInputStream(entry)) { return in.readAllBytes(); }
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void close() throws IOException { this.file.close(); }
|
public void close() throws IOException
|
||||||
|
{
|
||||||
|
JarFile file = this.file;
|
||||||
|
if (file != null) file.close();
|
||||||
|
}
|
||||||
|
|
||||||
static String packageOf(String internalName)
|
static String packageOf(String internalName)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -67,9 +67,10 @@ public final class ModVerifier
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* @param ordered mods in load order, as returned by {@link ModResolver#resolve}
|
* @param ordered mods in load order, as returned by {@link ModResolver#resolve}
|
||||||
|
* @param version the version of {@code game}, for messages; {@code null} with {@link GameClasses#none()}
|
||||||
* @throws ModLoadException listing every problem of every mod
|
* @throws ModLoadException listing every problem of every mod
|
||||||
*/
|
*/
|
||||||
public static void verify(List<ModDiscovery.Candidate> ordered, GameClasses game, GameVersion version) throws ModLoadException
|
public static void verify(List<ModDiscovery.Candidate> ordered, GameClasses game, @Nullable GameVersion version) throws ModLoadException
|
||||||
{
|
{
|
||||||
Hierarchy hierarchy = new Hierarchy(game);
|
Hierarchy hierarchy = new Hierarchy(game);
|
||||||
Map<String, Set<String>> ownByMod = new HashMap<>();
|
Map<String, Set<String>> ownByMod = new HashMap<>();
|
||||||
@@ -139,7 +140,7 @@ public final class ModVerifier
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!linkage.isEmpty())
|
if (!linkage.isEmpty())
|
||||||
problems.add("'" + id + "': uses " + ModVerifier.examples(linkage) + ", which " + (linkage.size() == 1 ? "does" : "do") + " not exist in Project Zomboid " + version + ".");
|
problems.add("'" + id + "': uses " + ModVerifier.examples(linkage) + ", which " + (linkage.size() == 1 ? "does" : "do") + " not exist in " + (version == null ? "the game jar" : "Project Zomboid " + version) + ".");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!problems.isEmpty()) throw new ModLoadException(problems);
|
if (!problems.isEmpty()) throw new ModLoadException(problems);
|
||||||
|
|||||||
@@ -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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
// Build-time checks for mods, run by the ZomboidForge Gradle plugin in a separate Java 25
|
||||||
|
// process. Published as one self-contained jar (dev.overlord.zomboidforge:mod-tools) without
|
||||||
|
// dependencies, so a mod's build only needs the ZomboidForge Maven repository.
|
||||||
|
|
||||||
|
plugins {
|
||||||
|
id("zomboidforge.java-conventions")
|
||||||
|
id("zomboidforge.publishing")
|
||||||
|
}
|
||||||
|
|
||||||
|
dependencies {
|
||||||
|
implementation(project(":api"))
|
||||||
|
implementation(project(":core"))
|
||||||
|
implementation(project(":patcher"))
|
||||||
|
implementation(libs.bundles.asm)
|
||||||
|
|
||||||
|
testImplementation(platform(libs.junit.bom))
|
||||||
|
testImplementation(libs.junit.jupiter)
|
||||||
|
testRuntimeOnly(libs.junit.platform.launcher)
|
||||||
|
}
|
||||||
|
|
||||||
|
val toolJar = tasks.register<Jar>("toolJar") {
|
||||||
|
description = "The mod tools with every runtime dependency, for publishing."
|
||||||
|
archiveBaseName = "mod-tools"
|
||||||
|
archiveClassifier = "all"
|
||||||
|
manifest.attributes("Main-Class" to "dev.overlord.zomboidforge.tools.ModCheck")
|
||||||
|
|
||||||
|
from(sourceSets.main.map { it.output })
|
||||||
|
// Mapping the classpath to zip trees loses its task dependencies; the input restores them.
|
||||||
|
inputs.files(configurations.runtimeClasspath)
|
||||||
|
from(configurations.runtimeClasspath.map { classpath -> classpath.map { zipTree(it) } })
|
||||||
|
exclude("META-INF/*.SF", "META-INF/*.DSA", "META-INF/*.RSA", "META-INF/versions/*/module-info.class", "module-info.class")
|
||||||
|
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
|
||||||
|
}
|
||||||
|
|
||||||
|
publishing {
|
||||||
|
publications {
|
||||||
|
create<MavenPublication>("modTools") {
|
||||||
|
artifactId = "mod-tools"
|
||||||
|
artifact(toolJar) { classifier = null }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,379 @@
|
|||||||
|
package dev.overlord.zomboidforge.tools;
|
||||||
|
|
||||||
|
import dev.overlord.zomboidforge.api.GameVersion;
|
||||||
|
import dev.overlord.zomboidforge.core.config.TomlTree;
|
||||||
|
import dev.overlord.zomboidforge.core.mods.GameClasses;
|
||||||
|
import dev.overlord.zomboidforge.core.mods.ModDescriptor;
|
||||||
|
import dev.overlord.zomboidforge.core.mods.ModDiscovery;
|
||||||
|
import dev.overlord.zomboidforge.core.mods.ModLoadException;
|
||||||
|
import dev.overlord.zomboidforge.core.mods.ModVerifier;
|
||||||
|
import dev.overlord.zomboidforge.core.mods.ModVersion;
|
||||||
|
import dev.overlord.zomboidforge.patcher.GameVersionReader;
|
||||||
|
|
||||||
|
import org.jetbrains.annotations.Nullable;
|
||||||
|
import org.objectweb.asm.ClassReader;
|
||||||
|
import org.objectweb.asm.Opcodes;
|
||||||
|
import org.objectweb.asm.tree.ClassNode;
|
||||||
|
import org.objectweb.asm.tree.MethodNode;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.jar.JarFile;
|
||||||
|
import java.util.zip.ZipEntry;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Checks a built mod jar the way the server does when it loads the mod, plus what only a
|
||||||
|
* build can check:
|
||||||
|
*
|
||||||
|
* <ol>
|
||||||
|
* <li>{@code mod.toml} and the default {@code config.toml} in the jar are valid;</li>
|
||||||
|
* <li>the entry point is in the jar, extends {@code Mod}, is not abstract, and has a public
|
||||||
|
* constructor without parameters;</li>
|
||||||
|
* <li>every mod jar the mod compiles against is declared in {@code dependencies} with a
|
||||||
|
* minimum version it satisfies;</li>
|
||||||
|
* <li>the game jar is one of the declared {@code game} versions;</li>
|
||||||
|
* <li>{@link ModVerifier}: game use requires {@code game} versions, every used game class
|
||||||
|
* and member exists in the game jar, no ZomboidForge internals.</li>
|
||||||
|
* </ol>
|
||||||
|
*
|
||||||
|
* <pre>
|
||||||
|
* java -jar mod-tools.jar --jar <mod.jar> [--game-jar <projectzomboid.jar>]
|
||||||
|
* [--library <jar>]... [--dependency <mod jar>]... [--report <file>]
|
||||||
|
* </pre>
|
||||||
|
*
|
||||||
|
* A mod that declares {@code game} versions needs {@code --game-jar}; without it, game classes
|
||||||
|
* count as unknown, which is enough for a mod that does not compile against the game.
|
||||||
|
*
|
||||||
|
* Exit code 0 when the mod passes (the report file is written then), 1 with every problem on
|
||||||
|
* standard error, 2 for invalid arguments.
|
||||||
|
*/
|
||||||
|
public final class ModCheck
|
||||||
|
{
|
||||||
|
private static final String MOD_CLASS = "dev/overlord/zomboidforge/api/Mod";
|
||||||
|
|
||||||
|
/** The command-line arguments. */
|
||||||
|
public record Arguments(Path jar, @Nullable Path gameJar, List<Path> libraries, List<Path> dependencies, @Nullable Path report)
|
||||||
|
{
|
||||||
|
public Arguments
|
||||||
|
{
|
||||||
|
libraries = List.copyOf(libraries);
|
||||||
|
dependencies = List.copyOf(dependencies);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static final Set<String> OPTIONS = Set.of("--jar", "--game-jar", "--report", "--library", "--dependency");
|
||||||
|
|
||||||
|
/** @throws IllegalArgumentException for unknown, missing, repeated, or incomplete options */
|
||||||
|
public static Arguments parse(String[] args)
|
||||||
|
{
|
||||||
|
Map<String, List<Path>> values = new HashMap<>();
|
||||||
|
|
||||||
|
for (int i = 0; i < args.length; i += 2)
|
||||||
|
{
|
||||||
|
if (!Arguments.OPTIONS.contains(args[i])) throw new IllegalArgumentException("Unknown option '" + args[i] + "'.");
|
||||||
|
if (i + 1 >= args.length) throw new IllegalArgumentException("'" + args[i] + "' needs a value.");
|
||||||
|
|
||||||
|
values.computeIfAbsent(args[i], option -> new ArrayList<>()).add(Path.of(args[i + 1]));
|
||||||
|
}
|
||||||
|
|
||||||
|
return new Arguments(
|
||||||
|
Arguments.single(values, "--jar"),
|
||||||
|
Arguments.optional(values, "--game-jar"),
|
||||||
|
values.getOrDefault("--library", List.of()),
|
||||||
|
values.getOrDefault("--dependency", List.of()),
|
||||||
|
Arguments.optional(values, "--report")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Path single(Map<String, List<Path>> values, String option)
|
||||||
|
{
|
||||||
|
List<Path> given = values.getOrDefault(option, List.of());
|
||||||
|
|
||||||
|
if (given.size() != 1) throw new IllegalArgumentException("'" + option + "' is required once.");
|
||||||
|
|
||||||
|
return given.getFirst();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static @Nullable Path optional(Map<String, List<Path>> values, String option)
|
||||||
|
{
|
||||||
|
List<Path> given = values.getOrDefault(option, List.of());
|
||||||
|
|
||||||
|
if (given.size() > 1) throw new IllegalArgumentException("'" + option + "' may be given once.");
|
||||||
|
|
||||||
|
return given.isEmpty() ? null : given.getFirst();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What a check found: the mod's descriptor (when readable), the game version, and every problem. */
|
||||||
|
public record Result(@Nullable ModDescriptor descriptor, @Nullable GameVersion gameVersion, List<String> problems)
|
||||||
|
{
|
||||||
|
public Result { problems = List.copyOf(problems); }
|
||||||
|
|
||||||
|
public boolean passed() { return this.problems.isEmpty(); }
|
||||||
|
}
|
||||||
|
|
||||||
|
private ModCheck() {}
|
||||||
|
|
||||||
|
public static void main(String[] args)
|
||||||
|
{
|
||||||
|
Arguments arguments;
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
arguments = Arguments.parse(args);
|
||||||
|
}
|
||||||
|
catch (IllegalArgumentException e)
|
||||||
|
{
|
||||||
|
System.err.println("[ZomboidForge] " + e.getMessage());
|
||||||
|
System.exit(2);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
Result result = ModCheck.check(arguments);
|
||||||
|
ModDescriptor descriptor = result.descriptor();
|
||||||
|
|
||||||
|
if (!result.passed() || descriptor == null)
|
||||||
|
{
|
||||||
|
System.err.println("[ZomboidForge] The mod in '" + arguments.jar().getFileName() + "' would not load:");
|
||||||
|
result.problems().forEach(problem -> System.err.println(" - " + problem));
|
||||||
|
System.exit(1);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
String against = result.gameVersion() == null ? " (no game jar: the mod declares no game versions)" : " against Project Zomboid " + result.gameVersion();
|
||||||
|
String summary = "Mod '" + descriptor.id() + "' " + descriptor.version() + " passed the checks" + against + ".";
|
||||||
|
System.out.println("[ZomboidForge] " + summary);
|
||||||
|
|
||||||
|
Path report = arguments.report();
|
||||||
|
if (report == null) return;
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Files.writeString(report, summary + System.lineSeparator());
|
||||||
|
}
|
||||||
|
catch (IOException e)
|
||||||
|
{
|
||||||
|
System.err.println("[ZomboidForge] Cannot write '" + report + "': " + e.getMessage());
|
||||||
|
System.exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Runs every check; never throws for problems of the mod. */
|
||||||
|
public static Result check(Arguments arguments)
|
||||||
|
{
|
||||||
|
List<String> problems = new ArrayList<>();
|
||||||
|
ModDescriptor descriptor = ModCheck.descriptor(arguments.jar(), problems);
|
||||||
|
|
||||||
|
if (descriptor == null) return new Result(null, null, problems);
|
||||||
|
|
||||||
|
ModCheck.checkDefaultConfig(arguments.jar(), problems);
|
||||||
|
ModCheck.checkEntrypoint(arguments.jar(), descriptor, problems);
|
||||||
|
|
||||||
|
List<ModDiscovery.Candidate> candidates = new ArrayList<>();
|
||||||
|
|
||||||
|
for (Path dependency : arguments.dependencies())
|
||||||
|
{
|
||||||
|
ModDescriptor declared = ModCheck.descriptor(dependency, problems);
|
||||||
|
if (declared == null) continue;
|
||||||
|
|
||||||
|
ModVersion minimum = descriptor.dependencies().get(declared.id());
|
||||||
|
|
||||||
|
if (minimum == null)
|
||||||
|
problems.add("The mod compiles against '" + declared.id() + "' (" + dependency.getFileName() + "), which 'mod.toml' does not list in 'dependencies'.");
|
||||||
|
else if (declared.version().compareTo(minimum) < 0)
|
||||||
|
problems.add("The mod compiles against '" + declared.id() + "' " + declared.version() + ", older than the declared minimum " + minimum + ".");
|
||||||
|
|
||||||
|
candidates.add(ModCheck.candidate(dependency, List.of(), declared));
|
||||||
|
}
|
||||||
|
|
||||||
|
candidates.add(ModCheck.candidate(arguments.jar(), arguments.libraries(), descriptor));
|
||||||
|
|
||||||
|
Path gameJar = arguments.gameJar();
|
||||||
|
|
||||||
|
if (gameJar == null)
|
||||||
|
{
|
||||||
|
if (!descriptor.game().isEmpty()) problems.add("The mod declares " + descriptor.game() + ", so the check needs '--game-jar'.");
|
||||||
|
|
||||||
|
ModCheck.verify(candidates, GameClasses.none(), null, problems);
|
||||||
|
return new Result(descriptor, null, problems);
|
||||||
|
}
|
||||||
|
|
||||||
|
GameVersion gameVersion = ModCheck.gameVersion(gameJar, problems);
|
||||||
|
if (gameVersion == null) return new Result(descriptor, null, problems);
|
||||||
|
|
||||||
|
if (!descriptor.game().isEmpty() && descriptor.game().stream().noneMatch(gameVersion::matches))
|
||||||
|
problems.add("The game jar '" + gameJar + "' is Project Zomboid " + gameVersion + ", but the mod declares " + descriptor.game() + "; the check needs a game jar of a declared version.");
|
||||||
|
|
||||||
|
try (GameClasses game = GameClasses.open(gameJar))
|
||||||
|
{
|
||||||
|
ModCheck.verify(candidates, game, gameVersion, problems);
|
||||||
|
}
|
||||||
|
catch (IOException e)
|
||||||
|
{
|
||||||
|
problems.add("Cannot read the game jar '" + gameJar + "': " + e.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
return new Result(descriptor, gameVersion, problems);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void verify(List<ModDiscovery.Candidate> candidates, GameClasses game, @Nullable GameVersion version, List<String> problems)
|
||||||
|
{
|
||||||
|
try { ModVerifier.verify(candidates, game, version); }
|
||||||
|
catch (ModLoadException e) { problems.addAll(e.problems()); }
|
||||||
|
}
|
||||||
|
|
||||||
|
private static ModDiscovery.Candidate candidate(Path jar, List<Path> libraries, ModDescriptor descriptor)
|
||||||
|
{
|
||||||
|
return new ModDiscovery.Candidate(jar.toAbsolutePath().getParent(), jar, libraries, descriptor, true, Map.of());
|
||||||
|
}
|
||||||
|
|
||||||
|
private static @Nullable ModDescriptor descriptor(Path jar, List<String> problems)
|
||||||
|
{
|
||||||
|
String toml = ModCheck.entry(jar, ModDescriptor.PATH, problems);
|
||||||
|
|
||||||
|
if (toml == null)
|
||||||
|
{
|
||||||
|
problems.add("'" + jar.getFileName() + "' contains no '" + ModDescriptor.PATH + "'.");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return ModDescriptor.parse(toml);
|
||||||
|
}
|
||||||
|
catch (ModLoadException e)
|
||||||
|
{
|
||||||
|
e.problems().forEach(problem -> problems.add("'" + jar.getFileName() + "': mod.toml: " + problem));
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void checkDefaultConfig(Path jar, List<String> problems)
|
||||||
|
{
|
||||||
|
String toml = ModCheck.entry(jar, ModDiscovery.DEFAULT_CONFIG, problems);
|
||||||
|
if (toml == null) return;
|
||||||
|
|
||||||
|
Map<String, Object> settings;
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
settings = TomlTree.parse(toml);
|
||||||
|
}
|
||||||
|
catch (IllegalArgumentException e)
|
||||||
|
{
|
||||||
|
problems.add("'" + ModDiscovery.DEFAULT_CONFIG + "': " + e.getMessage());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!(settings.get("forge") instanceof Map<?, ?> forge)) return;
|
||||||
|
|
||||||
|
for (Map.Entry<?, ?> entry : forge.entrySet())
|
||||||
|
{
|
||||||
|
if (!"enabled".equals(entry.getKey()))
|
||||||
|
problems.add("'" + ModDiscovery.DEFAULT_CONFIG + "': unknown key 'forge." + entry.getKey() + "'; [forge] only has 'enabled'.");
|
||||||
|
else if (!(entry.getValue() instanceof Boolean))
|
||||||
|
problems.add("'" + ModDiscovery.DEFAULT_CONFIG + "': 'forge.enabled' must be true or false.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The entry point and its superclasses inside the jar must lead to {@code Mod}. */
|
||||||
|
private static void checkEntrypoint(Path jar, ModDescriptor descriptor, List<String> problems)
|
||||||
|
{
|
||||||
|
String entrypoint = descriptor.entrypoint();
|
||||||
|
ClassNode type = ModCheck.classNode(jar, entrypoint.replace('.', '/'), problems);
|
||||||
|
|
||||||
|
if (type == null)
|
||||||
|
{
|
||||||
|
problems.add("The entry point '" + entrypoint + "' is not in '" + jar.getFileName() + "'.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ((type.access & (Opcodes.ACC_ABSTRACT | Opcodes.ACC_INTERFACE)) != 0) problems.add("The entry point '" + entrypoint + "' is abstract.");
|
||||||
|
|
||||||
|
boolean constructor = type.methods.stream().anyMatch(ModCheck::isPublicNoArgConstructor);
|
||||||
|
if (!constructor || (type.access & Opcodes.ACC_PUBLIC) == 0) problems.add("The entry point '" + entrypoint + "' needs to be public, with a public constructor without parameters.");
|
||||||
|
|
||||||
|
ClassNode current = type;
|
||||||
|
|
||||||
|
for (int depth = 0; depth < 32; depth++)
|
||||||
|
{
|
||||||
|
String superName = current.superName;
|
||||||
|
|
||||||
|
if (ModCheck.MOD_CLASS.equals(superName)) return;
|
||||||
|
if (superName == null) break;
|
||||||
|
|
||||||
|
ClassNode parent = ModCheck.classNode(jar, superName, problems);
|
||||||
|
if (parent == null) break;
|
||||||
|
|
||||||
|
current = parent;
|
||||||
|
}
|
||||||
|
|
||||||
|
problems.add("The entry point '" + entrypoint + "' does not extend 'dev.overlord.zomboidforge.api.Mod'.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean isPublicNoArgConstructor(MethodNode method)
|
||||||
|
{
|
||||||
|
return method.name.equals("<init>") && method.desc.equals("()V") && (method.access & Opcodes.ACC_PUBLIC) != 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static @Nullable GameVersion gameVersion(Path gameJar, List<String> problems)
|
||||||
|
{
|
||||||
|
try (JarFile file = new JarFile(gameJar.toFile()))
|
||||||
|
{
|
||||||
|
ZipEntry entry = file.getEntry(GameVersionReader.CORE_CLASS + ".class");
|
||||||
|
|
||||||
|
if (entry == null)
|
||||||
|
{
|
||||||
|
problems.add("'" + gameJar + "' is not a Project Zomboid jar: it has no '" + GameVersionReader.CORE_CLASS + "'.");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
try (InputStream in = file.getInputStream(entry)) { return GameVersionReader.read(in.readAllBytes()); }
|
||||||
|
}
|
||||||
|
catch (IOException | RuntimeException e)
|
||||||
|
{
|
||||||
|
problems.add("Cannot read the Project Zomboid version from '" + gameJar + "': " + e.getMessage());
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static @Nullable ClassNode classNode(Path jar, String internalName, List<String> problems)
|
||||||
|
{
|
||||||
|
byte[] bytes = ModCheck.bytes(jar, internalName + ".class", problems);
|
||||||
|
if (bytes == null) return null;
|
||||||
|
|
||||||
|
ClassNode node = new ClassNode();
|
||||||
|
new ClassReader(bytes).accept(node, ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES);
|
||||||
|
|
||||||
|
return node;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static @Nullable String entry(Path jar, String name, List<String> problems)
|
||||||
|
{
|
||||||
|
byte[] bytes = ModCheck.bytes(jar, name, problems);
|
||||||
|
return bytes == null ? null : new String(bytes, StandardCharsets.UTF_8);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte @Nullable [] bytes(Path jar, String name, List<String> problems)
|
||||||
|
{
|
||||||
|
try (JarFile file = new JarFile(jar.toFile()))
|
||||||
|
{
|
||||||
|
ZipEntry entry = file.getEntry(name);
|
||||||
|
if (entry == null) return null;
|
||||||
|
|
||||||
|
try (InputStream in = file.getInputStream(entry)) { return in.readAllBytes(); }
|
||||||
|
}
|
||||||
|
catch (IOException e)
|
||||||
|
{
|
||||||
|
problems.add("Cannot read '" + jar + "': " + e.getMessage());
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
/**
|
||||||
|
* Build-time checks for mods, run by the ZomboidForge Gradle plugin.
|
||||||
|
*
|
||||||
|
* @noinspection UnstableApiUsage, RedundantSuppression
|
||||||
|
*/
|
||||||
|
@NotNullByDefault
|
||||||
|
package dev.overlord.zomboidforge.tools;
|
||||||
|
|
||||||
|
import org.jetbrains.annotations.NotNullByDefault;
|
||||||
+1
-1
@@ -10,7 +10,7 @@ dependencyResolutionManagement {
|
|||||||
|
|
||||||
rootProject.name = "ZomboidForge"
|
rootProject.name = "ZomboidForge"
|
||||||
|
|
||||||
include("api", "core", "agent", "patcher")
|
include("api", "core", "agent", "patcher", "mod-tools", "gradle-plugin")
|
||||||
|
|
||||||
// Only the compat modules of the selected Project Zomboid Build are part of the build.
|
// Only the compat modules of the selected Project Zomboid Build are part of the build.
|
||||||
// Each of them compiles against that Build's server jar.
|
// Each of them compiles against that Build's server jar.
|
||||||
|
|||||||
Reference in new issue
Block a user