diff --git a/.forgejo/workflows/guild-cookbook.yml b/.forgejo/workflows/guild-cookbook.yml new file mode 100644 index 00000000..5dca9e92 --- /dev/null +++ b/.forgejo/workflows/guild-cookbook.yml @@ -0,0 +1,54 @@ +name: Guild and Cookbook Overlay +on: + workflow_dispatch: + push: + branches: ['fix/guild-navigator-*'] + +jobs: + guild-cookbook: + runs-on: dune-ci + steps: + - name: Check out exact revision + shell: bash + env: + REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + git init . + git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/plugins.git "$GITHUB_SHA" + git checkout --detach FETCH_HEAD + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '21' + - uses: gradle/actions/setup-gradle@v4 + with: + gradle-version: '9.2.1' + - name: Test and package exact overlay donors + shell: bash + run: | + set -euo pipefail + for module in DuneRealmsGUI DuneNPC DuneLobby; do + gradle --no-daemon -p "$module" test jar + done + mkdir guild-cookbook + PYTHONPATH=tools python3 - <<'PY' + from pathlib import Path + from plugin_guild_cookbook import CLASSES + from plugin_wild_update import read_archive, write_archive + for module, jar in ( + ("gui", "DuneRealmsGUI/build/libs/DunerealmsGUI.jar"), + ("npc", "DuneNPC/build/libs/DuneRealms-NPC.jar"), + ("lobby", "DuneLobby/build/libs/DuneRealms-Lobby.jar"), + ): + entries = read_archive(Path(jar).read_bytes()) + Path(f"guild-cookbook/{module}.zip").write_bytes(write_archive({entry: entries[entry] for entry in CLASSES[module]})) + PY + cp tools/{GuildCookbookMerge.java,plugin_guild_cookbook.py,plugin_wild_update.py} guild-cookbook/ + printf '%s\n' "$GITHUB_SHA" > guild-cookbook/SOURCE_COMMIT + (cd guild-cookbook && sha256sum -- *.zip *.py *.java SOURCE_COMMIT > SHA256SUMS) + - uses: actions/upload-artifact@v3 + with: + name: DuneRealms-Guild-Cookbook + path: guild-cookbook + if-no-files-found: error diff --git a/tools/GuildCookbookMerge.java b/tools/GuildCookbookMerge.java new file mode 100644 index 00000000..1c8d9fc7 --- /dev/null +++ b/tools/GuildCookbookMerge.java @@ -0,0 +1,81 @@ +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; +import org.objectweb.asm.ClassReader; +import org.objectweb.asm.ClassWriter; +import org.objectweb.asm.Handle; +import org.objectweb.asm.tree.ClassNode; +import org.objectweb.asm.tree.InvokeDynamicInsnNode; +import org.objectweb.asm.tree.MethodNode; + +class GuildCookbookMerge { + private static final String GUI = "com/dunerealms/gui/"; + private static final Map> TARGETS = Map.of( + GUI + "DuneGUI", Set.of("openGuild", "guildReturnMenu"), + GUI + "OrganisationMenus", Set.of("cookbookRecipe", "recipeIngredient"), + GUI + "CookbookCatalog$Recipe", Set.of("key"), + "com/example/dunelobby/DuneLobby", Set.of("entityInteract"), + "com/example/dunenpc/DuneNPC", Set.of("navigator")); + + public static void main(String[] args) throws Exception { + if (args.length != 3) throw new IllegalArgumentException("Expected retained, donor and output classes"); + var retainedReader = new ClassReader(Files.readAllBytes(Path.of(args[0]))); + var retained = parse(retainedReader); + var donor = parse(new ClassReader(Files.readAllBytes(Path.of(args[1])))); + var targets = TARGETS.get(retained.name); + if (targets == null || !retained.name.equals(donor.name)) throw new IllegalArgumentException("Unexpected overlay class"); + var additions = new LinkedHashMap(); + var renamed = new HashMap(); + for (String target : targets.stream().sorted().toList()) { + var method = donor.methods.stream().filter(m -> m.name.equals(target)).toList(); + if (method.size() != 1) throw new IllegalArgumentException("Expected one donor method " + target); + prepare(donor, method.getFirst(), additions, renamed); + } + for (var entry : additions.entrySet()) { + var method = entry.getValue(); + if (!targets.contains(method.name) && + retained.methods.stream().anyMatch(old -> old.name.equals(method.name) && old.desc.equals(method.desc))) { + throw new IllegalArgumentException("Unexpected existing helper " + method.name); + } + retained.methods.removeIf(old -> old.name.equals(method.name) && old.desc.equals(method.desc)); + retained.methods.add(method); + } + var writer = new ClassWriter(retainedReader, 0); + retained.accept(writer); + Files.write(Path.of(args[2]), writer.toByteArray()); + } + + private static void prepare(ClassNode donor, MethodNode method, Map copies, + Map renamed) { + String key = method.name + method.desc; + if (copies.putIfAbsent(key, method) != null) return; + for (var instruction : method.instructions) { + if (!(instruction instanceof InvokeDynamicInsnNode dynamic)) continue; + for (int i = 0; i < dynamic.bsmArgs.length; i++) { + if (!(dynamic.bsmArgs[i] instanceof Handle handle) || !handle.getOwner().equals(donor.name) || + !handle.getName().startsWith("lambda$")) continue; + String original = handle.getName() + handle.getDesc(); + String replacement = renamed.get(original); + if (replacement == null) { + var helper = donor.methods.stream().filter(m -> m.name.equals(handle.getName()) && + m.desc.equals(handle.getDesc())).findFirst().orElseThrow(); + replacement = "guildCookbook$" + handle.getName(); + renamed.put(original, replacement); + helper.name = replacement; + prepare(donor, helper, copies, renamed); + } + dynamic.bsmArgs[i] = new Handle(handle.getTag(), handle.getOwner(), replacement, + handle.getDesc(), handle.isInterface()); + } + } + } + + private static ClassNode parse(ClassReader reader) { + var node = new ClassNode(); + reader.accept(node, 0); + return node; + } +} diff --git a/tools/plugin_guild_cookbook.py b/tools/plugin_guild_cookbook.py new file mode 100644 index 00000000..46f02c02 --- /dev/null +++ b/tools/plugin_guild_cookbook.py @@ -0,0 +1,53 @@ +"""Assemble reviewed Guild and Cookbook methods onto the installed plugin variants.""" +import argparse +import os +from pathlib import Path +import subprocess +from tempfile import TemporaryDirectory + +from plugin_wild_update import digest, read_archive, write_archive + +CLASSES = { + "gui": ( + "com/dunerealms/gui/DuneGUI.class", + "com/dunerealms/gui/OrganisationMenus.class", + "com/dunerealms/gui/CookbookCatalog$Recipe.class", + ), + "npc": ("com/example/dunenpc/DuneNPC.class",), + "lobby": ("com/example/dunelobby/DuneLobby.class",), +} + + +def assemble(module, baseline, baseline_sha, donor, donor_sha, output, classpath): + baseline_bytes = baseline.read_bytes() + donor_bytes = donor.read_bytes() + if digest(baseline_bytes) != baseline_sha or digest(donor_bytes) != donor_sha: + raise ValueError("Unexpected baseline or donor checksum") + retained = read_archive(baseline_bytes) + compiled = read_archive(donor_bytes) + java_home = os.environ.get("JAVA_HOME") + executable = "java.exe" if os.name == "nt" else "java" + java = str(Path(java_home) / "bin" / executable) if java_home else executable + helper = Path(__file__).with_name("GuildCookbookMerge.java") + with TemporaryDirectory() as temporary: + temp = Path(temporary) + for index, entry in enumerate(CLASSES[module]): + old, new, merged = (temp / f"{index}-{name}.class" for name in ("retained", "donor", "merged")) + old.write_bytes(retained[entry]) + new.write_bytes(compiled[entry]) + subprocess.run([java, "--class-path", classpath, str(helper), str(old), str(new), str(merged)], check=True) + retained[entry] = merged.read_bytes() + with output.open("xb") as candidate: + candidate.write(write_archive(retained)) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("module", choices=CLASSES) + parser.add_argument("baseline", type=Path) + parser.add_argument("baseline_sha") + parser.add_argument("donor", type=Path) + parser.add_argument("donor_sha") + parser.add_argument("output", type=Path) + parser.add_argument("classpath", help="ASM core and tree JARs") + assemble(**vars(parser.parse_args()))