diff --git a/crates/horizon-client/examples/command_parse_fixture.rs b/crates/horizon-client/examples/command_parse_fixture.rs index 39d738b7f..1cc1f95d5 100644 --- a/crates/horizon-client/examples/command_parse_fixture.rs +++ b/crates/horizon-client/examples/command_parse_fixture.rs @@ -135,7 +135,7 @@ fn tree(d: &Dispatcher, node: usize) -> Value { fn main() -> horizon_client::Result<()> { let args: Vec = std::env::args().collect(); if args.get(1).map(String::as_str) == Some("tree") { - let d = vanilla::release_dispatcher(); + let d = &vanilla::registered(false); let mut v = tree(d, 0); v["type"] = json!("root"); fs::write(&args[2], v.to_string())?; diff --git a/crates/horizon-client/src/command/vanilla.rs b/crates/horizon-client/src/command/vanilla.rs index daf4ecf86..fd23b82cd 100644 --- a/crates/horizon-client/src/command/vanilla.rs +++ b/crates/horizon-client/src/command/vanilla.rs @@ -36,6 +36,14 @@ pub fn build() -> Dispatcher { /// The tree Commands registers; `dev` adds the commands vanilla only /// registers in development builds (raid, warden_spawn_tracker). pub fn build_with(dev: bool) -> Dispatcher { + let mut d = registered(dev); + apply_vanilla_order(&mut d); + d +} +/// The tree in the order Horizon's code registers it, before +/// [`vanilla_order`](super::vanilla_order) puts children in vanilla's order +/// (tools/generate_command_order.py compares the two). +pub fn registered(dev: bool) -> Dispatcher { let mut d = Dispatcher::new(); let root = 0; @@ -403,7 +411,6 @@ pub fn build_with(dev: bool) -> Dispatcher { super::tree_misc::register(&mut d, root); super::tree_world::register(&mut d, root); super::tree_extra::register(&mut d, root); - apply_vanilla_order(&mut d); d } diff --git a/tests/test_port_regen.py b/tests/test_port_regen.py new file mode 100644 index 000000000..c52499417 --- /dev/null +++ b/tests/test_port_regen.py @@ -0,0 +1,52 @@ +import unittest + +from tools import port_regen as regen + +LOCK = {"minecraft": {"version": "26.3", "manifest_sha1": "m3", "accepted_manifest_sha1": ["m3old"], + "accepted_manifest_note": "republished", "client_sha1": "c3", "server_sha1": "s3", + "java_major": 25}, + "vineflower": {"version": "1.12.0"}} + + +def manifest(version, client, server, java=25): + return {"id": version, "downloads": {"client": {"sha1": client}, "server": {"sha1": server}}, + "javaVersion": {"majorVersion": java}} + + +class PinTests(unittest.TestCase): + def test_another_version_gets_a_new_block(self): + pinned = regen.pinned_lock(LOCK, manifest("26.4", "c4", "s4", 26), "m4") + self.assertEqual(pinned["minecraft"], {"version": "26.4", "manifest_sha1": "m4", "client_sha1": "c4", + "server_sha1": "s4", "java_major": 26}) + self.assertEqual(pinned["vineflower"], LOCK["vineflower"]) + + def test_the_same_version_keeps_its_block(self): + for sha1 in ["m3", "m3old"]: + self.assertIs(regen.pinned_lock(LOCK, manifest("26.3", "c3", "s3"), sha1), LOCK) + + def test_the_same_version_with_other_jars_is_repinned(self): + self.assertEqual(regen.pinned_lock(LOCK, manifest("26.3", "c3b", "s3"), "m3b")["minecraft"]["client_sha1"], + "c3b") + + +class CompileErrorTests(unittest.TestCase): + OUTPUT = """/x/mods/horizon/src/test/java/dev/horizonlab/parity/ParityData.java:45: error: cannot find symbol + var context = TagLoader.buildUpdatedLookups(layers.getAccessForLoading(RegistryLayer.WORLD), staticTags); + ^ + symbol: variable WORLD + location: class RegistryLayer +/x/VanillaCommandParseOracle.java:12: error: incompatible types: int cannot be converted to String +2 errors +""" + + def test_names_the_symbols(self): + self.assertEqual(regen.compile_errors(self.OUTPUT), [ + "ParityData.java:45: cannot find symbol: variable WORLD (class RegistryLayer)", + "VanillaCommandParseOracle.java:12: incompatible types: int cannot be converted to String"]) + + def test_nothing_from_other_failures(self): + self.assertEqual(regen.compile_errors("expected the root's order to differ"), []) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_port_report.py b/tests/test_port_report.py index f1a8e1f35..9db732862 100644 --- a/tests/test_port_report.py +++ b/tests/test_port_report.py @@ -62,11 +62,32 @@ def diff(): class PortReportTests(unittest.TestCase): - def build(self, results=None): + def build(self, results=None, regen=None): with mock.patch.object(report, "version_sites", return_value=["crates/p/src/lib.rs:20"]), \ mock.patch.object(report, "files_naming", return_value=["crates/p/src/play.rs"]), \ mock.patch.object(report, "files_containing", return_value=["crates/w/src/blocks.rs"]): - return report.build(diff(), mapping(), "26.2", "26.3", {"id": "26.3"}, results) + return report.build(diff(), mapping(), "26.2", "26.3", {"id": "26.3"}, results, regen=regen) + + def test_regen_results_replace_the_stale_tables(self): + regen = {"new": "26.3", "candidate": "/ports/26.3", "commit": "0123456789abcdef", "generators": { + "packet_ids": {"status": "regenerated", "outputs": ["crates/horizon-protocol/src/ids.rs"], + "stat": {"crates/horizon-protocol/src/ids.rs": [142, 134]}}, + "entity_tracking": {"status": "unchanged", "outputs": ["crates/horizon-client/src/lan/tracking.rs"], + "stat": {}}, + "lan_command_order": {"status": "failed", "outputs": ["crates/horizon-client/src/lan/command_order.rs"], + "error": "javac exited 1", + "compile_errors": ["ParityData.java:45: cannot find symbol: variable WORLD"]}}} + built = self.build(regen=regen) + self.assertFalse([i for i in built["items"] if i["kind"] == "regenerate"]) + [failed] = [i for i in built["items"] if i["kind"] == "regen-failed"] + self.assertEqual(failed["rank"], 1) + self.assertIn("no longer compiles", failed["title"]) + self.assertEqual(built["summary"]["generators"], + {"packet_ids": "regenerated", "entity_tracking": "unchanged", "lan_command_order": "failed"}) + text = report.markdown(built) + self.assertIn("regenerated 1, unchanged 1, failed 1", text) + self.assertIn("`crates/horizon-protocol/src/ids.rs` (+142 -134)", text) + self.assertIn("- javac: `ParityData.java:45: cannot find symbol: variable WORLD`", text) def test_ranks_and_kinds(self): built = self.build() diff --git a/tools/generate_command_order.py b/tools/generate_command_order.py index 6eabc909b..ab78b3ada 100644 --- a/tools/generate_command_order.py +++ b/tools/generate_command_order.py @@ -5,7 +5,7 @@ registers them in a different order. Brigadier keeps children in registration order, and /help (smart usage) lists them that way. python3 tools/test_command_parse_parity.py # exports .local/command-parse-parity/tree.json - command_parse_fixture tree rust_tree.json # Horizon's tree with child order + command_parse_fixture tree rust_tree.json # Horizon's tree in its registration order generate_command_order.py VANILLA_TREE RUST_TREE """ import argparse diff --git a/tools/port_regen.py b/tools/port_regen.py index 025b69ed8..be2d31843 100644 --- a/tools/port_regen.py +++ b/tools/port_regen.py @@ -20,6 +20,7 @@ it reads. import json import os from pathlib import Path +import re import shutil import subprocess import tempfile @@ -127,17 +128,41 @@ def python(): return shutil.which("python3") or "python3" +class Failed(RuntimeError): + """A command that exited non-zero, with all it printed.""" + + def __init__(self, command, code, output): + super().__init__(f"{' '.join(map(str, command))[:300]} exited {code}:\n{output[-2500:]}") + self.output = output + + def run(command, cwd, log=None, env=None): - """Run a command; on failure raise with the end of its output.""" + """Run a command; on failure raise Failed.""" result = subprocess.run([str(c) for c in command], cwd=cwd, capture_output=True, text=True, env=env) if log: log.write_text(result.stdout + result.stderr) if result.returncode: - raise RuntimeError(f"{' '.join(map(str, command))[:300]} exited {result.returncode}:\n" - + (result.stdout + result.stderr)[-2500:]) + raise Failed(command, result.returncode, result.stdout + result.stderr) return result.stdout +def compile_errors(output, limit=12): + """javac's errors, one line each: "ParityData.java:45: cannot find symbol: variable WORLD (class + RegistryLayer)" names the vanilla API an oracle used that the new version changed.""" + lines = output.splitlines() + found = [] + for index, line in enumerate(lines): + match = re.match(r".*?([\w$]+\.java):(\d+): error: (.*)", line) + if not match: + continue + entry = f"{match[1]}:{match[2]}: {match[3]}" + after = [text.strip() for text in lines[index + 1:index + 6]] + symbol = next((text.split(":", 1)[1].strip() for text in after if text.startswith("symbol:")), None) + where = next((text.split(":", 1)[1].strip() for text in after if text.startswith("location:")), None) + found.append(entry + (f": {symbol}" if symbol else "") + (f" ({where})" if where else "")) + return found[:limit] + + # --- decompiling the classes the generators parse ------------------------------------------------------------ def decompile_classes(root, version, store): @@ -257,7 +282,8 @@ def run_generators(root, version, store, names=None): results[name] = {"status": state, "outputs": outputs, "stat": stat} except (RuntimeError, OSError, subprocess.CalledProcessError, KeyError, ValueError) as error: git("checkout", "HEAD", "--", *outputs, cwd=root, check=False) - results[name] = {"status": "failed", "outputs": outputs, "error": str(error)[-2500:]} + results[name] = {"status": "failed", "outputs": outputs, "error": str(error)[-2500:], + "compile_errors": compile_errors(getattr(error, "output", str(error)))} print(f" {name}: {results[name]['status']}", flush=True) return results diff --git a/tools/port_report.py b/tools/port_report.py index eafcaa8bd..0e5766ed9 100644 --- a/tools/port_report.py +++ b/tools/port_report.py @@ -154,8 +154,10 @@ def blocking_items(diff, mapping, pinned_facts, root, regen=None): else: for name, entry in regen["generators"].items(): if entry["status"] == "failed": - items.append(item(1, "regen-failed", f"Generator {name} failed on {regen['new']}", - files=entry["outputs"], error=entry["error"])) + errors = entry.get("compile_errors", []) + what = "its vanilla exporter no longer compiles" if errors else "failed" + items.append(item(1, "regen-failed", f"Generator {name}: {what} on {regen['new']}", + files=entry["outputs"], error=entry["error"], compile_errors=errors)) return items @@ -304,7 +306,9 @@ def markdown(report, limit=12): lines.append(f"### #{entry['id']} {entry['title']}") if entry.get("command"): lines.append(f"- run: `{entry['command']}`") - if entry.get("error"): + if entry.get("compile_errors"): + lines += [f"- javac: `{e}`" for e in entry["compile_errors"][:limit]] + elif entry.get("error"): lines.append("- error: `" + entry["error"].strip().splitlines()[-1][:300] + "`") if entry.get("failed"): lines.append(f"- failing harnesses: {', '.join(entry['failed'])}")