Compare commits
9
Commits
8fdd1b9b03
..
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ee4be1a5b6 | ||
|
|
0763730a24 | ||
|
|
389b5b19d7 | ||
|
|
1d657e2b9a | ||
|
|
322092729f | ||
|
|
e07e946a87 | ||
|
|
226c909d19 | ||
|
|
8484d6c20c | ||
|
|
e1094d96a2 |
No files matched your search
@@ -0,0 +1,35 @@
|
||||
# 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.
|
||||
# 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
|
||||
# exists, else the job's automatic token.
|
||||
name: release
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- "v*"
|
||||
|
||||
jobs:
|
||||
release:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
|
||||
with:
|
||||
# release.sh reads the v* tag on HEAD and checks that HEAD is on origin/master
|
||||
fetch-depth: 0
|
||||
|
||||
- uses: actions/setup-java@cf277c60eb25467037889841efdb72551f06f6c3 # v4.9.1
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: "25"
|
||||
|
||||
# The build runs without the token; only the publish step gets it.
|
||||
- name: Build
|
||||
run: ci/release.sh build
|
||||
|
||||
- name: Publish
|
||||
env:
|
||||
GITEA_TOKEN: ${{ secrets.RELEASE_TOKEN || secrets.GITEA_TOKEN }}
|
||||
run: ci/release.sh publish
|
||||
@@ -2,6 +2,7 @@
|
||||
!README.md
|
||||
/lib
|
||||
.*/
|
||||
!.gitea/
|
||||
|
||||
build/
|
||||
out/
|
||||
|
||||
@@ -11,15 +11,25 @@ Players keep the official, unmodified client; the mod runs on the server only.
|
||||
|
||||
## 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
|
||||
- a **Public** Steam Workshop collection: unlisted, friends-only, and private collections are
|
||||
invisible to Steam's Web API
|
||||
|
||||
## Installation
|
||||
|
||||
1. Unpack `lua_mod_automator-<version>.zip` into `<forge>/mods/`, which gives
|
||||
`<forge>/mods/lua_mod_automator/`.
|
||||
1. Download the newest release and unpack it into `<forge>/mods/`, which gives
|
||||
`<forge>/mods/lua_mod_automator/`:
|
||||
|
||||
```shell
|
||||
curl --fail --location --output lua_mod_automator.zip \
|
||||
https://git.security-command.org/Overlord/LuaModAutomator/releases/download/latest/lua_mod_automator.zip
|
||||
unzip -o lua_mod_automator.zip -d <forge>/mods/
|
||||
```
|
||||
|
||||
Every release also carries `lua_mod_automator-<version>.zip` for a fixed version. To update,
|
||||
remove `lua_mod_automator.jar` and `lib/` from the mod's folder first and unpack the new zip;
|
||||
`config.toml` is not part of the zip and stays.
|
||||
2. Create `<forge>/mods/lua_mod_automator/config.toml` with at least the collection:
|
||||
|
||||
```toml
|
||||
@@ -35,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.
|
||||
|
||||
- **Mod IDs** come from description lines such as `Mod ID: Foo` or `ModID = Foo; Bar`. An 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).
|
||||
- **Mod IDs** come from description lines such as `Mod ID: Foo` or `ModID = Foo; Bar`. A Mod
|
||||
ID may contain spaces (`Mod ID: Nicks Moveable Workstations - Furniture Fix`); `Mods=` then
|
||||
lists it as written, with a warning until `[items.<id>] mod_ids` confirms or corrects it. An
|
||||
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),
|
||||
`framework` (the Steam tag *Framework*), or `misc`. Buckets load in the order of
|
||||
`[order] buckets`, items within a bucket in collection order.
|
||||
@@ -53,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:
|
||||
|
||||
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
|
||||
`zomboidforge.db`;
|
||||
3. the values already in the `.ini`.
|
||||
@@ -110,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`
|
||||
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
|
||||
in a bucket missing from `[order] buckets` is an error: the mod then falls back as if Steam
|
||||
could not be reached.
|
||||
field), Mod IDs named by two items (`Mods=` lists them once), Mod IDs that differ only in case
|
||||
(`Mods=` lists both), unknown keys. An item that lands in a bucket missing from
|
||||
`[order] buckets` is an error: the mod then falls back as if Steam could not be reached.
|
||||
|
||||
## While the server runs
|
||||
|
||||
@@ -121,8 +134,9 @@ change:
|
||||
|
||||
- how the collection differs from what the server runs: items or Mod IDs added, removed, or in
|
||||
another order, a different `Map=`;
|
||||
- items that were updated on Steam after the server started. Clients that download the new
|
||||
version may not be able to join until the server restarts and downloads it too.
|
||||
- items with a newer version on Steam than the one the server downloaded. Clients that
|
||||
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.
|
||||
|
||||
@@ -145,6 +159,9 @@ download (see ZomboidForge's mod development guide).
|
||||
```shell
|
||||
./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)
|
||||
|
||||
# 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
|
||||
@@ -152,6 +169,11 @@ 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
|
||||
`config.toml` there.
|
||||
|
||||
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
|
||||
`-` (e.g. `v0.2.0-rc.1`) and tags on commits that are not on `master` are built and tested but
|
||||
not released.
|
||||
|
||||
## License
|
||||
|
||||
[GNU Affero General Public License v3.0](LICENSE)
|
||||
+13
-12
@@ -1,15 +1,7 @@
|
||||
plugins {
|
||||
id("dev.overlord.zomboidforge.mod") version "0.4.0" // the plugin's version is the ZomboidForge API version
|
||||
}
|
||||
|
||||
version = "0.1.0"
|
||||
|
||||
// id, name, version, and entry point: settings.gradle.kts
|
||||
zomboidForge {
|
||||
id = "lua_mod_automator"
|
||||
name = "LuaModAutomator"
|
||||
entrypoint = "dev.overlord.luamodautomator.LuaModAutomatorMod"
|
||||
game("42") // ServerOptions, GameServer, CommandBase
|
||||
serverImage = "git.security-command.org/overlord/zomboidforge:0.4.0-pz42.21"
|
||||
game("42") // ServerOptions, GameServer, SteamWorkshop, CommandBase
|
||||
serverImage = "git.security-command.org/overlord/zomboidforge:0.6.0-pz42.21"
|
||||
}
|
||||
|
||||
dependencies {
|
||||
@@ -19,7 +11,7 @@ dependencies {
|
||||
testCompileOnly("org.jetbrains:annotations:26.0.2")
|
||||
|
||||
// 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("org.junit.jupiter:junit-jupiter")
|
||||
@@ -39,3 +31,12 @@ tasks.withType<JavaCompile>().configureEach {
|
||||
tasks.test {
|
||||
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"))
|
||||
}
|
||||
Executable
+230
@@ -0,0 +1,230 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# Builds the mod for the v* git tag on HEAD and publishes it as a Gitea release, with the zip
|
||||
# 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.
|
||||
#
|
||||
# A pre-release tag (containing "-", e.g. v0.2.0-rc.1), or a tag on a commit that is not on
|
||||
# master, is built and tested but not released. The tag must match the version in
|
||||
# settings.gradle.kts.
|
||||
#
|
||||
# Usage:
|
||||
# ci/release.sh build downloads the game jar and builds the mod (tests and checkMod included)
|
||||
# ci/release.sh publish creates the release (or reuses the tag's release) and uploads the zip
|
||||
#
|
||||
# Environment:
|
||||
# GAME_JAR projectzomboid.jar to build against (build); default: downloaded from
|
||||
# the Steam branch PZ_BRANCH (default: public) with DepotDownloader
|
||||
# GITEA_TOKEN token with write access to the repository's releases (publish)
|
||||
# GITHUB_API_URL Gitea API, e.g. https://git.security-command.org/api/v1 (publish; set by Gitea Actions)
|
||||
# GITHUB_REPOSITORY owner/repo (publish; set by Gitea Actions)
|
||||
|
||||
set -o errexit
|
||||
set -o nounset
|
||||
set -o pipefail
|
||||
shopt -s inherit_errexit
|
||||
|
||||
REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
readonly REPO_ROOT
|
||||
|
||||
readonly MOD_ID="lua_mod_automator"
|
||||
readonly RELEASE_BRANCH="master"
|
||||
readonly WORK_DIR="${REPO_ROOT}/build/ci"
|
||||
|
||||
# DepotDownloader downloads single files of a depot; steamcmd only whole apps. Same release
|
||||
# and checksum as ZomboidForge's image build.
|
||||
readonly DEPOT_DOWNLOADER_URL="https://github.com/SteamRE/DepotDownloader/releases/download/DepotDownloader_3.4.0/DepotDownloader-linux-x64.zip"
|
||||
readonly DEPOT_DOWNLOADER_SHA256="a999dec66b4850fc961bd50366696d23c2d0fad7b18790e6a5647b2f19097a53"
|
||||
|
||||
# Project Zomboid Dedicated Server: app and its depot with java/projectzomboid.jar.
|
||||
readonly PZ_APP="380870"
|
||||
readonly PZ_DEPOT="380871"
|
||||
|
||||
log() {
|
||||
echo "[release] $*" >&2
|
||||
}
|
||||
|
||||
fail() {
|
||||
log "$*"
|
||||
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.
|
||||
release_tag() {
|
||||
git -C "${REPO_ROOT}" describe --tags --exact-match --match 'v*' 2> /dev/null || true
|
||||
}
|
||||
|
||||
run_gradle() {
|
||||
"${REPO_ROOT}/gradlew" --no-daemon --console=plain --project-dir "${REPO_ROOT}" "$@"
|
||||
}
|
||||
|
||||
# Prints the mod's version: the `version = "..."` line of zomboidForge { } in settings.gradle.kts.
|
||||
# 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.
|
||||
download_game_jar() {
|
||||
local branch="${PZ_BRANCH:-public}"
|
||||
local tools="${WORK_DIR}/depotdownloader"
|
||||
local game="${WORK_DIR}/game"
|
||||
|
||||
mkdir --parents "${tools}" "${game}"
|
||||
|
||||
log "Downloading DepotDownloader"
|
||||
curl --fail --silent --show-error --location --output "${tools}/depotdownloader.zip" "${DEPOT_DOWNLOADER_URL}"
|
||||
echo "${DEPOT_DOWNLOADER_SHA256} ${tools}/depotdownloader.zip" | sha256sum --check --quiet
|
||||
unzip -q -o "${tools}/depotdownloader.zip" -d "${tools}"
|
||||
chmod +x "${tools}/DepotDownloader"
|
||||
|
||||
log "Downloading projectzomboid.jar of the Steam branch '${branch}'"
|
||||
echo "java/projectzomboid.jar" > "${tools}/files"
|
||||
"${tools}/DepotDownloader" -app "${PZ_APP}" -depot "${PZ_DEPOT}" -branch "${branch}" -filelist "${tools}/files" -dir "${game}" >&2
|
||||
|
||||
echo "${game}/java/projectzomboid.jar"
|
||||
}
|
||||
|
||||
build() {
|
||||
local tag="$1"
|
||||
local version="${tag#v}"
|
||||
local project
|
||||
local game_jar="${GAME_JAR:-}"
|
||||
|
||||
project="$(mod_version)"
|
||||
if [[ -z "${project}" ]]; then
|
||||
fail "No version line in settings.gradle.kts."
|
||||
fi
|
||||
if [[ "${project}" != "${version}" ]]; then
|
||||
fail "The tag '${tag}' does not match the version '${project}' in settings.gradle.kts."
|
||||
fi
|
||||
|
||||
if [[ -z "${game_jar}" ]]; then
|
||||
game_jar="$(download_game_jar)"
|
||||
fi
|
||||
|
||||
log "Building ${MOD_ID} ${version} against '${game_jar}'"
|
||||
run_gradle "-Pzomboidforge.gameJar=${game_jar}" build
|
||||
}
|
||||
|
||||
# Calls the Gitea API; prints the response body. Extra arguments go to curl.
|
||||
api() {
|
||||
local method="$1"
|
||||
local path="$2"
|
||||
shift 2
|
||||
|
||||
curl --fail --silent --show-error \
|
||||
--request "${method}" \
|
||||
--header "Authorization: token ${GITEA_TOKEN}" \
|
||||
--header "Accept: application/json" \
|
||||
"$@" \
|
||||
"${GITHUB_API_URL}/repos/${GITHUB_REPOSITORY}${path}"
|
||||
}
|
||||
|
||||
# Prints the id of the tag's release, created when it does not exist yet.
|
||||
release_id() {
|
||||
local tag="$1"
|
||||
local status
|
||||
local body
|
||||
|
||||
status="$(curl --silent --output /dev/null --write-out '%{http_code}' \
|
||||
--header "Authorization: token ${GITEA_TOKEN}" \
|
||||
"${GITHUB_API_URL}/repos/${GITHUB_REPOSITORY}/releases/tags/${tag}")"
|
||||
|
||||
case "${status}" in
|
||||
200)
|
||||
log "Release '${tag}' exists; replacing its files"
|
||||
api GET "/releases/tags/${tag}" | jq --raw-output '.id'
|
||||
return
|
||||
;;
|
||||
404)
|
||||
;;
|
||||
*)
|
||||
fail "Cannot read the releases of '${GITHUB_REPOSITORY}' (HTTP ${status}); is GITEA_TOKEN valid for it?"
|
||||
;;
|
||||
esac
|
||||
|
||||
body="$(jq --null-input \
|
||||
--arg tag "${tag}" \
|
||||
--arg name "Release ${tag} - Stable, Automated" \
|
||||
--arg body "$(date --utc +%Y-%m-%d)"$'\n'"$(git -C "${REPO_ROOT}" rev-parse HEAD)" \
|
||||
'{tag_name: $tag, name: $name, body: $body, draft: false, prerelease: false}')"
|
||||
|
||||
log "Creating release '${tag}'"
|
||||
api POST "/releases" --header "Content-Type: application/json" --data "${body}" | jq --raw-output '.id'
|
||||
}
|
||||
|
||||
# Uploads ${file} as ${name}, replacing an attached file of that name.
|
||||
upload() {
|
||||
local id="$1"
|
||||
local file="$2"
|
||||
local name="$3"
|
||||
local existing
|
||||
|
||||
existing="$(api GET "/releases/${id}/assets" | jq --raw-output --arg name "${name}" '.[] | select(.name == $name) | .id')"
|
||||
if [[ -n "${existing}" ]]; then
|
||||
api DELETE "/releases/${id}/assets/${existing}" > /dev/null
|
||||
fi
|
||||
|
||||
api POST "/releases/${id}/assets?name=${name}" --form "attachment=@${file}" > /dev/null
|
||||
log "Attached '${name}'"
|
||||
}
|
||||
|
||||
publish() {
|
||||
local tag="$1"
|
||||
local version="${tag#v}"
|
||||
local zip="${REPO_ROOT}/build/distributions/${MOD_ID}-${version}.zip"
|
||||
local id
|
||||
|
||||
if [[ "${version}" == *-* ]]; then
|
||||
log "${tag} is a pre-release tag; nothing is released."
|
||||
return
|
||||
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}"
|
||||
: "${GITHUB_API_URL:?GITHUB_API_URL is not set}"
|
||||
: "${GITHUB_REPOSITORY:?GITHUB_REPOSITORY is not set}"
|
||||
|
||||
[[ -f "${zip}" ]] || fail "'${zip}' does not exist; run 'ci/release.sh build' first."
|
||||
|
||||
id="$(release_id "${tag}")"
|
||||
upload "${id}" "${zip}" "${MOD_ID}-${version}.zip"
|
||||
upload "${id}" "${zip}" "${MOD_ID}.zip"
|
||||
|
||||
log "Released ${tag}: ${GITHUB_SERVER_URL:-}/${GITHUB_REPOSITORY}/releases/tag/${tag}"
|
||||
}
|
||||
|
||||
main() {
|
||||
local step="${1:-}"
|
||||
local tag
|
||||
|
||||
tag="$(release_tag)"
|
||||
if [[ -z "${tag}" ]]; then
|
||||
fail "HEAD has no v* git tag (not a release commit, or a shallow clone without tags?); nothing to release."
|
||||
fi
|
||||
|
||||
case "${step}" in
|
||||
build)
|
||||
build "${tag}"
|
||||
;;
|
||||
publish)
|
||||
publish "${tag}"
|
||||
;;
|
||||
*)
|
||||
log "Usage: ci/release.sh build|publish"
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
main "$@"
|
||||
+9
-10
@@ -1,15 +1,14 @@
|
||||
pluginManagement {
|
||||
repositories {
|
||||
maven("https://git.security-command.org/api/packages/overlord/maven")
|
||||
gradlePluginPortal()
|
||||
}
|
||||
repositories { maven("https://git.security-command.org/api/packages/overlord/maven") }
|
||||
}
|
||||
|
||||
dependencyResolutionManagement {
|
||||
repositories {
|
||||
maven("https://git.security-command.org/api/packages/overlord/maven")
|
||||
mavenCentral()
|
||||
}
|
||||
plugins {
|
||||
id("dev.overlord.zomboidforge") version "0.6.0" // the plugin's version is the ZomboidForge API version
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
import dev.overlord.zomboidforge.api.annotations.RegisterCommand;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
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
|
||||
* 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}.
|
||||
* ZomboidForge registers it before {@link LuaModAutomatorMod#onLoad()}.
|
||||
*/
|
||||
@RegisterCommand
|
||||
@CommandName(name = "collection")
|
||||
@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)
|
||||
|
||||
@@ -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.");
|
||||
}
|
||||
|
||||
// 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())
|
||||
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()));
|
||||
|
||||
// All pinned items out first: removing one later would shift those placed before it.
|
||||
ordered.removeAll(pinned);
|
||||
|
||||
for (String id : pinned)
|
||||
{
|
||||
ordered.remove(id);
|
||||
ordered.add(Math.clamp(overrides.get(id).position().orElseThrow() - 1, 0, ordered.size()), id);
|
||||
}
|
||||
|
||||
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)
|
||||
{
|
||||
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 (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)
|
||||
{
|
||||
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 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 SEPARATOR = Pattern.compile("[\\s,;]+");
|
||||
private static final Pattern MOD_ID = Pattern.compile("[A-Za-z0-9_.\\-]+");
|
||||
private static final Pattern SEPARATOR = Pattern.compile("[,;]");
|
||||
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() {}
|
||||
|
||||
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)
|
||||
{
|
||||
Set<String> modIds = new LinkedHashSet<>();
|
||||
@@ -33,9 +42,20 @@ final class DescriptionParser
|
||||
|
||||
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
|
||||
* {@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()}
|
||||
* and {@link CollectionCommand}; drift checks on the mod thread.
|
||||
* <p>Threads: game objects ({@code ServerOptions}, {@code SteamWorkshop}) on the main thread
|
||||
* only, in {@link #onLoad()}, {@link #onServerStarted()}, and {@link CollectionCommand}; drift
|
||||
* checks on the mod thread.
|
||||
*/
|
||||
public final class LuaModAutomatorMod extends Mod
|
||||
{
|
||||
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 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 Duration RETRY_DELAY = Duration.ofSeconds(2);
|
||||
|
||||
/** The loaded instance, for {@link CollectionCommand}, which Project Zomboid creates. */
|
||||
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 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.
|
||||
private @Nullable Settings settings;
|
||||
private @Nullable String collectionId;
|
||||
@@ -73,7 +83,6 @@ public final class LuaModAutomatorMod extends Mod
|
||||
public void onLoad()
|
||||
{
|
||||
LuaModAutomatorMod.instance = this;
|
||||
this.commands().register(CollectionCommand.class);
|
||||
|
||||
this.running = ServerOptionsAdapter.read();
|
||||
|
||||
@@ -115,7 +124,7 @@ public final class LuaModAutomatorMod extends Mod
|
||||
|
||||
try
|
||||
{
|
||||
Resolution resolution = this.resolve();
|
||||
Resolution resolution = this.resolveAtStartup();
|
||||
ServerValues values = resolution.values(settings.ini().baseMap());
|
||||
|
||||
this.logWarnings(resolution.warnings());
|
||||
@@ -128,10 +137,14 @@ public final class LuaModAutomatorMod extends Mod
|
||||
}
|
||||
catch (SteamException | ConfigurationException e)
|
||||
{
|
||||
String reason = Objects.requireNonNullElse(e.getMessage(), e.getClass().getSimpleName());
|
||||
|
||||
this.log(WARNING, "Cannot resolve collection '" + this.collectionId + "': " + reason);
|
||||
this.fallBack(reason.endsWith(".") ? reason.substring(0, reason.length() - 1) : reason);
|
||||
this.log(WARNING, "Cannot resolve collection '" + this.collectionId + "': " + LuaModAutomatorMod.reason(e) + ".");
|
||||
this.fallBack(LuaModAutomatorMod.reason(e));
|
||||
}
|
||||
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);
|
||||
@@ -141,7 +154,18 @@ public final class LuaModAutomatorMod extends Mod
|
||||
public void onServerStarted()
|
||||
{
|
||||
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());
|
||||
this.modThread().scheduleWithFixedDelay(this::scheduledCheck, interval, interval);
|
||||
@@ -272,7 +296,7 @@ public final class LuaModAutomatorMod extends Mod
|
||||
|
||||
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.")
|
||||
+ (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)
|
||||
{
|
||||
@@ -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)};
|
||||
* logs each update once. Mod thread.
|
||||
* Items the server runs that have a newer version on Steam than the installed one (or, when
|
||||
* Steam does not report it, than {@link #startedAt}), as {@code 'title' (id)}; logs each
|
||||
* update once. Mod thread.
|
||||
*/
|
||||
private List<String> updatedItems(Resolution resolution)
|
||||
{
|
||||
Set<String> running = new HashSet<>(this.running.workshopIds());
|
||||
List<String> updated = new ArrayList<>();
|
||||
Set<String> running = new HashSet<>(this.running.workshopIds());
|
||||
Map<String, Long> installed = this.installed;
|
||||
List<String> updated = new ArrayList<>();
|
||||
|
||||
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() + ")";
|
||||
updated.add(name);
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@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
|
||||
{
|
||||
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); }
|
||||
|
||||
/** 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)
|
||||
{
|
||||
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()
|
||||
{
|
||||
// Widths start at 1: "%-0s" is not a valid format.
|
||||
List<String> lines = new ArrayList<>();
|
||||
int number = String.valueOf(this.items.size()).length();
|
||||
int title = 0;
|
||||
int modIds = 0;
|
||||
int title = 1;
|
||||
int modIds = 1;
|
||||
|
||||
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());
|
||||
}
|
||||
|
||||
lines.add("# Mod list");
|
||||
lines.add("Mod List:");
|
||||
|
||||
for (int i = 0; i < this.items.size(); 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())
|
||||
{
|
||||
lines.add("# Excluded");
|
||||
for (Item item : this.excluded) lines.add("# %s %s".formatted(item.title(), item.id()));
|
||||
lines.add("Excluded:");
|
||||
for (Item item : this.excluded) lines.add(" %s %s".formatted(item.title(), item.id()));
|
||||
}
|
||||
|
||||
return lines;
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package dev.overlord.luamodautomator;
|
||||
|
||||
import dev.overlord.zomboidforge.api.annotations.Min;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
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) {}
|
||||
|
||||
/** @param timeoutS seconds per Steam Web API request */
|
||||
record Steam(int timeoutS)
|
||||
{
|
||||
Steam
|
||||
{
|
||||
if (timeoutS < 1) throw new IllegalArgumentException("'timeout_s' must be at least 1, found " + timeoutS);
|
||||
}
|
||||
}
|
||||
record Steam(@Min(1) int timeoutS) {}
|
||||
|
||||
/** @param intervalMin minutes between drift checks while the server runs; 0 turns them off */
|
||||
record Drift(int intervalMin)
|
||||
{
|
||||
Drift
|
||||
{
|
||||
if (intervalMin < 0) throw new IllegalArgumentException("'interval_min' must be 0 or more, found " + intervalMin);
|
||||
}
|
||||
}
|
||||
record Drift(@Min(0) int intervalMin) {}
|
||||
|
||||
/**
|
||||
* @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 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());
|
||||
|
||||
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); }
|
||||
|
||||
/** 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. */
|
||||
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 URI base;
|
||||
@@ -59,11 +60,19 @@ final class SteamWorkshopApi implements AutoCloseable
|
||||
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)
|
||||
{
|
||||
Matcher matcher = SteamWorkshopApi.COLLECTION_ID.matcher(setting.strip());
|
||||
return matcher.find() ? Optional.of(matcher.group(1)) : Optional.empty();
|
||||
String value = setting.strip();
|
||||
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
|
||||
* from a public Steam Workshop collection, resolved at every start.
|
||||
*
|
||||
* <p>Only {@link dev.overlord.luamodautomator.LuaModAutomatorMod},
|
||||
* {@link dev.overlord.luamodautomator.ServerOptionsAdapter}, and
|
||||
* {@link dev.overlord.luamodautomator.CollectionCommand} use game classes; everything else runs
|
||||
* without the game.
|
||||
* <p>Only
|
||||
* {@link dev.overlord.luamodautomator.LuaModAutomatorMod},
|
||||
* {@link dev.overlord.luamodautomator.ServerOptionsAdapter},
|
||||
* {@link dev.overlord.luamodautomator.WorkshopAdapter}, and
|
||||
* {@link dev.overlord.luamodautomator.CollectionCommand} use game classes;
|
||||
* everything else runs without the game.
|
||||
*
|
||||
* @noinspection UnstableApiUsage, RedundantSuppression
|
||||
*/
|
||||
|
||||
@@ -73,7 +73,24 @@ class CollectionResolverTest
|
||||
|
||||
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
|
||||
@@ -169,6 +186,28 @@ class CollectionResolverTest
|
||||
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
|
||||
void mapFoldersThenBaseMapEachOnce() throws ConfigurationException
|
||||
{
|
||||
@@ -190,16 +229,25 @@ class CollectionResolverTest
|
||||
List<String> modList = CollectionResolver.resolve(CollectionResolverTest.COLLECTION, CollectionResolverTest.DEFAULT_ORDER, items).modList();
|
||||
|
||||
assertEquals(List.of(
|
||||
"# Mod list",
|
||||
"# 1. A Map 300 MapMod",
|
||||
"# 2. Framework 200 Frame",
|
||||
"# 3. Misc One 100 MiscOne",
|
||||
"# 4. Misc Two 400 MiscTwo, MiscTwoExtra",
|
||||
"# Excluded",
|
||||
"# Misc Three 500"
|
||||
"Mod List:",
|
||||
"1. A Map 300 MapMod",
|
||||
"2. Framework 200 Frame",
|
||||
"3. Misc One 100 MiscOne",
|
||||
"4. Misc Two 400 MiscTwo, MiscTwoExtra",
|
||||
"Excluded:",
|
||||
" Misc Three 500"
|
||||
), 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 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"));
|
||||
}
|
||||
|
||||
@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
|
||||
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
|
||||
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("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<>()); }
|
||||
|
||||
/** 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/?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.empty(), SteamWorkshopApi.collectionId("my collection"));
|
||||
assertEquals(Optional.empty(), SteamWorkshopApi.collectionId("https://steamcommunity.com/sharedfiles/filedetails/?tscn=1712345678"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -109,9 +111,9 @@ class SteamWorkshopApiTest
|
||||
Settings settings = SettingsTest.bind("");
|
||||
Resolution resolution = CollectionResolver.resolve(this.api.collection(SteamWorkshopApiTest.recordedId(), new ArrayList<>()), settings.order(), settings.items());
|
||||
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("WorkshopItems=" + values.workshopItems());
|
||||
|
||||
@@ -207,6 +209,9 @@ class SteamWorkshopApiTest
|
||||
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>}. */
|
||||
private static Response details(Map<String, String> form)
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user