Compare commits
6
Commits
8484d6c20c
..
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ee4be1a5b6 | ||
|
|
0763730a24 | ||
|
|
389b5b19d7 | ||
|
|
1d657e2b9a | ||
|
|
322092729f | ||
|
|
e07e946a87 |
No files matched your search
@@ -1,6 +1,7 @@
|
|||||||
# Builds the mod for every v* tag and publishes it as a release with lua_mod_automator.zip
|
# Builds the mod for every v* tag and publishes it as a release with lua_mod_automator.zip
|
||||||
# attached, so .../releases/download/latest/lua_mod_automator.zip always serves the newest one.
|
# attached, so .../releases/download/latest/lua_mod_automator.zip always serves the newest one.
|
||||||
# Pre-release tags (containing "-") are built and tested but not released (see ci/release.sh).
|
# Pre-release tags (containing "-") and tags on commits that are not on master are built and
|
||||||
|
# tested but not released (see ci/release.sh).
|
||||||
# Uses the repository secret RELEASE_TOKEN (a token with "repository: Read and Write") when it
|
# Uses the repository secret RELEASE_TOKEN (a token with "repository: Read and Write") when it
|
||||||
# exists, else the job's automatic token.
|
# exists, else the job's automatic token.
|
||||||
name: release
|
name: release
|
||||||
@@ -16,7 +17,7 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
|
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
|
||||||
with:
|
with:
|
||||||
# release.sh reads the v* tag on HEAD
|
# release.sh reads the v* tag on HEAD and checks that HEAD is on origin/master
|
||||||
fetch-depth: 0
|
fetch-depth: 0
|
||||||
|
|
||||||
- uses: actions/setup-java@cf277c60eb25467037889841efdb72551f06f6c3 # v4.9.1
|
- uses: actions/setup-java@cf277c60eb25467037889841efdb72551f06f6c3 # v4.9.1
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ Players keep the official, unmodified client; the mod runs on the server only.
|
|||||||
|
|
||||||
## Requirements
|
## Requirements
|
||||||
|
|
||||||
- ZomboidForge 0.4.0 or newer, Project Zomboid Build 42 (dedicated server)
|
- ZomboidForge 0.6.0 or newer, Project Zomboid Build 42 (dedicated server)
|
||||||
- Steam mode (the default of the ZomboidForge image), which the Workshop download needs
|
- Steam mode (the default of the ZomboidForge image), which the Workshop download needs
|
||||||
- a **Public** Steam Workshop collection: unlisted, friends-only, and private collections are
|
- a **Public** Steam Workshop collection: unlisted, friends-only, and private collections are
|
||||||
invisible to Steam's Web API
|
invisible to Steam's Web API
|
||||||
@@ -45,10 +45,13 @@ replaces those values at every start anyway.
|
|||||||
|
|
||||||
For every item of the collection, Steam's Web API returns its title, tags, and description.
|
For every item of the collection, Steam's Web API returns its title, tags, and description.
|
||||||
|
|
||||||
- **Mod IDs** come from description lines such as `Mod ID: Foo` or `ModID = Foo; Bar`. An item
|
- **Mod IDs** come from description lines such as `Mod ID: Foo` or `ModID = Foo; Bar`. A Mod
|
||||||
without one stays in `WorkshopItems=` (so the server downloads it) but is left out of `Mods=`,
|
ID may contain spaces (`Mod ID: Nicks Moveable Workstations - Furniture Fix`); `Mods=` then
|
||||||
with a warning; `[items.<id>] mod_ids` supplies it. The same applies to items Steam returns no
|
lists it as written, with a warning until `[items.<id>] mod_ids` confirms or corrects it. An
|
||||||
details for (private, unlisted, or removed items inside the collection).
|
item without one stays in `WorkshopItems=` (so the server downloads it) but is left out of
|
||||||
|
`Mods=`, with a warning; `[items.<id>] mod_ids` supplies it. The same applies to
|
||||||
|
items Steam returns no details for (private, unlisted, or removed items inside the
|
||||||
|
collection).
|
||||||
- **Buckets** decide the load order: `map` (a `Map Folder:` line in the description),
|
- **Buckets** decide the load order: `map` (a `Map Folder:` line in the description),
|
||||||
`framework` (the Steam tag *Framework*), or `misc`. Buckets load in the order of
|
`framework` (the Steam tag *Framework*), or `misc`. Buckets load in the order of
|
||||||
`[order] buckets`, items within a bucket in collection order.
|
`[order] buckets`, items within a bucket in collection order.
|
||||||
@@ -63,7 +66,7 @@ Values go into the server's `.ini` (`[ini] write`), so `showoptions` and the fil
|
|||||||
|
|
||||||
The server always starts. The mod uses, in this order:
|
The server always starts. The mod uses, in this order:
|
||||||
|
|
||||||
1. the collection, resolved live from Steam;
|
1. the collection, resolved live from Steam (tried a second time after 2 seconds);
|
||||||
2. the last successful resolution of the same collection, cached in the world's
|
2. the last successful resolution of the same collection, cached in the world's
|
||||||
`zomboidforge.db`;
|
`zomboidforge.db`;
|
||||||
3. the values already in the `.ini`.
|
3. the values already in the `.ini`.
|
||||||
@@ -120,9 +123,9 @@ exclude = true # left out of Mods=, WorkshopItems=, a
|
|||||||
|
|
||||||
Problems that do not stop the mod are logged as warnings: `[items]` keys or `priority`
|
Problems that do not stop the mod are logged as warnings: `[items]` keys or `priority`
|
||||||
entries that match no item, two keys naming the same item (the workshop-id key wins field by
|
entries that match no item, two keys naming the same item (the workshop-id key wins field by
|
||||||
field), Mod IDs named by two items (`Mods=` lists them once), unknown keys. An item that lands
|
field), Mod IDs named by two items (`Mods=` lists them once), Mod IDs that differ only in case
|
||||||
in a bucket missing from `[order] buckets` is an error: the mod then falls back as if Steam
|
(`Mods=` lists both), unknown keys. An item that lands in a bucket missing from
|
||||||
could not be reached.
|
`[order] buckets` is an error: the mod then falls back as if Steam could not be reached.
|
||||||
|
|
||||||
## While the server runs
|
## While the server runs
|
||||||
|
|
||||||
@@ -131,8 +134,9 @@ change:
|
|||||||
|
|
||||||
- how the collection differs from what the server runs: items or Mod IDs added, removed, or in
|
- how the collection differs from what the server runs: items or Mod IDs added, removed, or in
|
||||||
another order, a different `Map=`;
|
another order, a different `Map=`;
|
||||||
- items that were updated on Steam after the server started. Clients that download the new
|
- items with a newer version on Steam than the one the server downloaded. Clients that
|
||||||
version may not be able to join until the server restarts and downloads it too.
|
download the new version may not be able to join until the server restarts and downloads it
|
||||||
|
too.
|
||||||
|
|
||||||
The mod never restarts the server; changes apply at the next start.
|
The mod never restarts the server; changes apply at the next start.
|
||||||
|
|
||||||
@@ -155,6 +159,9 @@ download (see ZomboidForge's mod development guide).
|
|||||||
```shell
|
```shell
|
||||||
./gradlew build # compiles, tests, checks the mod against the game, and packs build/distributions/
|
./gradlew build # compiles, tests, checks the mod against the game, and packs build/distributions/
|
||||||
./gradlew runServer # a ZomboidForge server in a container with the mod (default settings: idle)
|
./gradlew runServer # a ZomboidForge server in a container with the mod (default settings: idle)
|
||||||
|
|
||||||
|
# What a config.toml resolves to, the way the server does it at startup, without a server:
|
||||||
|
./gradlew -q resolveCollection --args=path/to/config.toml
|
||||||
```
|
```
|
||||||
|
|
||||||
`runServer` mounts the mod read-only, so it runs with the default settings, in which the mod
|
`runServer` mounts the mod read-only, so it runs with the default settings, in which the mod
|
||||||
@@ -162,9 +169,10 @@ is idle. To try it with a collection, copy `build/mod/lua_mod_automator/` into a
|
|||||||
directory (or set `zomboidForge.deployDirectory` and run `./gradlew deployMod`) and add a
|
directory (or set `zomboidForge.deployDirectory` and run `./gradlew deployMod`) and add a
|
||||||
`config.toml` there.
|
`config.toml` there.
|
||||||
|
|
||||||
Pushing a tag `v<version>` that matches `version` in `build.gradle.kts` builds the mod and
|
Pushing a tag `v<version>` that matches `version` in `settings.gradle.kts` builds the mod and
|
||||||
publishes it as a release (`.gitea/workflows/release.yml`, `ci/release.sh`). Tags containing
|
publishes it as a release (`.gitea/workflows/release.yml`, `ci/release.sh`). Tags containing
|
||||||
`-` (e.g. `v0.2.0-rc.1`) are built and tested but not released.
|
`-` (e.g. `v0.2.0-rc.1`) and tags on commits that are not on `master` are built and tested but
|
||||||
|
not released.
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
|
|||||||
+13
-12
@@ -1,15 +1,7 @@
|
|||||||
plugins {
|
// id, name, version, and entry point: settings.gradle.kts
|
||||||
id("dev.overlord.zomboidforge.mod") version "0.4.0" // the plugin's version is the ZomboidForge API version
|
|
||||||
}
|
|
||||||
|
|
||||||
version = "0.1.0"
|
|
||||||
|
|
||||||
zomboidForge {
|
zomboidForge {
|
||||||
id = "lua_mod_automator"
|
game("42") // ServerOptions, GameServer, SteamWorkshop, CommandBase
|
||||||
name = "LuaModAutomator"
|
serverImage = "git.security-command.org/overlord/zomboidforge:0.6.0-pz42.21"
|
||||||
entrypoint = "dev.overlord.luamodautomator.LuaModAutomatorMod"
|
|
||||||
game("42") // ServerOptions, GameServer, CommandBase
|
|
||||||
serverImage = "git.security-command.org/overlord/zomboidforge:0.4.0-pz42.21"
|
|
||||||
}
|
}
|
||||||
|
|
||||||
dependencies {
|
dependencies {
|
||||||
@@ -19,7 +11,7 @@ dependencies {
|
|||||||
testCompileOnly("org.jetbrains:annotations:26.0.2")
|
testCompileOnly("org.jetbrains:annotations:26.0.2")
|
||||||
|
|
||||||
// ZomboidForge's config.toml parser and binder, to bind the settings the way the server does.
|
// ZomboidForge's config.toml parser and binder, to bind the settings the way the server does.
|
||||||
testImplementation("dev.overlord.zomboidforge:mod-tools:0.4.0")
|
testImplementation("dev.overlord.zomboidforge:mod-tools:0.6.0")
|
||||||
|
|
||||||
testImplementation(platform("org.junit:junit-bom:6.1.3"))
|
testImplementation(platform("org.junit:junit-bom:6.1.3"))
|
||||||
testImplementation("org.junit.jupiter:junit-jupiter")
|
testImplementation("org.junit.jupiter:junit-jupiter")
|
||||||
@@ -39,3 +31,12 @@ tasks.withType<JavaCompile>().configureEach {
|
|||||||
tasks.test {
|
tasks.test {
|
||||||
useJUnitPlatform()
|
useJUnitPlatform()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Prints what the server would set for a config.toml: ./gradlew -q resolveCollection --args=<config.toml>
|
||||||
|
tasks.register<JavaExec>("resolveCollection") {
|
||||||
|
group = "zomboidforge"
|
||||||
|
description = "Resolves the collection of a config.toml like the server does at startup and prints Mods=, WorkshopItems=, and Map=."
|
||||||
|
classpath = sourceSets.test.get().runtimeClasspath
|
||||||
|
mainClass = "dev.overlord.luamodautomator.ResolveCollection"
|
||||||
|
workingDir = File(System.getProperty("user.dir"))
|
||||||
|
}
|
||||||
+23
-6
@@ -4,8 +4,9 @@
|
|||||||
# attached twice: as lua_mod_automator-<version>.zip, and as lua_mod_automator.zip, the stable
|
# attached twice: as lua_mod_automator-<version>.zip, and as lua_mod_automator.zip, the stable
|
||||||
# name behind <server>/<owner>/<repo>/releases/download/latest/lua_mod_automator.zip.
|
# name behind <server>/<owner>/<repo>/releases/download/latest/lua_mod_automator.zip.
|
||||||
#
|
#
|
||||||
# A pre-release tag (containing "-", e.g. v0.2.0-rc.1) is built and tested but not released.
|
# A pre-release tag (containing "-", e.g. v0.2.0-rc.1), or a tag on a commit that is not on
|
||||||
# The tag must match the version in build.gradle.kts.
|
# master, is built and tested but not released. The tag must match the version in
|
||||||
|
# settings.gradle.kts.
|
||||||
#
|
#
|
||||||
# Usage:
|
# Usage:
|
||||||
# ci/release.sh build downloads the game jar and builds the mod (tests and checkMod included)
|
# ci/release.sh build downloads the game jar and builds the mod (tests and checkMod included)
|
||||||
@@ -27,6 +28,7 @@ REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
|||||||
readonly REPO_ROOT
|
readonly REPO_ROOT
|
||||||
|
|
||||||
readonly MOD_ID="lua_mod_automator"
|
readonly MOD_ID="lua_mod_automator"
|
||||||
|
readonly RELEASE_BRANCH="master"
|
||||||
readonly WORK_DIR="${REPO_ROOT}/build/ci"
|
readonly WORK_DIR="${REPO_ROOT}/build/ci"
|
||||||
|
|
||||||
# DepotDownloader downloads single files of a depot; steamcmd only whole apps. Same release
|
# DepotDownloader downloads single files of a depot; steamcmd only whole apps. Same release
|
||||||
@@ -47,6 +49,11 @@ fail() {
|
|||||||
exit 1
|
exit 1
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# Whether HEAD is on the release branch, as fetched from origin.
|
||||||
|
on_release_branch() {
|
||||||
|
git -C "${REPO_ROOT}" merge-base --is-ancestor HEAD "origin/${RELEASE_BRANCH}" 2> /dev/null
|
||||||
|
}
|
||||||
|
|
||||||
# Prints the v* tag on HEAD, or nothing.
|
# Prints the v* tag on HEAD, or nothing.
|
||||||
release_tag() {
|
release_tag() {
|
||||||
git -C "${REPO_ROOT}" describe --tags --exact-match --match 'v*' 2> /dev/null || true
|
git -C "${REPO_ROOT}" describe --tags --exact-match --match 'v*' 2> /dev/null || true
|
||||||
@@ -56,8 +63,10 @@ run_gradle() {
|
|||||||
"${REPO_ROOT}/gradlew" --no-daemon --console=plain --project-dir "${REPO_ROOT}" "$@"
|
"${REPO_ROOT}/gradlew" --no-daemon --console=plain --project-dir "${REPO_ROOT}" "$@"
|
||||||
}
|
}
|
||||||
|
|
||||||
project_version() {
|
# Prints the mod's version: the `version = "..."` line of zomboidForge { } in settings.gradle.kts.
|
||||||
run_gradle --quiet properties --property version | sed --quiet 's/^version: //p'
|
# The ZomboidForge plugin does not set Gradle's project version.
|
||||||
|
mod_version() {
|
||||||
|
sed --quiet 's/^[[:space:]]*version[[:space:]]*=[[:space:]]*"\([^"]*\)".*/\1/p' "${REPO_ROOT}/settings.gradle.kts"
|
||||||
}
|
}
|
||||||
|
|
||||||
# Downloads java/projectzomboid.jar of the dedicated server and prints its path.
|
# Downloads java/projectzomboid.jar of the dedicated server and prints its path.
|
||||||
@@ -87,9 +96,12 @@ build() {
|
|||||||
local project
|
local project
|
||||||
local game_jar="${GAME_JAR:-}"
|
local game_jar="${GAME_JAR:-}"
|
||||||
|
|
||||||
project="$(project_version)"
|
project="$(mod_version)"
|
||||||
|
if [[ -z "${project}" ]]; then
|
||||||
|
fail "No version line in settings.gradle.kts."
|
||||||
|
fi
|
||||||
if [[ "${project}" != "${version}" ]]; then
|
if [[ "${project}" != "${version}" ]]; then
|
||||||
fail "The tag '${tag}' does not match the version '${project}' in build.gradle.kts."
|
fail "The tag '${tag}' does not match the version '${project}' in settings.gradle.kts."
|
||||||
fi
|
fi
|
||||||
|
|
||||||
if [[ -z "${game_jar}" ]]; then
|
if [[ -z "${game_jar}" ]]; then
|
||||||
@@ -174,6 +186,11 @@ publish() {
|
|||||||
return
|
return
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
if ! on_release_branch; then
|
||||||
|
log "${tag} is not on ${RELEASE_BRANCH}; nothing is released."
|
||||||
|
return
|
||||||
|
fi
|
||||||
|
|
||||||
: "${GITEA_TOKEN:?GITEA_TOKEN is not set}"
|
: "${GITEA_TOKEN:?GITEA_TOKEN is not set}"
|
||||||
: "${GITHUB_API_URL:?GITHUB_API_URL is not set}"
|
: "${GITHUB_API_URL:?GITHUB_API_URL is not set}"
|
||||||
: "${GITHUB_REPOSITORY:?GITHUB_REPOSITORY is not set}"
|
: "${GITHUB_REPOSITORY:?GITHUB_REPOSITORY is not set}"
|
||||||
|
|||||||
+9
-10
@@ -1,15 +1,14 @@
|
|||||||
pluginManagement {
|
pluginManagement {
|
||||||
repositories {
|
repositories { maven("https://git.security-command.org/api/packages/overlord/maven") }
|
||||||
maven("https://git.security-command.org/api/packages/overlord/maven")
|
|
||||||
gradlePluginPortal()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
dependencyResolutionManagement {
|
plugins {
|
||||||
repositories {
|
id("dev.overlord.zomboidforge") version "0.6.0" // the plugin's version is the ZomboidForge API version
|
||||||
maven("https://git.security-command.org/api/packages/overlord/maven")
|
|
||||||
mavenCentral()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
rootProject.name = "LuaModAutomator"
|
zomboidForge {
|
||||||
|
id = "lua_mod_automator"
|
||||||
|
name = "LuaModAutomator"
|
||||||
|
version = "0.2.0"
|
||||||
|
entrypoint = "dev.overlord.luamodautomator.LuaModAutomatorMod"
|
||||||
|
}
|
||||||
@@ -1,5 +1,7 @@
|
|||||||
package dev.overlord.luamodautomator;
|
package dev.overlord.luamodautomator;
|
||||||
|
|
||||||
|
import dev.overlord.zomboidforge.api.annotations.RegisterCommand;
|
||||||
|
|
||||||
import org.jetbrains.annotations.Nullable;
|
import org.jetbrains.annotations.Nullable;
|
||||||
|
|
||||||
import zombie.characters.Capability;
|
import zombie.characters.Capability;
|
||||||
@@ -15,7 +17,9 @@ import zombie.core.raknet.UdpConnection;
|
|||||||
* {@code /collection}: where the running mod list comes from and the result of the last drift
|
* {@code /collection}: where the running mod list comes from and the result of the last drift
|
||||||
* check. {@code /collection check} starts a drift check on the mod thread. Works in the chat,
|
* check. {@code /collection check} starts a drift check on the mod thread. Works in the chat,
|
||||||
* the server console, and RCON; needs the capability of vanilla's {@code checkModsNeedUpdate}.
|
* the server console, and RCON; needs the capability of vanilla's {@code checkModsNeedUpdate}.
|
||||||
|
* ZomboidForge registers it before {@link LuaModAutomatorMod#onLoad()}.
|
||||||
*/
|
*/
|
||||||
|
@RegisterCommand
|
||||||
@CommandName(name = "collection")
|
@CommandName(name = "collection")
|
||||||
@CommandArgs(optional = "(\\S+)")
|
@CommandArgs(optional = "(\\S+)")
|
||||||
@CommandHelp(helpText = "collection [check]: shows where the mod list comes from and the last drift check; 'check' starts a drift check", shouldTranslated = false)
|
@CommandHelp(helpText = "collection [check]: shows where the mod list comes from and the last drift check; 'check' starts a drift check", shouldTranslated = false)
|
||||||
|
|||||||
@@ -66,6 +66,16 @@ final class CollectionResolver
|
|||||||
warnings.add("Steam returns no details for " + item.id() + " (private, unlisted, or removed); it stays in WorkshopItems= but not in Mods=. Set [items." + item.id() + "] mod_ids to load it.");
|
warnings.add("Steam returns no details for " + item.id() + " (private, unlisted, or removed); it stays in WorkshopItems= but not in Mods=. Set [items." + item.id() + "] mod_ids to load it.");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Mod IDs may contain spaces, but "Mod ID: Foo Bar" may also mean two of them.
|
||||||
|
if (override.modIds().isEmpty())
|
||||||
|
{
|
||||||
|
for (String modId : result.modIds())
|
||||||
|
{
|
||||||
|
if (modId.chars().anyMatch(Character::isWhitespace))
|
||||||
|
warnings.add("'" + result.title() + "' (" + item.id() + ") names the Mod ID '" + modId + "', which contains spaces; Mods= lists it as written. Set [items." + item.id() + "] mod_ids to confirm or correct it.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (item.map() && item.mapFolders().isEmpty())
|
if (item.map() && item.mapFolders().isEmpty())
|
||||||
warnings.add("'" + result.title() + "' (" + item.id() + ") has a Map Folder line without a folder name; it adds nothing to Map=.");
|
warnings.add("'" + result.title() + "' (" + item.id() + ") has a Map Folder line without a folder name; it adds nothing to Map=.");
|
||||||
|
|
||||||
@@ -225,27 +235,43 @@ final class CollectionResolver
|
|||||||
|
|
||||||
pinned.sort(Comparator.comparingInt(id -> overrides.get(id).position().orElseThrow()));
|
pinned.sort(Comparator.comparingInt(id -> overrides.get(id).position().orElseThrow()));
|
||||||
|
|
||||||
|
// All pinned items out first: removing one later would shift those placed before it.
|
||||||
|
ordered.removeAll(pinned);
|
||||||
|
|
||||||
for (String id : pinned)
|
for (String id : pinned)
|
||||||
{
|
{
|
||||||
ordered.remove(id);
|
|
||||||
ordered.add(Math.clamp(overrides.get(id).position().orElseThrow() - 1, 0, ordered.size()), id);
|
ordered.add(Math.clamp(overrides.get(id).position().orElseThrow() - 1, 0, ordered.size()), id);
|
||||||
}
|
}
|
||||||
|
|
||||||
return ordered.stream().map(byId::get).toList();
|
return ordered.stream().map(byId::get).toList();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Warns about Mod IDs named by two items, which {@code Mods=} lists once, and about Mod IDs
|
||||||
|
* that differ only in case, which it lists as written, since references ignore case but
|
||||||
|
* Project Zomboid may not.
|
||||||
|
*/
|
||||||
private static void duplicateModIds(List<Resolution.Item> items, List<String> warnings)
|
private static void duplicateModIds(List<Resolution.Item> items, List<String> warnings)
|
||||||
{
|
{
|
||||||
Map<String, Resolution.Item> first = new HashMap<>();
|
Map<String, Resolution.Item> first = new HashMap<>();
|
||||||
|
Map<String, String> spellings = new HashMap<>();
|
||||||
|
|
||||||
for (Resolution.Item item : items)
|
for (Resolution.Item item : items)
|
||||||
{
|
{
|
||||||
for (String modId : item.modIds())
|
for (String modId : item.modIds())
|
||||||
{
|
{
|
||||||
Resolution.Item other = first.putIfAbsent(modId, item);
|
Resolution.Item other = first.putIfAbsent(modId, item);
|
||||||
|
String spelling = spellings.putIfAbsent(modId.toLowerCase(Locale.ROOT), modId);
|
||||||
|
|
||||||
if (other != null && other != item)
|
if (other != null && other != item)
|
||||||
|
{
|
||||||
warnings.add("Mod ID '" + modId + "' is named by '" + other.title() + "' (" + other.id() + ") and '" + item.title() + "' (" + item.id() + "); Mods= lists it once.");
|
warnings.add("Mod ID '" + modId + "' is named by '" + other.title() + "' (" + other.id() + ") and '" + item.title() + "' (" + item.id() + "); Mods= lists it once.");
|
||||||
|
}
|
||||||
|
else if (spelling != null && !spelling.equals(modId))
|
||||||
|
{
|
||||||
|
Resolution.Item owner = first.get(spelling);
|
||||||
|
warnings.add("Mod IDs '" + spelling + "' of '" + owner.title() + "' (" + owner.id() + ") and '" + modId + "' of '" + item.title() + "' (" + item.id() + ") differ only in case; Mods= lists both.");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,14 +18,23 @@ final class DescriptionParser
|
|||||||
private static final Pattern MOD_IDS = Pattern.compile("(?im)^\\s*Mod\\s*IDs?\\h*[:=]\\h*(.+)$");
|
private static final Pattern MOD_IDS = Pattern.compile("(?im)^\\s*Mod\\s*IDs?\\h*[:=]\\h*(.+)$");
|
||||||
private static final Pattern MAP_LINE = Pattern.compile("(?im)^\\s*Map\\s*Folder\\h*[:=]");
|
private static final Pattern MAP_LINE = Pattern.compile("(?im)^\\s*Map\\s*Folder\\h*[:=]");
|
||||||
private static final Pattern MAP_FOLDER = Pattern.compile("(?im)^\\s*Map\\s*Folder\\h*[:=]\\h*(.+)$");
|
private static final Pattern MAP_FOLDER = Pattern.compile("(?im)^\\s*Map\\s*Folder\\h*[:=]\\h*(.+)$");
|
||||||
private static final Pattern SEPARATOR = Pattern.compile("[\\s,;]+");
|
private static final Pattern SEPARATOR = Pattern.compile("[,;]");
|
||||||
private static final Pattern MOD_ID = Pattern.compile("[A-Za-z0-9_.\\-]+");
|
private static final Pattern WHITESPACE = Pattern.compile("\\s+");
|
||||||
|
|
||||||
|
/** Words of letters, digits, {@code _}, {@code .}, and {@code -}, separated by spaces; with at least one letter or digit. */
|
||||||
|
private static final Pattern MOD_ID = Pattern.compile("(?=.*[A-Za-z0-9])[A-Za-z0-9_.\\-]+(?:\\h+[A-Za-z0-9_.\\-]+)*");
|
||||||
|
|
||||||
private DescriptionParser() {}
|
private DescriptionParser() {}
|
||||||
|
|
||||||
static String stripBbcode(String description) { return DescriptionParser.BBCODE.matcher(description).replaceAll(""); }
|
static String stripBbcode(String description) { return DescriptionParser.BBCODE.matcher(description).replaceAll(""); }
|
||||||
|
|
||||||
/** Every Mod ID of every {@code Mod ID} line, each once, in order of appearance. */
|
/**
|
||||||
|
* Every Mod ID of every {@code Mod ID} line, each once, in order of appearance. Mod IDs on
|
||||||
|
* one line are separated by {@code ,} or {@code ;}, and may contain spaces
|
||||||
|
* ({@code Nicks Moveable Workstations - Furniture Fix}, as in its {@code mod.info}). A part
|
||||||
|
* with other characters ({@code Foo (B41)}) yields those of its words that are Mod IDs; parts
|
||||||
|
* without a letter or digit yield none.
|
||||||
|
*/
|
||||||
static List<String> modIds(String description)
|
static List<String> modIds(String description)
|
||||||
{
|
{
|
||||||
Set<String> modIds = new LinkedHashSet<>();
|
Set<String> modIds = new LinkedHashSet<>();
|
||||||
@@ -33,9 +42,20 @@ final class DescriptionParser
|
|||||||
|
|
||||||
while (matcher.find())
|
while (matcher.find())
|
||||||
{
|
{
|
||||||
for (String token : DescriptionParser.SEPARATOR.split(matcher.group(1).strip()))
|
for (String part : DescriptionParser.SEPARATOR.split(matcher.group(1)))
|
||||||
{
|
{
|
||||||
if (DescriptionParser.MOD_ID.matcher(token).matches()) modIds.add(token);
|
String modId = part.strip();
|
||||||
|
|
||||||
|
if (DescriptionParser.MOD_ID.matcher(modId).matches())
|
||||||
|
{
|
||||||
|
modIds.add(modId);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (String token : DescriptionParser.WHITESPACE.split(modId))
|
||||||
|
{
|
||||||
|
if (DescriptionParser.MOD_ID.matcher(token).matches()) modIds.add(token);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -33,23 +33,33 @@ import org.jetbrains.annotations.Nullable;
|
|||||||
*
|
*
|
||||||
* <p>While the server runs, a drift check resolves the collection again every
|
* <p>While the server runs, a drift check resolves the collection again every
|
||||||
* {@code [drift] interval_min} minutes and logs how it differs from what the server runs, and
|
* {@code [drift] interval_min} minutes and logs how it differs from what the server runs, and
|
||||||
* which items were updated on Steam since startup. Changes take effect at the next restart.
|
* which items have a newer version on Steam than the server downloaded. Changes take effect at
|
||||||
|
* the next restart.
|
||||||
*
|
*
|
||||||
* <p>Threads: game objects ({@code ServerOptions}) on the main thread only, in {@link #onLoad()}
|
* <p>Threads: game objects ({@code ServerOptions}, {@code SteamWorkshop}) on the main thread
|
||||||
* and {@link CollectionCommand}; drift checks on the mod thread.
|
* only, in {@link #onLoad()}, {@link #onServerStarted()}, and {@link CollectionCommand}; drift
|
||||||
|
* checks on the mod thread.
|
||||||
*/
|
*/
|
||||||
public final class LuaModAutomatorMod extends Mod
|
public final class LuaModAutomatorMod extends Mod
|
||||||
{
|
{
|
||||||
private static final String NO_CHECK = "No drift check yet.";
|
private static final String NO_CHECK = "No drift check yet.";
|
||||||
private static final DateTimeFormatter TIME = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss 'UTC'").withZone(ZoneOffset.UTC);
|
private static final DateTimeFormatter TIME = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss 'UTC'").withZone(ZoneOffset.UTC);
|
||||||
|
private static final Duration RETRY_DELAY = Duration.ofSeconds(2);
|
||||||
|
|
||||||
/** The loaded instance, for {@link CollectionCommand}, which Project Zomboid creates. */
|
/** The loaded instance, for {@link CollectionCommand}, which Project Zomboid creates. */
|
||||||
private static volatile @Nullable LuaModAutomatorMod instance;
|
private static volatile @Nullable LuaModAutomatorMod instance;
|
||||||
|
|
||||||
/** When the server started; the Workshop download comes after this, so later Steam updates are not on the server. */
|
/**
|
||||||
|
* When the mod loaded, before the Workshop download. Stands in for the installed version of
|
||||||
|
* items Steam does not report (no Steam mode), on the side of reporting updates the server
|
||||||
|
* may already have downloaded.
|
||||||
|
*/
|
||||||
private final Instant startedAt = Instant.now();
|
private final Instant startedAt = Instant.now();
|
||||||
private final AtomicBoolean checkQueued = new AtomicBoolean();
|
private final AtomicBoolean checkQueued = new AtomicBoolean();
|
||||||
|
|
||||||
|
/** {@link WorkshopAdapter#installedVersions}, set in {@link #onServerStarted()}, after the Workshop download. */
|
||||||
|
private volatile Map<String, Long> installed = Map.of();
|
||||||
|
|
||||||
// Set in onLoad(), read later. Tasks submitted after onLoad() see these values.
|
// Set in onLoad(), read later. Tasks submitted after onLoad() see these values.
|
||||||
private @Nullable Settings settings;
|
private @Nullable Settings settings;
|
||||||
private @Nullable String collectionId;
|
private @Nullable String collectionId;
|
||||||
@@ -73,7 +83,6 @@ public final class LuaModAutomatorMod extends Mod
|
|||||||
public void onLoad()
|
public void onLoad()
|
||||||
{
|
{
|
||||||
LuaModAutomatorMod.instance = this;
|
LuaModAutomatorMod.instance = this;
|
||||||
this.commands().register(CollectionCommand.class);
|
|
||||||
|
|
||||||
this.running = ServerOptionsAdapter.read();
|
this.running = ServerOptionsAdapter.read();
|
||||||
|
|
||||||
@@ -115,7 +124,7 @@ public final class LuaModAutomatorMod extends Mod
|
|||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
Resolution resolution = this.resolve();
|
Resolution resolution = this.resolveAtStartup();
|
||||||
ServerValues values = resolution.values(settings.ini().baseMap());
|
ServerValues values = resolution.values(settings.ini().baseMap());
|
||||||
|
|
||||||
this.logWarnings(resolution.warnings());
|
this.logWarnings(resolution.warnings());
|
||||||
@@ -128,10 +137,14 @@ public final class LuaModAutomatorMod extends Mod
|
|||||||
}
|
}
|
||||||
catch (SteamException | ConfigurationException e)
|
catch (SteamException | ConfigurationException e)
|
||||||
{
|
{
|
||||||
String reason = Objects.requireNonNullElse(e.getMessage(), e.getClass().getSimpleName());
|
this.log(WARNING, "Cannot resolve collection '" + this.collectionId + "': " + LuaModAutomatorMod.reason(e) + ".");
|
||||||
|
this.fallBack(LuaModAutomatorMod.reason(e));
|
||||||
this.log(WARNING, "Cannot resolve collection '" + this.collectionId + "': " + reason);
|
}
|
||||||
this.fallBack(reason.endsWith(".") ? reason.substring(0, reason.length() - 1) : reason);
|
catch (RuntimeException e)
|
||||||
|
{
|
||||||
|
// An exception that leaves onLoad() stops the server.
|
||||||
|
this.logger().log(ERROR, "Cannot resolve collection '" + this.collectionId + "'.", e);
|
||||||
|
this.fallBack(e.toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
this.log(INFO, this.startup);
|
this.log(INFO, this.startup);
|
||||||
@@ -141,7 +154,18 @@ public final class LuaModAutomatorMod extends Mod
|
|||||||
public void onServerStarted()
|
public void onServerStarted()
|
||||||
{
|
{
|
||||||
Settings settings = this.settings;
|
Settings settings = this.settings;
|
||||||
if (settings == null || settings.drift().intervalMin() == 0) return;
|
if (settings == null) return;
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
this.installed = WorkshopAdapter.installedVersions(this.running.workshopIds());
|
||||||
|
}
|
||||||
|
catch (RuntimeException e)
|
||||||
|
{
|
||||||
|
this.logger().log(WARNING, "Cannot read the versions of the installed Workshop items; updates count from the server's start.", e);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (settings.drift().intervalMin() == 0) return;
|
||||||
|
|
||||||
Duration interval = Duration.ofMinutes(settings.drift().intervalMin());
|
Duration interval = Duration.ofMinutes(settings.drift().intervalMin());
|
||||||
this.modThread().scheduleWithFixedDelay(this::scheduledCheck, interval, interval);
|
this.modThread().scheduleWithFixedDelay(this::scheduledCheck, interval, interval);
|
||||||
@@ -272,7 +296,7 @@ public final class LuaModAutomatorMod extends Mod
|
|||||||
|
|
||||||
this.lastCheck = "Last drift check " + time + ": "
|
this.lastCheck = "Last drift check " + time + ": "
|
||||||
+ (drift.isEmpty() ? "the collection matches the running mod list." : "the collection differs: " + difference + "; restart the server to apply it.")
|
+ (drift.isEmpty() ? "the collection matches the running mod list." : "the collection differs: " + difference + "; restart the server to apply it.")
|
||||||
+ (updated.isEmpty() ? "" : "\nUpdated on Steam since startup: " + String.join(", ", updated) + "; restart the server to load the updates.");
|
+ (updated.isEmpty() ? "" : "\nNewer on Steam than on the server: " + String.join(", ", updated) + "; restart the server to load the updates.");
|
||||||
}
|
}
|
||||||
catch (SteamException | ConfigurationException e)
|
catch (SteamException | ConfigurationException e)
|
||||||
{
|
{
|
||||||
@@ -294,28 +318,58 @@ public final class LuaModAutomatorMod extends Mod
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Items the server runs that Steam updated after the server started, as {@code 'title' (id)};
|
* Items the server runs that have a newer version on Steam than the installed one (or, when
|
||||||
* logs each update once. Mod thread.
|
* Steam does not report it, than {@link #startedAt}), as {@code 'title' (id)}; logs each
|
||||||
|
* update once. Mod thread.
|
||||||
*/
|
*/
|
||||||
private List<String> updatedItems(Resolution resolution)
|
private List<String> updatedItems(Resolution resolution)
|
||||||
{
|
{
|
||||||
Set<String> running = new HashSet<>(this.running.workshopIds());
|
Set<String> running = new HashSet<>(this.running.workshopIds());
|
||||||
List<String> updated = new ArrayList<>();
|
Map<String, Long> installed = this.installed;
|
||||||
|
List<String> updated = new ArrayList<>();
|
||||||
|
|
||||||
for (Resolution.Item item : resolution.items())
|
for (Resolution.Item item : resolution.items())
|
||||||
{
|
{
|
||||||
if (!running.contains(item.id()) || item.timeUpdated() <= this.startedAt.getEpochSecond()) continue;
|
if (!running.contains(item.id()) || item.timeUpdated() <= installed.getOrDefault(item.id(), this.startedAt.getEpochSecond())) continue;
|
||||||
|
|
||||||
String name = "'" + item.title() + "' (" + item.id() + ")";
|
String name = "'" + item.title() + "' (" + item.id() + ")";
|
||||||
updated.add(name);
|
updated.add(name);
|
||||||
|
|
||||||
if (!Objects.equals(this.reportedUpdates.put(item.id(), item.timeUpdated()), item.timeUpdated()))
|
if (!Objects.equals(this.reportedUpdates.put(item.id(), item.timeUpdated()), item.timeUpdated()))
|
||||||
this.log(WARNING, name + " was updated on Steam at " + LuaModAutomatorMod.TIME.format(Instant.ofEpochSecond(item.timeUpdated())) + ", after the server started. Restart the server to load the update; clients with the new version may not be able to join until then.");
|
this.log(WARNING, name + " was updated on Steam at " + LuaModAutomatorMod.TIME.format(Instant.ofEpochSecond(item.timeUpdated())) + ", after the version the server downloaded. Restart the server to load the update; clients with the new version may not be able to join until then.");
|
||||||
}
|
}
|
||||||
|
|
||||||
return updated;
|
return updated;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@link #resolve()}, tried once more after {@link #RETRY_DELAY} when Steam fails. Main
|
||||||
|
* thread, in {@link #onLoad()}, before the server runs.
|
||||||
|
*/
|
||||||
|
private Resolution resolveAtStartup() throws SteamException, ConfigurationException
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return this.resolve();
|
||||||
|
}
|
||||||
|
catch (SteamException e)
|
||||||
|
{
|
||||||
|
this.log(WARNING, "Cannot resolve collection '" + this.collectionId + "': " + LuaModAutomatorMod.reason(e) + "; retrying in " + LuaModAutomatorMod.RETRY_DELAY.toSeconds() + " seconds.");
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Thread.sleep(LuaModAutomatorMod.RETRY_DELAY);
|
||||||
|
}
|
||||||
|
catch (InterruptedException interrupted)
|
||||||
|
{
|
||||||
|
Thread.currentThread().interrupt();
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.resolve();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private Resolution resolve() throws SteamException, ConfigurationException
|
private Resolution resolve() throws SteamException, ConfigurationException
|
||||||
{
|
{
|
||||||
Settings settings = Objects.requireNonNull(this.settings);
|
Settings settings = Objects.requireNonNull(this.settings);
|
||||||
@@ -386,6 +440,13 @@ public final class LuaModAutomatorMod extends Mod
|
|||||||
|
|
||||||
private void log(System.Logger.Level level, String message) { this.logger().log(level, message); }
|
private void log(System.Logger.Level level, String message) { this.logger().log(level, message); }
|
||||||
|
|
||||||
|
/** The message of {@code e}, without a final period. */
|
||||||
|
private static String reason(Exception e)
|
||||||
|
{
|
||||||
|
String reason = Objects.requireNonNullElse(e.getMessage(), e.getClass().getSimpleName());
|
||||||
|
return reason.endsWith(".") ? reason.substring(0, reason.length() - 1) : reason;
|
||||||
|
}
|
||||||
|
|
||||||
private static String counts(ServerValues values)
|
private static String counts(ServerValues values)
|
||||||
{
|
{
|
||||||
return LuaModAutomatorMod.count(values.workshopIds().size(), "Workshop item") + ", " + LuaModAutomatorMod.count(values.modIds().size(), "Mod ID") + ", Map=" + values.map();
|
return LuaModAutomatorMod.count(values.workshopIds().size(), "Workshop item") + ", " + LuaModAutomatorMod.count(values.modIds().size(), "Mod ID") + ", Map=" + values.map();
|
||||||
|
|||||||
@@ -51,10 +51,11 @@ record Resolution(List<Resolution.Item> items, List<Resolution.Item> excluded, L
|
|||||||
*/
|
*/
|
||||||
List<String> modList()
|
List<String> modList()
|
||||||
{
|
{
|
||||||
|
// Widths start at 1: "%-0s" is not a valid format.
|
||||||
List<String> lines = new ArrayList<>();
|
List<String> lines = new ArrayList<>();
|
||||||
int number = String.valueOf(this.items.size()).length();
|
int number = String.valueOf(this.items.size()).length();
|
||||||
int title = 0;
|
int title = 1;
|
||||||
int modIds = 0;
|
int modIds = 1;
|
||||||
|
|
||||||
for (Item item : this.items)
|
for (Item item : this.items)
|
||||||
{
|
{
|
||||||
@@ -62,18 +63,23 @@ record Resolution(List<Resolution.Item> items, List<Resolution.Item> excluded, L
|
|||||||
modIds = Math.max(modIds, Resolution.modIds(item).length());
|
modIds = Math.max(modIds, Resolution.modIds(item).length());
|
||||||
}
|
}
|
||||||
|
|
||||||
lines.add("# Mod list");
|
lines.add("Mod List:");
|
||||||
|
|
||||||
for (int i = 0; i < this.items.size(); i++)
|
for (int i = 0; i < this.items.size(); i++)
|
||||||
{
|
{
|
||||||
Item item = this.items.get(i);
|
Item item = this.items.get(i);
|
||||||
lines.add(("# %" + number + "d. %-" + title + "s %10s %-" + modIds + "s").formatted(i + 1, item.title(), item.id(), Resolution.modIds(item)).stripTrailing());
|
//noinspection StringConcatenationInFormatCall
|
||||||
|
lines.add(
|
||||||
|
("%" + number + "d. %-" + title + "s %10s %-" + modIds + "s").formatted(
|
||||||
|
i + 1, item.title(), item.id(), Resolution.modIds(item)
|
||||||
|
).stripTrailing()
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!this.excluded.isEmpty())
|
if (!this.excluded.isEmpty())
|
||||||
{
|
{
|
||||||
lines.add("# Excluded");
|
lines.add("Excluded:");
|
||||||
for (Item item : this.excluded) lines.add("# %s %s".formatted(item.title(), item.id()));
|
for (Item item : this.excluded) lines.add(" %s %s".formatted(item.title(), item.id()));
|
||||||
}
|
}
|
||||||
|
|
||||||
return lines;
|
return lines;
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
package dev.overlord.luamodautomator;
|
package dev.overlord.luamodautomator;
|
||||||
|
|
||||||
|
import dev.overlord.zomboidforge.api.annotations.Min;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
@@ -21,22 +23,10 @@ record Settings(String collection, Settings.Ini ini, Settings.Steam steam, Setti
|
|||||||
record Ini(boolean write, boolean manageMap, List<String> baseMap) {}
|
record Ini(boolean write, boolean manageMap, List<String> baseMap) {}
|
||||||
|
|
||||||
/** @param timeoutS seconds per Steam Web API request */
|
/** @param timeoutS seconds per Steam Web API request */
|
||||||
record Steam(int timeoutS)
|
record Steam(@Min(1) int timeoutS) {}
|
||||||
{
|
|
||||||
Steam
|
|
||||||
{
|
|
||||||
if (timeoutS < 1) throw new IllegalArgumentException("'timeout_s' must be at least 1, found " + timeoutS);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @param intervalMin minutes between drift checks while the server runs; 0 turns them off */
|
/** @param intervalMin minutes between drift checks while the server runs; 0 turns them off */
|
||||||
record Drift(int intervalMin)
|
record Drift(@Min(0) int intervalMin) {}
|
||||||
{
|
|
||||||
Drift
|
|
||||||
{
|
|
||||||
if (intervalMin < 0) throw new IllegalArgumentException("'interval_min' must be 0 or more, found " + intervalMin);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param buckets the bucket sequence of the load order
|
* @param buckets the bucket sequence of the load order
|
||||||
@@ -53,15 +43,10 @@ record Settings(String collection, Settings.Ini ini, Settings.Steam steam, Setti
|
|||||||
* @param position 1-based place in the final list, applied after {@code priority}
|
* @param position 1-based place in the final list, applied after {@code priority}
|
||||||
* @param exclude whether the item is left out of {@code Mods=}, {@code WorkshopItems=}, and {@code Map=}
|
* @param exclude whether the item is left out of {@code Mods=}, {@code WorkshopItems=}, and {@code Map=}
|
||||||
*/
|
*/
|
||||||
record Item(Optional<List<String>> modIds, Optional<String> title, Optional<String> bucket, Optional<Integer> position, Optional<Boolean> exclude)
|
record Item(Optional<List<String>> modIds, Optional<String> title, Optional<String> bucket, @Min(1) Optional<Integer> position, Optional<Boolean> exclude)
|
||||||
{
|
{
|
||||||
static final Item NONE = new Item(Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty());
|
static final Item NONE = new Item(Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty());
|
||||||
|
|
||||||
Item
|
|
||||||
{
|
|
||||||
if (position.isPresent() && position.get() < 1) throw new IllegalArgumentException("'position' must be at least 1, found " + position.get());
|
|
||||||
}
|
|
||||||
|
|
||||||
boolean excluded() { return this.exclude.orElse(false); }
|
boolean excluded() { return this.exclude.orElse(false); }
|
||||||
|
|
||||||
/** These overrides, with the fields this item does not set taken from {@code other}. */
|
/** These overrides, with the fields this item does not set taken from {@code other}. */
|
||||||
|
|||||||
@@ -44,7 +44,8 @@ final class SteamWorkshopApi implements AutoCloseable
|
|||||||
/** {@code filetype} of a child that is itself a collection. */
|
/** {@code filetype} of a child that is itself a collection. */
|
||||||
private static final int COLLECTION = 2;
|
private static final int COLLECTION = 2;
|
||||||
|
|
||||||
private static final Pattern COLLECTION_ID = Pattern.compile("(?:[?&]id=)?(\\d{2,})");
|
private static final Pattern ID_PARAMETER = Pattern.compile("[?&]id=(\\d{2,})");
|
||||||
|
private static final Pattern BARE_ID = Pattern.compile("\\d{2,}");
|
||||||
|
|
||||||
private final HttpClient client;
|
private final HttpClient client;
|
||||||
private final URI base;
|
private final URI base;
|
||||||
@@ -59,11 +60,19 @@ final class SteamWorkshopApi implements AutoCloseable
|
|||||||
this.userAgent = userAgent;
|
this.userAgent = userAgent;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The collection id in {@code setting}, a collection URL or a bare id. */
|
/**
|
||||||
|
* The collection id in {@code setting}: the {@code id} parameter of a collection URL, which
|
||||||
|
* may have other numeric parameters such as {@code tscn}, or a bare id.
|
||||||
|
*/
|
||||||
static Optional<String> collectionId(String setting)
|
static Optional<String> collectionId(String setting)
|
||||||
{
|
{
|
||||||
Matcher matcher = SteamWorkshopApi.COLLECTION_ID.matcher(setting.strip());
|
String value = setting.strip();
|
||||||
return matcher.find() ? Optional.of(matcher.group(1)) : Optional.empty();
|
Matcher matcher = SteamWorkshopApi.ID_PARAMETER.matcher(value);
|
||||||
|
|
||||||
|
if (matcher.find()) return Optional.of(matcher.group(1));
|
||||||
|
if (SteamWorkshopApi.BARE_ID.matcher(value).matches()) return Optional.of(value);
|
||||||
|
|
||||||
|
return Optional.empty();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -0,0 +1,50 @@
|
|||||||
|
package dev.overlord.luamodautomator;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import zombie.core.znet.SteamUtils;
|
||||||
|
import zombie.core.znet.SteamWorkshop;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The versions of the Workshop items installed on the server. Main thread only.
|
||||||
|
*
|
||||||
|
* <p>Steam reports, for an installed item, when the installed version was updated on the
|
||||||
|
* Workshop; {@code GameServerWorkshopItems} compares it with Steam's {@code time_updated} to
|
||||||
|
* decide whether an item needs an update (Project Zomboid 42.21).
|
||||||
|
*/
|
||||||
|
final class WorkshopAdapter
|
||||||
|
{
|
||||||
|
private WorkshopAdapter() {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* For each of {@code ids}, when its installed version was updated on the Workshop, in
|
||||||
|
* seconds since the epoch. Ids that are not installed or not numeric are left out; all of
|
||||||
|
* them without Steam mode.
|
||||||
|
*/
|
||||||
|
static Map<String, Long> installedVersions(List<String> ids)
|
||||||
|
{
|
||||||
|
if (!SteamUtils.isSteamModeEnabled()) return Map.of();
|
||||||
|
|
||||||
|
Map<String, Long> versions = new HashMap<>();
|
||||||
|
|
||||||
|
for (String id : ids)
|
||||||
|
{
|
||||||
|
long timeUpdated;
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
timeUpdated = SteamWorkshop.instance.GetItemInstallTimeStamp(Long.parseLong(id));
|
||||||
|
}
|
||||||
|
catch (NumberFormatException e)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (timeUpdated > 0) versions.put(id, timeUpdated);
|
||||||
|
}
|
||||||
|
|
||||||
|
return Map.copyOf(versions);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,10 +2,12 @@
|
|||||||
* LuaModAutomator: the server's {@code Mods=}, {@code WorkshopItems=}, and {@code Map=} come
|
* LuaModAutomator: the server's {@code Mods=}, {@code WorkshopItems=}, and {@code Map=} come
|
||||||
* from a public Steam Workshop collection, resolved at every start.
|
* from a public Steam Workshop collection, resolved at every start.
|
||||||
*
|
*
|
||||||
* <p>Only {@link dev.overlord.luamodautomator.LuaModAutomatorMod},
|
* <p>Only
|
||||||
* {@link dev.overlord.luamodautomator.ServerOptionsAdapter}, and
|
* {@link dev.overlord.luamodautomator.LuaModAutomatorMod},
|
||||||
* {@link dev.overlord.luamodautomator.CollectionCommand} use game classes; everything else runs
|
* {@link dev.overlord.luamodautomator.ServerOptionsAdapter},
|
||||||
* without the game.
|
* {@link dev.overlord.luamodautomator.WorkshopAdapter}, and
|
||||||
|
* {@link dev.overlord.luamodautomator.CollectionCommand} use game classes;
|
||||||
|
* everything else runs without the game.
|
||||||
*
|
*
|
||||||
* @noinspection UnstableApiUsage, RedundantSuppression
|
* @noinspection UnstableApiUsage, RedundantSuppression
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -73,7 +73,24 @@ class CollectionResolverTest
|
|||||||
|
|
||||||
Resolution resolution = CollectionResolver.resolve(CollectionResolverTest.COLLECTION, order, items);
|
Resolution resolution = CollectionResolver.resolve(CollectionResolverTest.COLLECTION, order, items);
|
||||||
|
|
||||||
assertEquals(List.of("100", "200", "300", "400", "500"), CollectionResolverTest.ids(resolution));
|
assertEquals(List.of("100", "300", "200", "400", "500"), CollectionResolverTest.ids(resolution));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void pinsKeepTheirPlaceWhenALaterPinStartsAheadOfThem() throws ConfigurationException
|
||||||
|
{
|
||||||
|
List<WorkshopItem> collection = List.of(
|
||||||
|
CollectionResolverTest.item("1", "B", "Mod ID: B"),
|
||||||
|
CollectionResolverTest.item("2", "X", "Mod ID: X"),
|
||||||
|
CollectionResolverTest.item("3", "Y", "Mod ID: Y"),
|
||||||
|
CollectionResolverTest.item("4", "P", "Mod ID: P"),
|
||||||
|
CollectionResolverTest.item("5", "Z", "Mod ID: Z")
|
||||||
|
);
|
||||||
|
Map<String, Settings.Item> items = Map.of("P", CollectionResolverTest.position(3), "B", CollectionResolverTest.position(4));
|
||||||
|
|
||||||
|
Resolution resolution = CollectionResolver.resolve(collection, CollectionResolverTest.DEFAULT_ORDER, items);
|
||||||
|
|
||||||
|
assertEquals(List.of("2", "3", "4", "1", "5"), CollectionResolverTest.ids(resolution));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -169,6 +186,28 @@ class CollectionResolverTest
|
|||||||
assertEquals(1, resolution.warnings().size());
|
assertEquals(1, resolution.warnings().size());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void modIdsDifferingOnlyInCaseAreWarnedAboutAndBothListed() throws ConfigurationException
|
||||||
|
{
|
||||||
|
List<WorkshopItem> collection = List.of(CollectionResolverTest.item("100", "One", "Mod ID: Shared"), CollectionResolverTest.item("200", "Two", "Mod ID: shared"));
|
||||||
|
Resolution resolution = CollectionResolver.resolve(collection, CollectionResolverTest.DEFAULT_ORDER, Map.of());
|
||||||
|
|
||||||
|
assertEquals("\\Shared;\\shared", resolution.values(List.of()).mods());
|
||||||
|
assertEquals(List.of("Mod IDs 'Shared' of 'One' (100) and 'shared' of 'Two' (200) differ only in case; Mods= lists both."), resolution.warnings());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void modIdWithSpacesIsListedWithAWarningUntilAnOverrideConfirmsIt() throws ConfigurationException
|
||||||
|
{
|
||||||
|
List<WorkshopItem> collection = List.of(CollectionResolverTest.item("3809993153", "Furniture Fix", "Mod ID: Nicks Moveable Workstations - Furniture Fix"));
|
||||||
|
Resolution parsed = CollectionResolver.resolve(collection, CollectionResolverTest.DEFAULT_ORDER, Map.of());
|
||||||
|
Resolution confirmed = CollectionResolver.resolve(collection, CollectionResolverTest.DEFAULT_ORDER, Map.of("3809993153", CollectionResolverTest.modIds("Nicks Moveable Workstations - Furniture Fix")));
|
||||||
|
|
||||||
|
assertEquals("\\Nicks Moveable Workstations - Furniture Fix", parsed.values(List.of()).mods());
|
||||||
|
assertEquals(List.of("'Furniture Fix' (3809993153) names the Mod ID 'Nicks Moveable Workstations - Furniture Fix', which contains spaces; Mods= lists it as written. Set [items.3809993153] mod_ids to confirm or correct it."), parsed.warnings());
|
||||||
|
assertEquals(List.of(), confirmed.warnings());
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void mapFoldersThenBaseMapEachOnce() throws ConfigurationException
|
void mapFoldersThenBaseMapEachOnce() throws ConfigurationException
|
||||||
{
|
{
|
||||||
@@ -190,16 +229,25 @@ class CollectionResolverTest
|
|||||||
List<String> modList = CollectionResolver.resolve(CollectionResolverTest.COLLECTION, CollectionResolverTest.DEFAULT_ORDER, items).modList();
|
List<String> modList = CollectionResolver.resolve(CollectionResolverTest.COLLECTION, CollectionResolverTest.DEFAULT_ORDER, items).modList();
|
||||||
|
|
||||||
assertEquals(List.of(
|
assertEquals(List.of(
|
||||||
"# Mod list",
|
"Mod List:",
|
||||||
"# 1. A Map 300 MapMod",
|
"1. A Map 300 MapMod",
|
||||||
"# 2. Framework 200 Frame",
|
"2. Framework 200 Frame",
|
||||||
"# 3. Misc One 100 MiscOne",
|
"3. Misc One 100 MiscOne",
|
||||||
"# 4. Misc Two 400 MiscTwo, MiscTwoExtra",
|
"4. Misc Two 400 MiscTwo, MiscTwoExtra",
|
||||||
"# Excluded",
|
"Excluded:",
|
||||||
"# Misc Three 500"
|
" Misc Three 500"
|
||||||
), modList);
|
), modList);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void modListWithAnEmptyTitle() throws ConfigurationException
|
||||||
|
{
|
||||||
|
List<WorkshopItem> collection = List.of(CollectionResolverTest.item("100", "Misc One", "Mod ID: MiscOne"));
|
||||||
|
Map<String, Settings.Item> items = Map.of("100", new Settings.Item(Optional.empty(), Optional.of(""), Optional.empty(), Optional.empty(), Optional.empty()));
|
||||||
|
|
||||||
|
assertEquals(List.of("Mod List:", "1. 100 MiscOne"), CollectionResolver.resolve(collection, CollectionResolverTest.DEFAULT_ORDER, items).modList());
|
||||||
|
}
|
||||||
|
|
||||||
private static List<String> ids(Resolution resolution) { return resolution.items().stream().map(Resolution.Item::id).toList(); }
|
private static List<String> ids(Resolution resolution) { return resolution.items().stream().map(Resolution.Item::id).toList(); }
|
||||||
|
|
||||||
private static WorkshopItem item(String id, String title, String description) { return WorkshopItem.of(id, title, description, List.of("Build 42"), 0); }
|
private static WorkshopItem item(String id, String title, String description) { return WorkshopItem.of(id, title, description, List.of("Build 42"), 0); }
|
||||||
|
|||||||
@@ -43,6 +43,25 @@ class DescriptionParserTest
|
|||||||
assertEquals(List.of("Foo", "Bar"), DescriptionParser.modIds("Mod ID: Foo (Bar) Bar"));
|
assertEquals(List.of("Foo", "Bar"), DescriptionParser.modIds("Mod ID: Foo (Bar) Bar"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void modIdsSkipPartsWithoutLetterOrDigit()
|
||||||
|
{
|
||||||
|
assertEquals(List.of("Foo", "Bar"), DescriptionParser.modIds("Mod ID: Foo; --; Bar, ..."));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void modIdWithSpacesStaysWhole()
|
||||||
|
{
|
||||||
|
// 3809993153: mod.info has id=Nicks Moveable Workstations - Furniture Fix
|
||||||
|
assertEquals(List.of("Nicks Moveable Workstations - Furniture Fix"), DescriptionParser.modIds("Mod id: Nicks Moveable Workstations - Furniture Fix\nid=3809993153"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void modIdsWithSpacesSeparatedBySemicolons()
|
||||||
|
{
|
||||||
|
assertEquals(List.of("Foo Bar", "Baz"), DescriptionParser.modIds("Mod IDs: Foo Bar ; Baz"));
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void emptyModIdLineDoesNotReadTheNextLine()
|
void emptyModIdLineDoesNotReadTheNextLine()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -0,0 +1,70 @@
|
|||||||
|
package dev.overlord.luamodautomator;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.time.Duration;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolves a collection like the server does at startup, without the server: binds the shipped
|
||||||
|
* defaults with a {@code config.toml} on top, asks Steam, and prints the mod list,
|
||||||
|
* {@code Mods=}, {@code WorkshopItems=}, {@code Map=}, and every warning. Run through
|
||||||
|
* {@code ./gradlew resolveCollection --args=<config.toml>}.
|
||||||
|
*/
|
||||||
|
public final class ResolveCollection
|
||||||
|
{
|
||||||
|
private ResolveCollection() {}
|
||||||
|
|
||||||
|
public static void main(String[] args) throws IOException
|
||||||
|
{
|
||||||
|
if (args.length != 1)
|
||||||
|
{
|
||||||
|
System.err.println("Usage: ./gradlew resolveCollection --args=<config.toml>");
|
||||||
|
System.exit(2);
|
||||||
|
}
|
||||||
|
|
||||||
|
Path config = Path.of(args[0]);
|
||||||
|
|
||||||
|
if (!Files.isRegularFile(config))
|
||||||
|
{
|
||||||
|
System.err.println("'" + config.toAbsolutePath() + "' does not exist.");
|
||||||
|
System.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
List<String> warnings = new ArrayList<>();
|
||||||
|
Settings settings = SettingsTest.bind(Files.readString(config, StandardCharsets.UTF_8), warnings);
|
||||||
|
String id = SteamWorkshopApi.collectionId(settings.collection()).orElse("");
|
||||||
|
|
||||||
|
if (id.isEmpty())
|
||||||
|
{
|
||||||
|
System.err.println("'collection' in '" + args[0] + "' holds no collection id.");
|
||||||
|
System.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
try (SteamWorkshopApi api = new SteamWorkshopApi(SteamWorkshopApi.BASE, Duration.ofSeconds(settings.steam().timeoutS()), "LuaModAutomator/resolveCollection"))
|
||||||
|
{
|
||||||
|
Resolution resolution = CollectionResolver.resolve(api.collection(id, warnings), settings.order(), settings.items());
|
||||||
|
ServerValues values = resolution.values(settings.ini().baseMap());
|
||||||
|
|
||||||
|
warnings.addAll(resolution.warnings());
|
||||||
|
|
||||||
|
resolution.modList().forEach(System.out::println);
|
||||||
|
System.out.println();
|
||||||
|
System.out.println("Mods=" + values.mods());
|
||||||
|
System.out.println();
|
||||||
|
System.out.println("WorkshopItems=" + values.workshopItems());
|
||||||
|
System.out.println();
|
||||||
|
System.out.println("Map=" + values.map());
|
||||||
|
|
||||||
|
for (String warning : warnings) System.err.println("WARNING: " + warning);
|
||||||
|
}
|
||||||
|
catch (SteamException | ConfigurationException e)
|
||||||
|
{
|
||||||
|
System.err.println(e.getMessage());
|
||||||
|
System.exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -102,13 +102,20 @@ class SettingsTest
|
|||||||
@Test
|
@Test
|
||||||
void invalidValues()
|
void invalidValues()
|
||||||
{
|
{
|
||||||
assertThrows(IllegalStateException.class, () -> SettingsTest.bind("[steam]\ntimeout_s = 0"));
|
|
||||||
assertThrows(IllegalStateException.class, () -> SettingsTest.bind("[drift]\ninterval_min = -1"));
|
|
||||||
assertThrows(IllegalStateException.class, () -> SettingsTest.bind("[items.123]\nposition = 0"));
|
|
||||||
assertThrows(IllegalStateException.class, () -> SettingsTest.bind("[items.123]\nmod_ids = \"Foo\""));
|
assertThrows(IllegalStateException.class, () -> SettingsTest.bind("[items.123]\nmod_ids = \"Foo\""));
|
||||||
assertThrows(IllegalStateException.class, () -> SettingsTest.bind("collection = 123"));
|
assertThrows(IllegalStateException.class, () -> SettingsTest.bind("collection = 123"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void valuesOutOfBoundsAreReportedTogetherWithTheirKeys()
|
||||||
|
{
|
||||||
|
String message = assertThrows(IllegalStateException.class, () -> SettingsTest.bind("[steam]\ntimeout_s = 0\n[drift]\ninterval_min = -1\n[items.123]\nposition = 0")).getMessage();
|
||||||
|
|
||||||
|
assertTrue(message.contains("'steam.timeout_s' must be at least 1, found 0."), message);
|
||||||
|
assertTrue(message.contains("'drift.interval_min' must be at least 0, found -1."), message);
|
||||||
|
assertTrue(message.contains("'items.123.position' must be at least 1, found 0."), message);
|
||||||
|
}
|
||||||
|
|
||||||
static Settings bind(String overrides) { return SettingsTest.bind(overrides, new CopyOnWriteArrayList<>()); }
|
static Settings bind(String overrides) { return SettingsTest.bind(overrides, new CopyOnWriteArrayList<>()); }
|
||||||
|
|
||||||
/** The shipped defaults with {@code overrides} on top, bound like the server binds them; warnings go to {@code warnings}. */
|
/** The shipped defaults with {@code overrides} on top, bound like the server binds them; warnings go to {@code warnings}. */
|
||||||
|
|||||||
@@ -73,8 +73,10 @@ class SteamWorkshopApiTest
|
|||||||
{
|
{
|
||||||
assertEquals(Optional.of("1234567890"), SteamWorkshopApi.collectionId("https://steamcommunity.com/sharedfiles/filedetails/?id=1234567890"));
|
assertEquals(Optional.of("1234567890"), SteamWorkshopApi.collectionId("https://steamcommunity.com/sharedfiles/filedetails/?id=1234567890"));
|
||||||
assertEquals(Optional.of("1234567890"), SteamWorkshopApi.collectionId("https://steamcommunity.com/sharedfiles/filedetails/?searchtext=&id=1234567890"));
|
assertEquals(Optional.of("1234567890"), SteamWorkshopApi.collectionId("https://steamcommunity.com/sharedfiles/filedetails/?searchtext=&id=1234567890"));
|
||||||
|
assertEquals(Optional.of("1234567890"), SteamWorkshopApi.collectionId("https://steamcommunity.com/sharedfiles/filedetails/?tscn=1712345678&id=1234567890"));
|
||||||
assertEquals(Optional.of("1234567890"), SteamWorkshopApi.collectionId(" 1234567890 "));
|
assertEquals(Optional.of("1234567890"), SteamWorkshopApi.collectionId(" 1234567890 "));
|
||||||
assertEquals(Optional.empty(), SteamWorkshopApi.collectionId("my collection"));
|
assertEquals(Optional.empty(), SteamWorkshopApi.collectionId("my collection"));
|
||||||
|
assertEquals(Optional.empty(), SteamWorkshopApi.collectionId("https://steamcommunity.com/sharedfiles/filedetails/?tscn=1712345678"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -109,9 +111,9 @@ class SteamWorkshopApiTest
|
|||||||
Settings settings = SettingsTest.bind("");
|
Settings settings = SettingsTest.bind("");
|
||||||
Resolution resolution = CollectionResolver.resolve(this.api.collection(SteamWorkshopApiTest.recordedId(), new ArrayList<>()), settings.order(), settings.items());
|
Resolution resolution = CollectionResolver.resolve(this.api.collection(SteamWorkshopApiTest.recordedId(), new ArrayList<>()), settings.order(), settings.items());
|
||||||
ServerValues values = resolution.values(settings.ini().baseMap());
|
ServerValues values = resolution.values(settings.ini().baseMap());
|
||||||
List<String> expected = SteamWorkshopApiTest.resource("script-output.txt").lines().toList();
|
List<String> expected = SteamWorkshopApiTest.withoutCommentPrefix(SteamWorkshopApiTest.resource("script-output.txt").lines().toList());
|
||||||
|
|
||||||
List<String> actual = new ArrayList<>(resolution.modList());
|
List<String> actual = new ArrayList<>(resolution.modList().subList(1, resolution.modList().size()));
|
||||||
actual.add("Mods=" + values.mods());
|
actual.add("Mods=" + values.mods());
|
||||||
actual.add("WorkshopItems=" + values.workshopItems());
|
actual.add("WorkshopItems=" + values.workshopItems());
|
||||||
|
|
||||||
@@ -207,6 +209,9 @@ class SteamWorkshopApiTest
|
|||||||
assertFalse(items.get(0).found());
|
assertFalse(items.get(0).found());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** The script's output without its mod list header, and the mod list lines without their {@code "# "}. */
|
||||||
|
private static List<String> withoutCommentPrefix(List<String> output) { return output.stream().skip(1).map(line -> line.startsWith("# ") ? line.substring(2) : line).toList(); }
|
||||||
|
|
||||||
/** Details for every even id of the request: title {@code Item <id>}, Mod ID {@code Mod<id>}. */
|
/** Details for every even id of the request: title {@code Item <id>}, Mod ID {@code Mod<id>}. */
|
||||||
private static Response details(Map<String, String> form)
|
private static Response details(Map<String, String> form)
|
||||||
{
|
{
|
||||||
|
|||||||
Reference in new issue
Block a user