refactor: index source lines once per file

core.lines.LineIndex answers the line of an offset by binary search.
mame_parser and fbneo_parser counted the newlines before each match,
O(n) per set, and csharp_source kept its own copy of the index.

arcade_parent_importer reads a profile's repository slug through
core.upstream.parse_repo and refuses a source that is not on GitHub,
the only forge its fetches reach.
This commit is contained in:
Abdessamad Derraz committed 2026-11-20 20:03:20 +01:00
1 parent c63c2f369e
commit facebef9e5
5 files changed
+83 -6

No files matched your search

+27
View File
@@ -0,0 +1,27 @@
"""Line numbers of offsets in a text, read from one index of line starts."""
from __future__ import annotations
import bisect
class LineIndex:
"""1-based line of any offset of *text*, by binary search.
Counting the newlines before each match is O(n) per lookup: a parser
that reports the line of every match of a file reads it once here.
"""
def __init__(self, text: str) -> None:
self._starts = [0]
position = text.find("\n")
while position != -1:
self._starts.append(position + 1)
position = text.find("\n", position + 1)
def line(self, offset: int) -> int:
return bisect.bisect_right(self._starts, offset)
def start(self, line: int) -> int:
"""Offset of the first character of a 1-based line."""
return self._starts[line - 1]
+6 -4
View File
@@ -55,6 +55,7 @@ from core.artifacts import write_if_changed
from model.profiles import load_emulator_profiles
from core.cli import run_cli
from core.hashing import compute_hashes
from core.upstream import parse_repo
from .base_scraper import download
from .listxml import Opener, attrs, iter_elements, open_listxml, rom_members
from .romset_dat_importer import (
@@ -935,10 +936,11 @@ def _dat_cross_check(
def _repo_slug(url: str) -> str:
parts = [p for p in urllib.parse.urlsplit(url).path.split("/") if p]
if len(parts) < 2:
raise ValueError(f"not a repository URL: {url}")
return f"{parts[0]}/{parts[1].removesuffix('.git')}"
"""owner/name of the GitHub repository a profile's source names."""
repo = parse_repo(url)
if repo is None or repo.family != "github":
raise ValueError(f"not a GitHub repository URL: {url}")
return repo.slug
def fetch_repo_file(slug: str, commit: str, path: str, cache_dir: Path) -> tuple[Path, str]:
+4 -1
View File
@@ -11,6 +11,8 @@ import os
import re
from pathlib import Path
from core.lines import LineIndex
_ROM_ENTRY_RE = re.compile(
r'\{\s*"([^"]+)"\s*,\s*(0x[\da-fA-F]+)\s*,\s*(0x[\da-fA-F]+)\s*,\s*([^}]+)\}',
)
@@ -33,6 +35,7 @@ def find_bios_sets(source: str, filename: str) -> dict[str, dict]:
{set_name: {"source_file": str, "source_line": int}}
"""
results: dict[str, dict] = {}
lines = LineIndex(source)
for match in _BURN_DRIVER_RE.finditer(source):
body = match.group(2)
@@ -45,7 +48,7 @@ def find_bios_sets(source: str, filename: str) -> dict[str, dict]:
continue
set_name = name_match.group(1)
line_num = source[: match.start()].count("\n") + 1
line_num = lines.line(match.start())
results[set_name] = {
"source_file": filename,
+4 -1
View File
@@ -13,6 +13,8 @@ import os
import re
from pathlib import Path
from core.lines import LineIndex
# Macros that declare a machine entry. GAMEL is GAME plus a layout and is
# the only suffixed form MAME declares (src/emu/gamedrv.h): a BIOS root that
# ships a layout, such as gq863 or aristmk5, is written with it.
@@ -126,6 +128,7 @@ def find_bios_root_sets(source: str, filename: str) -> dict[str, dict]:
MACHINE_IS_BIOS_ROOT, returns set names with source location.
"""
results: dict[str, dict] = {}
lines = LineIndex(source)
for match in MACHINE_MACROS.finditer(source):
start = match.end() - 1 # position of opening paren
@@ -154,7 +157,7 @@ def find_bios_root_sets(source: str, filename: str) -> dict[str, dict]:
continue
set_name = args[1].strip()
line_no = source[: match.start()].count("\n") + 1
line_no = lines.line(match.start())
results[set_name] = {
"source_file": filename,
+42
View File
@@ -0,0 +1,42 @@
"""One line index answers the line of every offset a parser reports."""
from __future__ import annotations
import tests
import unittest
from core.lines import LineIndex
class LinesOfOffsets(unittest.TestCase):
TEXT = "a\nbc\n\nd"
def test_each_offset_gets_the_count_of_newlines_before_it_plus_one(self):
index = LineIndex(self.TEXT)
for offset in range(len(self.TEXT) + 1):
with self.subTest(offset=offset):
self.assertEqual(index.line(offset), self.TEXT[:offset].count("\n") + 1)
def test_a_line_starts_after_the_newline_before_it(self):
index = LineIndex(self.TEXT)
self.assertEqual([index.start(n) for n in (1, 2, 3, 4)], [0, 2, 5, 6])
def test_a_text_without_newline_is_one_line(self):
self.assertEqual(LineIndex("").line(0), 1)
self.assertEqual(LineIndex("abc").line(2), 1)
class ParsersReportLines(unittest.TestCase):
def test_mame_and_fbneo_sets_carry_their_line(self):
from scripts.scraper.fbneo_parser import find_bios_sets
from scripts.scraper.mame_parser import find_bios_root_sets
mame = "\n\nGAME( 1990, neogeo, 0, ng, ng, ng_state, init, ROT0, \"SNK\", \"Neo\", MACHINE_IS_BIOS_ROOT )\n"
self.assertEqual(find_bios_root_sets(mame, "neogeo.cpp")["neogeo"]["source_line"], 3)
fbneo = '\n\n\nstruct BurnDriver BurnDrvNeogeo = {\n\t"neogeo", NULL, NULL, NULL, "1990",\n\tBDF_BOARDROM,\n};\n'
self.assertEqual(find_bios_sets(fbneo, "d_neogeo.cpp")["neogeo"]["source_line"], 4)
if __name__ == "__main__":
unittest.main()