fix: address whole-branch review findings for update-swarm

- versions: require entire normalized string to be numeric so dates
  and hotfix suffixes compare as incomparable instead of eq/gt
- hosts: exact host or dot-suffix match rejects lookalikes like
  notmediafire.com and evilmega.nz; GitHub stays exact-set
- census: lazy extractor loop so a later OSError no longer discards an
  earlier sidecar changelog hit
- jobs: watchlist parses only table rows whose vault-note cell is a
  bare wikilink (skips parenthetical related/complete notes); wanted
  also matches bold names in Wanted.md tables with Pokemon prefix
  stripped and casefolded
- cli: validate-scouts and judge raise SystemExit when jobs.json has
  jobs but scouts/ has zero valid files
- fetch: download forwards timeout=60 to urlopen and writes to a
  .part file then os.replace, removing the partial on any failure
This commit is contained in:
ginnoir committed 2026-08-14 15:11:16 -05:00
1 parent 37ebc97b51
commit cb294f72a0
16 files changed
+234 -48

No files matched your search

+11 -6
View File
@@ -80,12 +80,17 @@ def census_job(job: dict, file_path: str | None) -> dict:
} }
if file_path and os.path.isfile(file_path): if file_path and os.path.isfile(file_path):
rec["sha256"], rec["size"] = _sha_size(file_path) rec["sha256"], rec["size"] = _sha_size(file_path)
for found, evidence in ( extractors = (
(_sidecar_version(file_path), "sidecar"), (_sidecar_version, "sidecar"),
(_zip_version(file_path), "zip"), (_zip_version, "zip"),
(_filename_version(file_path), "filename"), (_filename_version, "filename"),
(_rom_version(file_path), "rom-bytes"), (_rom_version, "rom-bytes"),
): )
for fn, evidence in extractors:
try:
found = fn(file_path)
except OSError:
found = None
if found: if found:
rec["installed_version"] = found rec["installed_version"] = found
rec["source"] = "file" rec["source"] = "file"
+6 -3
View File
@@ -18,7 +18,7 @@ def deploy_argv(pokemon_repo: str, site_repo: str) -> list[list[str]]:
["powershell", "-File", "scripts/deploy-site.ps1"], ["powershell", "-File", "scripts/deploy-site.ps1"],
] ]
def _load_scouts(run_dir: str) -> dict: def _load_scouts(run_dir: str, jobs: list[dict] | None = None) -> dict:
out = {} out = {}
for path in glob.glob(os.path.join(run_dir, "scouts", "*.json")): for path in glob.glob(os.path.join(run_dir, "scouts", "*.json")):
obj = read_json(path) obj = read_json(path)
@@ -26,6 +26,8 @@ def _load_scouts(run_dir: str) -> dict:
if errs: if errs:
raise SystemExit(f"{path} missing keys: {errs}") raise SystemExit(f"{path} missing keys: {errs}")
out[obj["stem"]] = obj out[obj["stem"]] = obj
if jobs and len(jobs) > 0 and not out:
raise SystemExit("no valid scout files in scouts/ but jobs.json has jobs")
return out return out
def _load_census(run_dir: str) -> dict: def _load_census(run_dir: str) -> dict:
@@ -61,14 +63,15 @@ def main(argv=None) -> int:
if args.cmd == "validate-scouts": if args.cmd == "validate-scouts":
if not args.run: if not args.run:
raise SystemExit("--run is required") raise SystemExit("--run is required")
_load_scouts(args.run) jobs = read_json(os.path.join(args.run, "jobs.json")).get("jobs")
_load_scouts(args.run, jobs)
print("scouts ok") print("scouts ok")
return 0 return 0
if args.cmd == "judge": if args.cmd == "judge":
if not args.run: if not args.run:
raise SystemExit("--run is required") raise SystemExit("--run is required")
jobs = read_json(os.path.join(args.run, "jobs.json"))["jobs"] jobs = read_json(os.path.join(args.run, "jobs.json"))["jobs"]
verdicts = judge_all(jobs, _load_census(args.run), _load_scouts(args.run)) verdicts = judge_all(jobs, _load_census(args.run), _load_scouts(args.run, jobs))
write_json(os.path.join(args.run, "verdict.json"), {"verdicts": verdicts}) write_json(os.path.join(args.run, "verdict.json"), {"verdicts": verdicts})
print(f"wrote {len(verdicts)} verdicts") print(f"wrote {len(verdicts)} verdicts")
return 0 return 0
+17 -10
View File
@@ -17,8 +17,8 @@ def resolve_mediafire(html: str) -> str | None:
def _open(url: str, opener=None): def _open(url: str, opener=None):
req = urllib.request.Request(url, headers={"User-Agent": UA}) req = urllib.request.Request(url, headers={"User-Agent": UA})
if opener: if opener:
return opener(req) return opener(req, timeout=60)
return urllib.request.urlopen(req) return urllib.request.urlopen(req, timeout=60)
def download(url: str, dest_path: str, opener=None) -> dict: def download(url: str, dest_path: str, opener=None) -> dict:
host, gate = classify_url(url) host, gate = classify_url(url)
@@ -35,16 +35,23 @@ def download(url: str, dest_path: str, opener=None) -> dict:
raise ValueError("no mediafire direct link") raise ValueError("no mediafire direct link")
fetch_url = direct fetch_url = direct
os.makedirs(os.path.dirname(dest_path) or ".", exist_ok=True) os.makedirs(os.path.dirname(dest_path) or ".", exist_ok=True)
part_path = dest_path + ".part"
h = hashlib.sha256() h = hashlib.sha256()
size = 0 size = 0
with _open(fetch_url, opener) as resp, open(dest_path, "wb") as out: try:
while True: with _open(fetch_url, opener) as resp, open(part_path, "wb") as out:
chunk = resp.read(1024 * 1024) while True:
if not chunk: chunk = resp.read(1024 * 1024)
break if not chunk:
out.write(chunk) break
h.update(chunk) out.write(chunk)
size += len(chunk) h.update(chunk)
size += len(chunk)
except BaseException:
if os.path.exists(part_path):
os.remove(part_path)
raise
os.replace(part_path, dest_path)
return {"path": dest_path, "sha256": h.hexdigest(), "size": size, "url": fetch_url} return {"path": dest_path, "sha256": h.hexdigest(), "size": size, "url": fetch_url}
def english_mismatch(archive_path: str, expected_version: str) -> bool: def english_mismatch(archive_path: str, expected_version: str) -> bool:
+25 -15
View File
@@ -1,30 +1,40 @@
from __future__ import annotations from __future__ import annotations
from urllib.parse import urlparse from urllib.parse import urlparse
GITHUB_HOSTS = frozenset(("github.com", "raw.githubusercontent.com", "objects.githubusercontent.com"))
# Exact host or dot-suffix match — `endswith(d)` alone accepts lookalikes like
# `notmediafire.com` or `evilmega.nz`.
SUFFIX_HOSTS = {
"archive.org": "archive",
"mediafire.com": "mediafire",
"mega.nz": "mega",
"mega.co.nz": "mega",
"itch.io": "itch",
"ko-fi.com": "kofi",
"hackdex.app": "hackdex",
"pokecommunity.com": "pokecommunity",
}
def _host_match(host: str, domain: str) -> bool:
return host == domain or host.endswith("." + domain)
def classify_url(url: str) -> tuple[str, str]: def classify_url(url: str) -> tuple[str, str]:
p = urlparse(url or "") p = urlparse(url or "")
host = (p.netloc or "").lower().removeprefix("www.") host = (p.netloc or "").lower().removeprefix("www.")
path = p.path or "" path = p.path or ""
if host in ("github.com", "raw.githubusercontent.com", "objects.githubusercontent.com"): if host in GITHUB_HOSTS:
if host != "github.com" or "/releases/download/" in path: if host != "github.com" or "/releases/download/" in path:
return "github", "ungated" return "github", "ungated"
return "github", "gated" return "github", "gated"
if host.endswith("archive.org"): for domain, label in SUFFIX_HOSTS.items():
return "archive", "ungated" if _host_match(host, domain):
if host.endswith("mediafire.com"): if label == "mega":
return "mediafire", "ungated" return "mega", "ungated" if p.fragment else "gated"
if host.endswith("mega.nz") or host.endswith("mega.co.nz"): if label in ("archive", "mediafire"):
return "mega", "ungated" if p.fragment else "gated" return label, "ungated"
if host.endswith("itch.io"): return label, "gated"
return "itch", "gated"
if host in ("drive.google.com", "docs.google.com"): if host in ("drive.google.com", "docs.google.com"):
return "drive", "gated" return "drive", "gated"
if host in ("discord.com", "discord.gg"): if host in ("discord.com", "discord.gg"):
return "discord", "gated" return "discord", "gated"
if host.endswith("ko-fi.com"):
return "kofi", "gated"
if host.endswith("hackdex.app"):
return "hackdex", "gated"
if host.endswith("pokecommunity.com"):
return "pokecommunity", "gated"
return "other", "gated" return "other", "gated"
+36 -7
View File
@@ -6,17 +6,45 @@ import enrich_vault as E
from update_swarm.schema import write_json from update_swarm.schema import write_json
WIKILINK = re.compile(r"\[\[([^\]|#]+)") WIKILINK = re.compile(r"\[\[([^\]|#]+)")
BOLD = re.compile(r"\*\*([^*]+)\*\*")
WL_CELL = re.compile(r"^\s*\[\[([^\]|#]+)\]\]\s*$")
POKE_PREFIX = re.compile(r"^pokémon\s+", re.I)
def _links(path: str) -> set[str]: def _norm_stem(s: str) -> str:
return POKE_PREFIX.sub("", s.strip()).casefold()
def _watchlist_stems(path: str) -> set[str]:
if not os.path.isfile(path): if not os.path.isfile(path):
return set() return set()
text = open(path, encoding="utf-8").read() stems: set[str] = set()
return {m.strip() for m in WIKILINK.findall(text)} with open(path, encoding="utf-8") as fh:
for line in fh:
if not line.lstrip().startswith("|"):
continue
for cell in line.split("|"):
m = WL_CELL.match(cell)
if m:
stems.add(m.group(1).strip())
return stems
def _wanted_stems(path: str) -> set[str]:
if not os.path.isfile(path):
return set()
with open(path, encoding="utf-8") as fh:
text = fh.read()
stems = {m.strip() for m in WIKILINK.findall(text)}
for line in text.splitlines():
if not line.lstrip().startswith("|"):
continue
for cell in line.split("|"):
for m in BOLD.finditer(cell):
stems.add(m.group(1).strip())
return stems
def build_jobs(vault_romhacks_dir: str) -> list[dict]: def build_jobs(vault_romhacks_dir: str) -> list[dict]:
hacks = os.path.join(vault_romhacks_dir, "Hacks") hacks = os.path.join(vault_romhacks_dir, "Hacks")
watch = _links(os.path.join(vault_romhacks_dir, "Demo Watchlist.md")) watch = {_norm_stem(s) for s in _watchlist_stems(os.path.join(vault_romhacks_dir, "Demo Watchlist.md"))}
wanted = _links(os.path.join(vault_romhacks_dir, "Wanted.md")) wanted = {_norm_stem(s) for s in _wanted_stems(os.path.join(vault_romhacks_dir, "Wanted.md"))}
jobs = [] jobs = []
for path in sorted(glob.glob(os.path.join(hacks, "*.md"))): for path in sorted(glob.glob(os.path.join(hacks, "*.md"))):
stem = os.path.splitext(os.path.basename(path))[0] stem = os.path.splitext(os.path.basename(path))[0]
@@ -24,6 +52,7 @@ def build_jobs(vault_romhacks_dir: str) -> list[dict]:
fm = E.parse_fm(fm_text) fm = E.parse_fm(fm_text)
def blank(v): def blank(v):
return None if v in (None, "", "—") else v return None if v in (None, "", "—") else v
nstem = _norm_stem(stem)
jobs.append({ jobs.append({
"stem": stem, "stem": stem,
"title": fm.get("title") or stem, "title": fm.get("title") or stem,
@@ -33,8 +62,8 @@ def build_jobs(vault_romhacks_dir: str) -> list[dict]:
"source": blank(fm.get("source")), "source": blank(fm.get("source")),
"note_version": blank(fm.get("version")), "note_version": blank(fm.get("version")),
"note_status": blank(fm.get("status")), "note_status": blank(fm.get("status")),
"watchlist": stem in watch, "watchlist": nstem in watch,
"wanted": stem in wanted, "wanted": nstem in wanted,
}) })
return jobs return jobs
+1 -1
View File
@@ -3,7 +3,7 @@ import re
_LANG = re.compile(r"\s*\((EN|ES|FR|DE|IT|PT|JP)\)\s*", re.I) _LANG = re.compile(r"\s*\((EN|ES|FR|DE|IT|PT|JP)\)\s*", re.I)
_LEADING_V = re.compile(r"^\s*v", re.I) _LEADING_V = re.compile(r"^\s*v", re.I)
_NUMERIC = re.compile(r"^(\d+(?:\.\d+)*)") _NUMERIC = re.compile(r"^(\d+(?:\.\d+)*)\s*$")
def normalize_version(s: str) -> str: def normalize_version(s: str) -> str:
s = _LANG.sub(" ", s or "") s = _LANG.sub(" ", s or "")
@@ -1,3 +1,5 @@
| Hack | Vault note | | Hack | Vault note | Why parked | Where to watch |
|---|---| |---|---|---|---|
| **DemoOnly** | [[DemoOnly]] | | **DemoOnly** | [[DemoOnly]] | Essentials demo v0.6.2 | Eevee Expo |
| **Odyssey II / Heroes of Lemuria** | [[Odyssey]] (related) | Demo / early build | Discord |
| **Light Platinum DS** | [[Light Platinum]] (GBA complete; DS is separate) | DS remake — media/teasers only | Twitter |
@@ -0,0 +1,8 @@
---
title: "Pokémon Light Platinum"
platform: GBA
version: "1.0"
status: Complete
---
# Pokémon Light Platinum
@@ -0,0 +1,8 @@
---
title: "Pokémon Odyssey"
platform: GBA
version: "1.0"
status: Complete
---
# Pokémon Odyssey
@@ -1 +1,15 @@
# Wanted — Manual Acquisition List
See [[FakeHack]] still gated. See [[FakeHack]] still gated.
## Acquired
| Hack | Path |
|---|---|
| **FakeHack** | `gba/Hacks/Pokemon - FakeHack (Hack).gba` |
## Still wanted
| Hack | Notes |
|---|---|
| **DemoOnly** | demo-only entry, not in library yet |
+19
View File
@@ -50,5 +50,24 @@ class TestCensus(unittest.TestCase):
self.assertEqual(rec2["source"], "unknown") self.assertEqual(rec2["source"], "unknown")
self.assertIsNone(rec2["installed_version"]) self.assertIsNone(rec2["installed_version"])
@patch(
"update_swarm.census.os.listdir",
return_value=["changelog.txt", "dummy.bin"],
)
def test_rom_version_oserror_keeps_sidecar(self, _listdir):
# A later OSError must not discard an earlier sidecar hit.
with tempfile.TemporaryDirectory() as td:
cpath = os.path.join(td, "changelog.txt")
with open(cpath, "w", encoding="utf-8") as fh:
fh.write("Current Version: 3.3.1\n")
rom_path = os.path.join(td, "dummy.bin")
with open(rom_path, "wb") as fh:
fh.write(b"\x00")
with patch("update_swarm.census._rom_version", side_effect=OSError("boom")):
rec = census_job(job("S"), rom_path)
self.assertEqual(rec["installed_version"], "3.3.1")
self.assertEqual(rec["source"], "file")
self.assertEqual(rec["evidence"], "sidecar")
if __name__ == "__main__": if __name__ == "__main__":
unittest.main() unittest.main()
+36 -1
View File
@@ -1,8 +1,9 @@
import json, os, sys, tempfile, unittest import json, os, sys, tempfile, unittest
ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")) ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
sys.path.insert(0, os.path.join(ROOT, "scripts")) sys.path.insert(0, os.path.join(ROOT, "scripts"))
from update_swarm.cli import deploy_argv, validate_scout from update_swarm.cli import deploy_argv, validate_scout, main
from update_swarm.reports import write_reports from update_swarm.reports import write_reports
from update_swarm.schema import write_json
class TestCli(unittest.TestCase): class TestCli(unittest.TestCase):
def test_validate_scout_missing_keys(self): def test_validate_scout_missing_keys(self):
@@ -41,5 +42,39 @@ class TestCli(unittest.TestCase):
self.assertIn("latest_english_version", text) self.assertIn("latest_english_version", text)
self.assertIn("Do not invent versions", text) self.assertIn("Do not invent versions", text)
def _valid_scout(self, stem):
return {
"stem": stem, "latest_english_version": "1.0", "url": "https://example.com/z.zip",
"host": "other", "gate": "gated", "language_matrix": {"en": "1.0"},
"source_used": "website", "hackdex": "skipped", "upstream_status": "Complete", "notes": "",
}
def test_validate_scouts_fails_when_jobs_but_no_scouts(self):
with tempfile.TemporaryDirectory() as td:
run = os.path.join(td, "2026-08-14")
os.makedirs(os.path.join(run, "scouts"))
write_json(os.path.join(run, "jobs.json"),
{"run_date": "2026-08-14", "jobs": [{"stem": "X"}]})
with self.assertRaises(SystemExit):
main(["--run", run, "validate-scouts"])
def test_validate_scouts_ok_when_scouts_present(self):
with tempfile.TemporaryDirectory() as td:
run = os.path.join(td, "2026-08-14")
scouts = os.path.join(run, "scouts")
os.makedirs(scouts)
write_json(os.path.join(run, "jobs.json"),
{"run_date": "2026-08-14", "jobs": [{"stem": "X"}]})
write_json(os.path.join(scouts, "X.json"), self._valid_scout("X"))
self.assertEqual(main(["--run", run, "validate-scouts"]), 0)
def test_validate_scouts_ok_when_no_jobs(self):
with tempfile.TemporaryDirectory() as td:
run = os.path.join(td, "2026-08-14")
os.makedirs(os.path.join(run, "scouts"))
write_json(os.path.join(run, "jobs.json"),
{"run_date": "2026-08-14", "jobs": []})
self.assertEqual(main(["--run", run, "validate-scouts"]), 0)
if __name__ == "__main__": if __name__ == "__main__":
unittest.main() unittest.main()
+17 -1
View File
@@ -27,10 +27,26 @@ class TestFetch(unittest.TestCase):
return b"rombytes" return b"rombytes"
with tempfile.TemporaryDirectory() as td: with tempfile.TemporaryDirectory() as td:
dest = os.path.join(td, "g.gba") dest = os.path.join(td, "g.gba")
with patch("update_swarm.fetch.urllib.request.urlopen", return_value=Resp()): with patch("update_swarm.fetch.urllib.request.urlopen", return_value=Resp()) as mock_urlopen:
rec = download("https://github.com/a/b/releases/download/v1/g.gba", dest) rec = download("https://github.com/a/b/releases/download/v1/g.gba", dest)
self.assertTrue(os.path.isfile(dest)) self.assertTrue(os.path.isfile(dest))
self.assertEqual(rec["size"], 8) self.assertEqual(rec["size"], 8)
# timeout kwarg must be forwarded to urlopen
self.assertEqual(mock_urlopen.call_args.kwargs.get("timeout"), 60)
def test_download_failure_leaves_no_dest(self):
class Resp:
def __enter__(self): return self
def __exit__(self, *a): pass
def read(self, n=-1):
raise OSError("network died")
with tempfile.TemporaryDirectory() as td:
dest = os.path.join(td, "g.gba")
with patch("update_swarm.fetch.urllib.request.urlopen", return_value=Resp()):
with self.assertRaises(OSError):
download("https://github.com/a/b/releases/download/v1/g.gba", dest)
self.assertFalse(os.path.exists(dest))
self.assertFalse(os.path.exists(dest + ".part"))
def test_mega_not_implemented(self): def test_mega_not_implemented(self):
with tempfile.TemporaryDirectory() as td: with tempfile.TemporaryDirectory() as td:
+11
View File
@@ -20,5 +20,16 @@ class TestClassify(unittest.TestCase):
self.assertEqual(classify_url("https://www.pokecommunity.com/threads/x.1/"), ("pokecommunity", "gated")) self.assertEqual(classify_url("https://www.pokecommunity.com/threads/x.1/"), ("pokecommunity", "gated"))
self.assertEqual(classify_url("https://mystery.example/file.zip"), ("other", "gated")) self.assertEqual(classify_url("https://mystery.example/file.zip"), ("other", "gated"))
def test_lookalike_hosts_are_gated(self):
self.assertEqual(classify_url("https://notmediafire.com/x"), ("other", "gated"))
self.assertEqual(classify_url("https://evilmega.nz/file/a#k"), ("other", "gated"))
self.assertEqual(classify_url("https://notarchive.org/x"), ("other", "gated"))
self.assertEqual(classify_url("https://notitch.io/x"), ("other", "gated"))
def test_real_hosts_still_classified(self):
self.assertEqual(classify_url("https://www.mediafire.com/file/abc/x.zip/file"), ("mediafire", "ungated"))
self.assertEqual(classify_url("https://mega.nz/file/a#k"), ("mega", "ungated"))
self.assertEqual(classify_url("https://sub.archive.org/download/x"), ("archive", "ungated"))
if __name__ == "__main__": if __name__ == "__main__":
unittest.main() unittest.main()
+13 -1
View File
@@ -13,9 +13,21 @@ class TestJobs(unittest.TestCase):
self.assertFalse(jobs["FakeHack"]["watchlist"]) self.assertFalse(jobs["FakeHack"]["watchlist"])
self.assertEqual(jobs["FakeHack"]["note_version"], "1.0.0") self.assertEqual(jobs["FakeHack"]["note_version"], "1.0.0")
self.assertTrue(jobs["DemoOnly"]["watchlist"]) self.assertTrue(jobs["DemoOnly"]["watchlist"])
self.assertFalse(jobs["DemoOnly"]["wanted"]) self.assertTrue(jobs["DemoOnly"]["wanted"])
self.assertIsNone(jobs["DemoOnly"]["library_path"]) self.assertIsNone(jobs["DemoOnly"]["library_path"])
def test_watchlist_skips_parenthetical_notes(self):
jobs = {j["stem"]: j for j in build_jobs(FIXTURE)}
# `[[Odyssey]] (related)` and `[[Light Platinum]] (GBA complete; DS is separate)`
# appear in Demo Watchlist table rows but are parenthetical notes, not watchlist stems.
self.assertFalse(jobs["Odyssey"]["watchlist"])
self.assertFalse(jobs["Light Platinum"]["watchlist"])
def test_wanted_matches_bold_names(self):
jobs = {j["stem"]: j for j in build_jobs(FIXTURE)}
# `**DemoOnly**` in Wanted.md (no wikilink) should still flag wanted.
self.assertTrue(jobs["DemoOnly"]["wanted"])
def test_init_run_creates_dirs(self): def test_init_run_creates_dirs(self):
with tempfile.TemporaryDirectory() as td: with tempfile.TemporaryDirectory() as td:
run = os.path.join(td, "2026-08-14") run = os.path.join(td, "2026-08-14")
+7
View File
@@ -20,6 +20,13 @@ class TestCompare(unittest.TestCase):
self.assertEqual(compare_versions("Final", "1.2"), "incomparable") self.assertEqual(compare_versions("Final", "1.2"), "incomparable")
self.assertEqual(compare_versions("2026-03-30", "Nightly"), "incomparable") self.assertEqual(compare_versions("2026-03-30", "Nightly"), "incomparable")
def test_dates_are_incomparable(self):
self.assertEqual(compare_versions("2026-03-30", "2026-04-01"), "incomparable")
self.assertEqual(compare_versions("2026-03-30", "1.2"), "incomparable")
def test_hotfix_suffix_is_incomparable(self):
self.assertEqual(compare_versions("1.0.2 Hotfix", "1.0.2"), "incomparable")
def test_equal_non_numeric_after_normalize(self): def test_equal_non_numeric_after_normalize(self):
self.assertEqual(compare_versions("Final", "final"), "eq") self.assertEqual(compare_versions("Final", "final"), "eq")