refactor: split scraper cli and platform scrapers

This commit is contained in:
Abdessamad Derraz committed 2026-11-17 07:35:02 +01:00
1 parent fbf7ae826d
commit 9af72a1ffb
14 files changed
+491 -377

No files matched your search

+1 -1
View File
@@ -74,7 +74,7 @@ def discover_target_scrapers() -> dict[str, type]:
if _scrapers:
return _scrapers
package_dir = Path(__file__).parent
for finder, name, ispkg in pkgutil.iter_modules([str(package_dir)]):
for _finder, name, _ispkg in pkgutil.iter_modules([str(package_dir)]):
if not name.endswith("_targets_scraper"):
continue
module = importlib.import_module(f".{name}", package=__package__)
@@ -302,7 +302,7 @@ def _parse_es_systems(text: str) -> dict[str, list[str]]:
package_to_emulators: dict[str, list[str]] = {}
for _system_name, system_data in data.items():
for system_data in data.values():
if not isinstance(system_data, dict):
continue
emulators = system_data.get("emulators")
@@ -81,6 +81,91 @@ def _expand(value: str, env: dict[str, str]) -> str:
)
class _Evaluation:
"""The state of one evaluate() run over an options file."""
def __init__(self, env: dict[str, str]) -> None:
self.env = dict(env)
# One frame per open if: [parent state, branch taken, this branch's state],
# each True, False, or None where a condition read an unknown variable.
self.stack: list[list[bool | None]] = []
self.case_depth = self.loop_depth = 0
def state(self) -> bool | None:
states = [frame[2] for frame in self.stack]
if False in states:
return False
return None if None in states else True
def nesting(self, line: str) -> bool:
"""Follow case and loop nesting. True when the line is consumed."""
if re.match(r"^case\b", line):
self.case_depth += 1
return True
if line == "esac":
self.case_depth -= 1
return True
if re.match(r"^(for|while)\b", line):
self.loop_depth += 1
return True
if line == "done":
self.loop_depth -= 1
return True
return bool(self.loop_depth)
def branch(self, line: str) -> bool:
"""Follow if/elif/else/fi. True when the line is one of them."""
go: bool | None
branch = _IF_RE.match(line)
if branch and branch.group(1) == "if":
parent = self.state()
go = False if parent is False else (
None if parent is None else _condition(branch.group(2), self.env)
)
self.stack.append([parent, go, go])
return True
if branch and branch.group(1) == "elif":
frame = self.stack[-1]
if frame[0] is False or frame[1] is True:
go = False
elif frame[0] is None or frame[1] is None:
go = None
else:
go = _condition(branch.group(2), self.env)
frame[1] = True if go is True else (None if go is None else frame[1])
frame[2] = go
return True
if line == "else":
frame = self.stack[-1]
if frame[0] is False or frame[1] is True:
go = False
elif frame[0] is None or frame[1] is None:
go = None
else:
go = True
frame[1], frame[2] = True, go
return True
if line == "fi":
self.stack.pop()
return True
return False
def assign(self, line: str) -> None:
assign = _ASSIGN_RE.match(line)
current = self.state()
if not assign or current is False:
return
name, op, value = assign.groups()
if self.case_depth or current is None:
if name in WATCHED:
where = "a case statement" if self.case_depth else "an undecidable branch"
raise ShellSubsetError(f"{name} assigned inside {where}")
return
value = " ".join(_expand(value, self.env).split())
env = self.env
env[name] = f"{env.get(name, '')} {value}".strip() if op == "+=" else value
def evaluate(text: str, env: dict[str, str]) -> dict[str, str]:
"""Run the assignments and if/elif/else blocks of a LibreELEC options file.
@@ -89,82 +174,13 @@ def evaluate(text: str, env: dict[str, str]) -> dict[str, str]:
as a set difference. A watched variable set inside a case statement is
ambiguous and stops the scrape rather than guess.
"""
env = dict(env)
lines = re.sub(r"\\\n", " ", text).splitlines()
# One frame per open if: [parent state, branch taken, this branch's state],
# each True, False, or None where a condition read an unknown variable.
stack: list[list[bool | None]] = []
case_depth = loop_depth = 0
def state() -> bool | None:
states = [frame[2] for frame in stack]
if False in states:
return False
return None if None in states else True
for raw in lines:
run = _Evaluation(env)
for raw in re.sub(r"\\\n", " ", text).splitlines():
line = raw.split("#", 1)[0].strip()
if not line:
if not line or run.nesting(line) or run.branch(line):
continue
if re.match(r"^case\b", line):
case_depth += 1
continue
if line == "esac":
case_depth -= 1
continue
if re.match(r"^(for|while)\b", line):
loop_depth += 1
continue
if line == "done":
loop_depth -= 1
continue
if loop_depth:
continue
branch = _IF_RE.match(line)
if branch and branch.group(1) == "if":
parent = state()
go = False if parent is False else (
None if parent is None else _condition(branch.group(2), env)
)
stack.append([parent, go, go])
continue
if branch and branch.group(1) == "elif":
frame = stack[-1]
if frame[0] is False or frame[1] is True:
go = False
elif frame[0] is None or frame[1] is None:
go = None
else:
go = _condition(branch.group(2), env)
frame[1] = True if go is True else (None if go is None else frame[1])
frame[2] = go
continue
if line == "else":
frame = stack[-1]
if frame[0] is False or frame[1] is True:
go = False
elif frame[0] is None or frame[1] is None:
go = None
else:
go = True
frame[1], frame[2] = True, go
continue
if line == "fi":
stack.pop()
continue
assign = _ASSIGN_RE.match(line)
current = state()
if not assign or current is False:
continue
name, op, value = assign.groups()
if case_depth or current is None:
if name in WATCHED:
where = "a case statement" if case_depth else "an undecidable branch"
raise ShellSubsetError(f"{name} assigned inside {where}")
continue
value = " ".join(_expand(value, env).split())
env[name] = f"{env.get(name, '')} {value}".strip() if op == "+=" else value
return env
run.assign(line)
return run.env
def device_cores(cores_mk: str, env: dict[str, str]) -> list[str]:
@@ -93,6 +93,33 @@ _CORE_FILE_RE = re.compile(r"([\w+.-]+)_libretro\.(?:so\b|\{[^}]*\bso\b[^}]*\})"
_TEST_RE = re.compile(r'\[\s*"\$\{(\w+)\}"\s*=\s*"([^"]*)"\s*\]')
def _holds(condition: str, values: dict[str, str]) -> bool:
tests = _TEST_RE.findall(condition)
if not tests or re.sub(_TEST_RE, "", condition).strip(" ;&") not in ("", "then"):
raise RuntimeError(f"makeinstall_target tests {condition.strip()!r}")
for variable, value in tests:
if variable not in values:
raise RuntimeError(f"makeinstall_target tests ${{{variable}}}")
if values[variable] != value:
return False
return True
def _copied_cores(line: str) -> list[str]:
"""The core files one line of makeinstall_target copies, by installed name."""
found: list[str] = []
for sources, target in _COPY_RE.findall(line):
if named := _CORE_FILE_RE.search(target):
found.append(named.group(1))
continue
found.extend(
named.group(1) for source in sources.split()
if not source.startswith("-")
and (named := _CORE_FILE_RE.search(source.rsplit("/", 1)[-1]))
)
return found
def installed_cores(package_mk: str, arch: str, with_32bit: bool) -> list[str]:
"""The cores a libretro package installs on a device.
@@ -110,17 +137,6 @@ def installed_cores(package_mk: str, arch: str, with_32bit: bool) -> list[str]:
# config/options:36 sets TARGET_ARCH="${ARCH}".
values = {"ARCH": arch, "TARGET_ARCH": arch, "ENABLE_32BIT": "true" if with_32bit else "false"}
def holds(condition: str) -> bool:
tests = _TEST_RE.findall(condition)
if not tests or re.sub(_TEST_RE, "", condition).strip(" ;&") not in ("", "then"):
raise RuntimeError(f"makeinstall_target tests {condition.strip()!r}")
for variable, value in tests:
if variable not in values:
raise RuntimeError(f"makeinstall_target tests ${{{variable}}}")
if values[variable] != value:
return False
return True
found: list[str] = []
stack: list[bool] = []
in_case = False
@@ -138,7 +154,7 @@ def installed_cores(package_mk: str, arch: str, with_32bit: bool) -> list[str]:
stack[-1] = arch in arm.group(1).split("|") or arm.group(1) == "*"
line = arm.group(2)
if line.startswith("if "):
stack.append(holds(line[3:]))
stack.append(_holds(line[3:], values))
continue
if line == "else":
stack[-1] = not stack[-1]
@@ -148,13 +164,7 @@ def installed_cores(package_mk: str, arch: str, with_32bit: bool) -> list[str]:
continue
if not all(stack):
continue
for sources, target in _COPY_RE.findall(line):
if named := _CORE_FILE_RE.search(target):
found.append(named.group(1))
continue
for source in sources.split():
if not source.startswith("-") and (named := _CORE_FILE_RE.search(source.rsplit("/", 1)[-1])):
found.append(named.group(1))
found.extend(_copied_cores(line))
if not found:
raise RuntimeError("makeinstall_target installs no libretro core")
return sorted(set(found))