Preserve station output origins and allow protected iron-door interaction #83

Merged
unimatrix merged 3 commits from fix/station-origins-c555 into main 2026-12-05 16:08:25 +01:00
12 changed files with 447 additions and 15 deletions

View file

@ -0,0 +1,51 @@
name: Station Origins and Iron Doors Overlay
on:
workflow_dispatch:
push:
branches: ['fix/station-origins-*']
jobs:
station-and-doors:
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 both plugins and extract exact overlay donors
shell: bash
run: |
set -euo pipefail
gradle --no-daemon -p JarvisConnector test jar
gradle --no-daemon -p DuneEss test jar
mkdir station-and-doors
PYTHONPATH=tools python3 - <<'PY'
from pathlib import Path
from plugin_station_and_doors import donor_archive
output = Path("station-and-doors")
for role, jar in (
("station", "JarvisConnector/build/libs/jarvistranslator.jar"),
("ess", "DuneEss/build/libs/DuneRealms-Essentials.jar"),
):
(output / (role + "-donor.zip")).write_bytes(donor_archive(role, Path(jar)))
PY
cp tools/{StationAndDoorOverlay.java,plugin_station_and_doors.py,plugin_wild_update.py} station-and-doors/
printf '%s\n' "$GITHUB_SHA" > station-and-doors/SOURCE_COMMIT
(cd station-and-doors && sha256sum -- *.zip *.py *.java SOURCE_COMMIT > SHA256SUMS)
- uses: actions/upload-artifact@v3
with:
name: DuneRealms-Station-Origins-Iron-Doors
path: station-and-doors
if-no-files-found: error

View file

@ -90,6 +90,7 @@ public final class DuneEss extends JavaPlugin implements CommandExecutor, TabCom
command.setExecutor(this);
command.setTabCompleter(this);
getServer().getPluginManager().registerEvents(this, this);
getServer().getPluginManager().registerEvents(new IronDoorInteraction(), this);
basics=new EssentialsBasics(this);
basics.register();
StaffItemTools.start(this);

View file

@ -0,0 +1,45 @@
package com.example.duneess;
import org.bukkit.GameMode;
import org.bukkit.Material;
import org.bukkit.SoundCategory;
import org.bukkit.block.BlockFace;
import org.bukkit.block.data.Bisected;
import org.bukkit.block.data.type.Door;
import org.bukkit.event.Event;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.EquipmentSlot;
/** Give iron doors a manual interaction while retaining their redstone behavior. */
final class IronDoorInteraction implements Listener {
@EventHandler(priority = EventPriority.HIGHEST)
public void interact(PlayerInteractEvent event) {
if (event.getAction() != Action.RIGHT_CLICK_BLOCK || event.getHand() != EquipmentSlot.HAND
|| event.useInteractedBlock() == Event.Result.DENY) return;
var clicked = event.getClickedBlock();
if (clicked == null || clicked.getType() != Material.IRON_DOOR
|| !(clicked.getBlockData() instanceof Door door)) return;
var player = event.getPlayer();
if (player.getGameMode() == GameMode.SPECTATOR) return;
if (player.isSneaking() && (!player.getInventory().getItemInMainHand().isEmpty()
|| !player.getInventory().getItemInOffHand().isEmpty())) return;
var other = clicked.getRelative(door.getHalf() == Bisected.Half.TOP ? BlockFace.DOWN : BlockFace.UP);
if (other.getType() != Material.IRON_DOOR || !(other.getBlockData() instanceof Door otherDoor)
|| otherDoor.getHalf() == door.getHalf()) return;
boolean open = !door.isOpen();
door.setOpen(open);
otherDoor.setOpen(open);
clicked.setBlockData(door, false);
other.setBlockData(otherDoor, false);
clicked.getWorld().playSound(clicked.getLocation().add(.5, .5, .5),
open ? "minecraft:block.iron_door.open" : "minecraft:block.iron_door.close",
SoundCategory.BLOCKS, 1, 1);
event.setUseInteractedBlock(Event.Result.DENY);
event.setUseItemInHand(Event.Result.DENY);
}
}

View file

@ -0,0 +1,84 @@
package com.example.duneess;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.SoundCategory;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.data.Bisected;
import org.bukkit.block.data.type.Door;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.EquipmentSlot;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
class IronDoorInteractionTest {
private final IronDoorInteraction listener = new IronDoorInteraction();
private final PlayerInteractEvent event = mock(PlayerInteractEvent.class);
private final Player player = mock(Player.class);
private final Block upper = mock(Block.class);
private final Block lower = mock(Block.class);
private final Door top = mock(Door.class);
private final Door bottom = mock(Door.class);
private final World world = mock(World.class);
@BeforeEach void door() {
when(event.getAction()).thenReturn(Action.RIGHT_CLICK_BLOCK);
when(event.getHand()).thenReturn(EquipmentSlot.HAND);
when(event.useInteractedBlock()).thenReturn(Event.Result.DEFAULT);
when(event.getPlayer()).thenReturn(player);
when(player.getGameMode()).thenReturn(GameMode.SURVIVAL);
when(upper.getType()).thenReturn(Material.IRON_DOOR);
when(lower.getType()).thenReturn(Material.IRON_DOOR);
when(upper.getBlockData()).thenReturn(top);
when(lower.getBlockData()).thenReturn(bottom);
when(top.getHalf()).thenReturn(Bisected.Half.TOP);
when(bottom.getHalf()).thenReturn(Bisected.Half.BOTTOM);
when(upper.getRelative(BlockFace.DOWN)).thenReturn(lower);
when(lower.getRelative(BlockFace.UP)).thenReturn(upper);
when(upper.getWorld()).thenReturn(world);
when(lower.getWorld()).thenReturn(world);
when(upper.getLocation()).thenReturn(new Location(world, 1, 2, 1));
when(lower.getLocation()).thenReturn(new Location(world, 1, 1, 1));
}
@Test void topClickOpensBothHalvesWithoutChangingPower() {
when(event.getClickedBlock()).thenReturn(upper);
listener.interact(event);
verify(top).setOpen(true);
verify(bottom).setOpen(true);
verify(top, never()).setPowered(anyBoolean());
verify(bottom, never()).setPowered(anyBoolean());
verify(upper).setBlockData(top, false);
verify(lower).setBlockData(bottom, false);
verify(world).playSound(any(Location.class), eq("minecraft:block.iron_door.open"), eq(SoundCategory.BLOCKS), eq(1f), eq(1f));
verify(event).setUseItemInHand(Event.Result.DENY);
}
@Test void bottomClickClosesBothHalves() {
when(event.getClickedBlock()).thenReturn(lower);
when(bottom.isOpen()).thenReturn(true);
listener.interact(event);
verify(top).setOpen(false);
verify(bottom).setOpen(false);
verify(world).playSound(any(Location.class), eq("minecraft:block.iron_door.close"), eq(SoundCategory.BLOCKS), eq(1f), eq(1f));
}
@Test void protectedAndOffHandClicksNeverToggle() {
when(event.getClickedBlock()).thenReturn(upper);
when(event.useInteractedBlock()).thenReturn(Event.Result.DENY);
listener.interact(event);
when(event.useInteractedBlock()).thenReturn(Event.Result.DEFAULT);
when(event.getHand()).thenReturn(EquipmentSlot.OFF_HAND);
listener.interact(event);
verifyNoInteractions(top, bottom, world);
}
}

View file

@ -46,10 +46,7 @@ final class ArrakisBrewing implements Listener {
}
@EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=true) public void brewed(BrewEvent event){
String world=event.getBlock().getWorld().getName();
if(!spice(event.getContents().getIngredient())){
// Ordinary brewing is left intact; record the world of newly brewed potions.
for(var result:event.getResults())if(result!=null&&!result.isEmpty())ItemOrigin.created(result,world);return;
}
if(!spice(event.getContents().getIngredient()))return;
if(water==null||life==null)return;
if(!arrakis(world)){for(int i=0;i<3;i++)if(vial(event.getContents().getItem(i),"blood_vial")||boostable(event.getContents().getItem(i))){event.setCancelled(true);return;}return;}
for(int i=0;i<3&&i<event.getResults().size();i++){

View file

@ -0,0 +1,72 @@
package com.dunerealms.jarvis;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.data.Levelled;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.ItemSpawnEvent;
import org.bukkit.event.inventory.HopperInventorySearchEvent;
import org.bukkit.inventory.BlockInventoryHolder;
import org.bukkit.inventory.ItemStack;
/** Tags native composter output at creation or before the hopper takes it. */
final class ComposterOrigins implements Listener {
private static final StackWalker STACK = StackWalker.getInstance();
private static final String COMPOSTER = "net.minecraft.world.level.block.ComposterBlock";
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void dropped(ItemSpawnEvent event) {
var entity = event.getEntity();
var output = entity.getItemStack();
if (!boneMeal(output) || !nativeExtraction()) return;
// The native composter spawns the result 1.01 above its bottom, inside its horizontal footprint.
var location = entity.getLocation();
var source = location.getWorld().getBlockAt(location.getBlockX(), location.getBlockY() - 1, location.getBlockZ());
if (!ready(source)) return;
var marked = marked(output, source);
if (!marked.equals(output)) entity.setItemStack(marked);
}
@EventHandler(priority = EventPriority.MONITOR)
public void hopper(HopperInventorySearchEvent event) {
if (event.getContainerType() != HopperInventorySearchEvent.ContainerType.SOURCE) return;
var source = event.getSearchBlock();
var inventory = event.getInventory();
if (inventory == null || !ready(source) || inventory.getSize() != 1
|| !(inventory.getHolder() instanceof BlockInventoryHolder holder)
|| !source.equals(holder.getBlock())) return;
var output = inventory.getItem(0);
if (!boneMeal(output)) return;
var marked = marked(output, source);
// Paper's composter output container only empties the block when its slot becomes empty.
// Leave the native extraction, inventory capacity and protection checks in control.
if (!marked.equals(output)) inventory.setItem(0, marked);
}
private static boolean nativeExtraction() {
return STACK.walk(frames -> {
var enclosingCalls = frames.filter(frame ->
frame.getClassName().equals(COMPOSTER) && frame.getMethodName().equals("extractProduce")
|| frame.getClassName().equals("org.bukkit.craftbukkit.event.CraftEventFactory")
&& frame.getMethodName().equals("callItemSpawnEvent")).limit(2).toList();
return enclosingCalls.size() == 2 && enclosingCalls.get(1).getClassName().equals(COMPOSTER);
});
}
private static boolean ready(Block block) {
return block.getType() == Material.COMPOSTER && block.getBlockData() instanceof Levelled level
&& level.getLevel() == level.getMaximumLevel();
}
private static boolean boneMeal(ItemStack item) {
return item != null && item.getType() == Material.BONE_MEAL && item.getAmount() == 1;
}
private static ItemStack marked(ItemStack original, Block source) {
var output = original.clone();
ItemOrigin.created(output, source.getWorld().getName());
return output;
}
}

View file

@ -11,6 +11,10 @@ final class ItemOrigin {
static void configure(String value){server=value;}
static String label(String value){
if("jarvis-hq".equals(value))return "J.A.R.V.I.S. HQ";
if("lobby_base".equals(value))return "Lobby";
if("lobby_base_nether".equals(value))return "Lobby · Nether";
if("lobby_base_the_end".equals(value))return "Lobby · The End";
if("lobby_arrakis".equals(value))return "Arrakis build world";
String profile=PlanetItemArtwork.profile(value);
if(profile==null)return null;
return switch(profile){

View file

@ -30,10 +30,10 @@ final class ItemOriginRemainders implements Listener {
private record Burn(FurnaceBurnEvent event, FurnaceInventory inventory, String origin) {}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void fillLava(PlayerBucketFillEvent event) {
public void fillBucket(PlayerBucketFillEvent event) {
ItemStack result = event.getItemStack();
var source = event.getBlock();
if (result == null || !lavaPickup(event.getBucket(), source.getType(), result.getType())) return;
if (result == null || !bucketPickup(event.getBucket(), source.getType(), result.getType())) return;
var meta = result.getItemMeta();
if (meta == null || meta.getPersistentDataContainer().has(ItemOrigin.WORLD)) return;
@ -49,9 +49,11 @@ final class ItemOriginRemainders implements Listener {
event.setItemStack(tagged);
}
static boolean lavaPickup(Material held, Material source, Material result) {
return held == Material.BUCKET && result == Material.LAVA_BUCKET
&& (source == Material.LAVA || source == Material.LAVA_CAULDRON);
static boolean bucketPickup(Material held, Material source, Material result) {
if (held != Material.BUCKET) return false;
return result == Material.LAVA_BUCKET && (source == Material.LAVA || source == Material.LAVA_CAULDRON)
|| result == Material.WATER_BUCKET && (source == Material.WATER || source == Material.WATER_CAULDRON)
|| result == Material.POWDER_SNOW_BUCKET && (source == Material.POWDER_SNOW || source == Material.POWDER_SNOW_CAULDRON);
}
static String pickupOrigin(String previous, String world) {
@ -66,7 +68,8 @@ final class ItemOriginRemainders implements Listener {
|| !consumes(event) || !(event.getBlock().getState(false) instanceof Furnace furnace)) return;
var meta = fuel.getItemMeta();
if (meta == null) return;
String origin = meta.getPersistentDataContainer().get(ItemOrigin.WORLD, PersistentDataType.STRING);
String origin = pickupOrigin(meta.getPersistentDataContainer().get(ItemOrigin.WORLD, PersistentDataType.STRING),
event.getBlock().getWorld().getName());
if (origin != null && ItemOrigin.label(origin) != null)
burns.put(event.getBlock(), new Burn(event, furnace.getInventory(), origin));
}

View file

@ -36,6 +36,7 @@ final class WorkstationOrigins implements Listener {
this.plugin = plugin;
this.stamp = stamp;
Bukkit.getPluginManager().registerEvents(this, plugin);
Bukkit.getPluginManager().registerEvents(new ComposterOrigins(), plugin);
}
@EventHandler(priority = EventPriority.HIGHEST)

View file

@ -23,14 +23,20 @@ final class ItemOriginRemaindersTest {
assertFalse(ItemOriginRemainders.consumes(event));
}
@Test void lavaPickupPreservesAnExistingOriginOrUsesTheActualWorld() {
assertTrue(ItemOriginRemainders.lavaPickup(Material.BUCKET, Material.LAVA, Material.LAVA_BUCKET));
assertTrue(ItemOriginRemainders.lavaPickup(Material.BUCKET, Material.LAVA_CAULDRON, Material.LAVA_BUCKET));
assertFalse(ItemOriginRemainders.lavaPickup(Material.BUCKET, Material.WATER, Material.WATER_BUCKET));
assertFalse(ItemOriginRemainders.lavaPickup(Material.BUCKET, Material.WATER, Material.LAVA_BUCKET));
@Test void bucketPickupPreservesAnExistingOriginOrUsesTheActualWorld() {
assertTrue(ItemOriginRemainders.bucketPickup(Material.BUCKET, Material.LAVA, Material.LAVA_BUCKET));
assertTrue(ItemOriginRemainders.bucketPickup(Material.BUCKET, Material.LAVA_CAULDRON, Material.LAVA_BUCKET));
assertTrue(ItemOriginRemainders.bucketPickup(Material.BUCKET, Material.WATER, Material.WATER_BUCKET));
assertTrue(ItemOriginRemainders.bucketPickup(Material.BUCKET, Material.WATER_CAULDRON, Material.WATER_BUCKET));
assertTrue(ItemOriginRemainders.bucketPickup(Material.BUCKET, Material.POWDER_SNOW, Material.POWDER_SNOW_BUCKET));
assertTrue(ItemOriginRemainders.bucketPickup(Material.BUCKET, Material.POWDER_SNOW_CAULDRON, Material.POWDER_SNOW_BUCKET));
assertFalse(ItemOriginRemainders.bucketPickup(Material.WATER_BUCKET, Material.WATER_CAULDRON, Material.WATER_BUCKET));
assertFalse(ItemOriginRemainders.bucketPickup(Material.BUCKET, Material.WATER, Material.LAVA_BUCKET));
assertEquals("arrakis", ItemOriginRemainders.pickupOrigin("arrakis", "giedi_prime_nether"));
assertEquals("giedi_prime_nether", ItemOriginRemainders.pickupOrigin(null, "giedi_prime_nether"));
assertNull(ItemOriginRemainders.pickupOrigin(null, "unknown-world"));
for(String world:new String[]{"lobby_base","lobby_base_nether","lobby_base_the_end","lobby_arrakis","guild_lobby"})
assertEquals(world,ItemOriginRemainders.pickupOrigin(null,world));
}
@Test void provenanceOnlyAppliesToASingleCleanEmptyBucket() {

View file

@ -0,0 +1,88 @@
import java.nio.file.Files;
import java.nio.file.Path;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.*;
final class StationAndDoorOverlay implements Opcodes {
private static final String JARVIS = "com/dunerealms/jarvis/";
private static final String ESS = "com/example/duneess/";
private static final String BUKKIT = "org/bukkit/Bukkit";
private static final String MANAGER = "org/bukkit/plugin/PluginManager";
private static final String REGISTER = "(Lorg/bukkit/event/Listener;Lorg/bukkit/plugin/Plugin;)V";
private static final String MATERIAL = "Lorg/bukkit/Material;";
private static final String PICKUP = "(" + MATERIAL.repeat(3) + ")Z";
private static final String FILL = "(Lorg/bukkit/event/player/PlayerBucketFillEvent;)V";
public static void main(String[] args) throws Exception {
if (args.length != 5) throw new IllegalArgumentException("Expected role, entry, retained, donor and output");
String role = args[0], entry = args[1];
var reader = new ClassReader(Files.readAllBytes(Path.of(args[2])));
var retained = read(reader);
var donor = read(new ClassReader(Files.readAllBytes(Path.of(args[3]))));
if (!retained.name.equals(donor.name) || !retained.name.equals(entry)) {
throw new IllegalArgumentException("Unexpected retained or donor class: " + entry);
}
if (role.equals("ess")) {
if (!entry.equals(ESS + "DuneEss")) throw new IllegalArgumentException("Unexpected Essentials class");
registerAfterExisting(method(retained, "onEnable", "()V"), ESS + "IronDoorInteraction");
} else if (role.equals("station")) {
switch (entry.substring(JARVIS.length())) {
case "WorkstationOrigins" -> registerAfterExisting(method(retained, "<init>",
"(Lorg/bukkit/plugin/Plugin;Ljava/util/function/BiFunction;)V"), JARVIS + "ComposterOrigins");
case "ItemOrigin" -> replace(retained, donor, "label", "label", "(Ljava/lang/String;)Ljava/lang/String;");
case "ArrakisBrewing" -> replace(retained, donor, "brewed", "brewed", "(Lorg/bukkit/event/inventory/BrewEvent;)V");
case "ItemOriginRemainders" -> {
replace(retained, donor, "fillLava", "fillBucket", FILL);
replace(retained, donor, "burn", "burn", "(Lorg/bukkit/event/inventory/FurnaceBurnEvent;)V");
// Retain the old package-private predicate for callers compiled against the baseline.
if (retained.methods.stream().anyMatch(m -> m.name.equals("bucketPickup")))
throw new IllegalArgumentException("Bucket pickup already installed");
retained.methods.add(method(donor, "bucketPickup", PICKUP));
}
default -> throw new IllegalArgumentException("Unexpected station class: " + entry);
}
} else throw new IllegalArgumentException("Unknown overlay role: " + role);
var writer = new ClassWriter(reader, 0);
retained.accept(writer);
Files.write(Path.of(args[4]), writer.toByteArray());
}
private static MethodNode method(ClassNode node, String name, String descriptor) {
return node.methods.stream().filter(m -> m.name.equals(name) && m.desc.equals(descriptor)).findFirst().orElseThrow();
}
private static ClassNode read(ClassReader reader) {
var node = new ClassNode();
reader.accept(node, 0);
return node;
}
private static void replace(ClassNode retained, ClassNode donor, String oldName, String newName, String descriptor) {
var original = method(retained, oldName, descriptor);
var next = method(donor, newName, descriptor);
retained.methods.set(retained.methods.indexOf(original), next);
}
private static void registerAfterExisting(MethodNode method, String listener) {
MethodInsnNode registration = null;
for (var instruction : method.instructions) {
if (instruction instanceof MethodInsnNode call && call.owner.equals(MANAGER)
&& call.name.equals("registerEvents") && call.desc.equals(REGISTER)) {
if (registration != null) throw new IllegalArgumentException("Ambiguous existing listener registration");
registration = call;
}
}
if (registration == null) throw new IllegalArgumentException("Retained listener registration missing");
var code = new InsnList();
code.add(new MethodInsnNode(INVOKESTATIC, BUKKIT, "getPluginManager", "()L" + MANAGER + ";", false));
code.add(new TypeInsnNode(NEW, listener));
code.add(new InsnNode(DUP));
code.add(new MethodInsnNode(INVOKESPECIAL, listener, "<init>", "()V", false));
code.add(new VarInsnNode(ALOAD, method.name.equals("<init>") ? 1 : 0));
code.add(new MethodInsnNode(INVOKEINTERFACE, MANAGER, "registerEvents", REGISTER, true));
method.instructions.insert(registration, code);
method.maxStack = Math.max(method.maxStack, 3);
}
}

View file

@ -0,0 +1,80 @@
"""Build exact station-origin and Essentials door overlays against retained JARs."""
import argparse
import os
from pathlib import Path
import subprocess
from tempfile import TemporaryDirectory
from plugin_wild_update import digest, read_archive, write_archive
JARVIS = "com/dunerealms/jarvis/"
ESS = "com/example/duneess/"
SCOPES = {
"station": (
tuple(JARVIS + name for name in ("WorkstationOrigins", "ItemOrigin", "ArrakisBrewing", "ItemOriginRemainders")),
(JARVIS + "ComposterOrigins",),
{
"86af7e1b6127dbb577cf9223b9b850a613c1a56e42fcfcac53d4dbad367b2703",
"8facb13e8049a73b8072eb1af5053ec3255c2ae22d28b37419ad5cb34c24b31c",
"adc66adcfc1db4ead4de1f5b0d4863822158f23c0b612c669b86fcd1f9ac287a",
},
),
"ess": (
(ESS + "DuneEss",),
(ESS + "IronDoorInteraction",),
{
"35d6bc1946574159defd7e296d1f037c5d0be1ee21bc767801380ed9b7d5a214",
"2e4de7e769c47a036fa9f6c5f175d966aa38c336f5e537d60b07cdd1c267eb1e",
"fd9f633b1d0a89a265a6dd91cfd863ca7c1901652030ee521941d40eb0182954",
},
),
}
def donor_archive(role, jar):
changed, added, _ = SCOPES[role]
source = read_archive(jar.read_bytes())
return write_archive({name + ".class": source[name + ".class"] for name in (*changed, *added)})
def assemble(role, baseline, baseline_sha, donor, donor_sha, output, classpath):
changed, added, approved = SCOPES[role]
existing = baseline.read_bytes()
compiled = donor.read_bytes()
if digest(existing) != baseline_sha or baseline_sha not in approved or digest(compiled) != donor_sha:
raise ValueError("Unexpected baseline or donor checksum")
retained = read_archive(existing)
source = read_archive(compiled)
if set(source) != {name + ".class" for name in (*changed, *added)}:
raise ValueError("Unexpected source class scope")
if any(name + ".class" in retained for name in added):
raise ValueError("The retained archive already contains the new feature")
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("StationAndDoorOverlay.java")
with TemporaryDirectory() as temporary:
root = Path(temporary)
for name in changed:
path = name + ".class"
old, new, merged = (root / file for file in ("retained.class", "donor.class", "merged.class"))
old.write_bytes(retained[path])
new.write_bytes(source[path])
subprocess.run([java, "--class-path", classpath, str(helper), role, name, str(old), str(new), str(merged)], check=True)
retained[path] = merged.read_bytes()
for name in added:
retained[name + ".class"] = source[name + ".class"]
with output.open("xb") as candidate:
candidate.write(write_archive(retained))
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("role", choices=SCOPES)
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()))