mirror of
https://github.com/Abdess/retroarch_system.git
synced 2026-11-22 17:47:48 -06:00
refactor: move profile_sync logic into profiling
This commit is contained in:
1 parent
22a81c384d
commit
75a69a4a42
13 files changed
+366
-300
No files matched your search
+13
-271
@@ -9,83 +9,23 @@ recalable from what needs the code read again.
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
from collections import Counter
|
||||
from dataclasses import asdict
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
sys.path.insert(0, os.path.dirname(__file__))
|
||||
|
||||
from core import upstream
|
||||
from profiling import version_basis
|
||||
from model.systems import norm_system_id, system_index
|
||||
from core.github import github_token
|
||||
from model.profiles import ProfileSelectionError, is_emulator, load_emulator_profiles, resolve_profile_name
|
||||
from core.cli import add_repo_inputs, suggest_names
|
||||
from profiling.bump import DEFAULT_CACHE, write_version
|
||||
from profiling.realign import realign_prose
|
||||
from profiling.reports import ProfileReport
|
||||
from profiling.run import WRITTEN_PROFILES, emit_reports, read_one_profile
|
||||
from profiling.triage import PROGRESS_SECONDS, Progress, print_interrupted
|
||||
from profiling.yamledit import YamlWriteError
|
||||
|
||||
ANON_QUOTA = 60
|
||||
|
||||
|
||||
def _refuse_dirty_tree(emulators_dir: str, names: list[str]) -> None:
|
||||
"""Writes need a clean copy of each profile they touch to roll back to.
|
||||
|
||||
Only the selected profiles count: a pass writing one profile after
|
||||
another used to refuse every profile after the first it wrote.
|
||||
"""
|
||||
try:
|
||||
dirty = emulators_dir_is_dirty(emulators_dir, names)
|
||||
except RuntimeError as e:
|
||||
print(f"{e}. Pass --force to write anyway.", file=sys.stderr)
|
||||
raise SystemExit(1) from e
|
||||
if dirty:
|
||||
# Another session may own the change, so the refusal names the files:
|
||||
# --force writes over them.
|
||||
one = len(dirty) == 1
|
||||
print(
|
||||
f"{', '.join(dirty)} {'has' if one else 'have'} uncommitted changes: "
|
||||
f"commit {'it' if one else 'them'} or pass --force, which writes over "
|
||||
f"{'it' if one else 'them'}.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
raise SystemExit(1)
|
||||
|
||||
|
||||
def emulators_dir_is_dirty(emulators_dir: str, names: list[str] | None = None) -> list[str]:
|
||||
"""The files of the profile directory that carry uncommitted changes.
|
||||
|
||||
Paths read as the status prints them, from the repository root.
|
||||
|
||||
``names`` narrows the question to those profiles. Git is asked from
|
||||
inside the directory, so a profile tree that lives in another
|
||||
repository answers for itself. A directory git cannot read is never
|
||||
reported clean: the writes have nothing to roll back to.
|
||||
"""
|
||||
paths = [f"{name}.yml" for name in names] if names is not None else ["."]
|
||||
result = subprocess.run(
|
||||
["git", "-C", emulators_dir, "status", "--porcelain", "--", *paths],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
if result.returncode:
|
||||
raise RuntimeError(
|
||||
f"cannot read the git status of {emulators_dir}: {result.stderr.strip()}"
|
||||
)
|
||||
return sorted(
|
||||
line[3:].split(" -> ")[-1].strip('"')
|
||||
for line in result.stdout.splitlines()
|
||||
if line.strip()
|
||||
)
|
||||
from profiling.bump import DEFAULT_CACHE
|
||||
from profiling.quota import check_quota
|
||||
from profiling.realignpass import run_realign
|
||||
from profiling.run import emit_reports, read_selected
|
||||
from profiling.sourcepaths import refresh_source_paths
|
||||
from profiling.versioncheck import run_versions
|
||||
from profiling.worktree import branch_profiles, project_base, refuse_dirty_tree
|
||||
|
||||
|
||||
def build_parser() -> argparse.ArgumentParser:
|
||||
@@ -239,57 +179,6 @@ def build_parser() -> argparse.ArgumentParser:
|
||||
return parser
|
||||
|
||||
|
||||
def _git_lines(args: list[str]) -> list[str]:
|
||||
from core.gitclone import GitRefused, required_git_lines
|
||||
|
||||
try:
|
||||
return required_git_lines(*args)
|
||||
except GitRefused as exc:
|
||||
raise SystemExit(f"ERROR: {exc}") from exc
|
||||
|
||||
|
||||
def branch_profiles(emulators_dir: str, base: str, added_only: bool) -> list[str]:
|
||||
"""Names of the profiles the branch adds (or edits) against ``base``.
|
||||
|
||||
The diff starts at the merge base, so commits main gained since the
|
||||
branch point are not counted, and ends at the working tree, so a
|
||||
profile not yet committed is checked too. A rename reads as an addition.
|
||||
"""
|
||||
if subprocess.run(["git", "rev-parse", "--verify", "--quiet", base],
|
||||
capture_output=True, check=False).returncode:
|
||||
remote = base.split("/", 1)[0] if "/" in base else "upstream"
|
||||
raise SystemExit(f"ERROR: {base} is not in this clone: run git fetch {remote} first")
|
||||
merge_base = _git_lines(["merge-base", base, "HEAD"])[0]
|
||||
paths = _git_lines([
|
||||
"diff", "--name-only", "--no-renames",
|
||||
"--diff-filter=A" if added_only else "--diff-filter=AM",
|
||||
merge_base, "--", emulators_dir,
|
||||
])
|
||||
paths += _git_lines([
|
||||
"ls-files", "--others", "--exclude-standard", "--full-name",
|
||||
"--", emulators_dir,
|
||||
])
|
||||
top = Path(_git_lines(["rev-parse", "--show-toplevel"])[0])
|
||||
root = Path(emulators_dir).resolve()
|
||||
return sorted({
|
||||
full.stem
|
||||
for path in paths
|
||||
if (full := (top / path).resolve()).suffix == ".yml" and full.parent == root
|
||||
})
|
||||
|
||||
|
||||
def project_base() -> str:
|
||||
"""The project's main line, the base --changed compares with by default.
|
||||
|
||||
In a fork's clone origin/main is the fork: once the branch is pushed it
|
||||
is HEAD, and --changed --strict found nothing and passed while the PR's
|
||||
CI then failed. validate_pr.py resolves the same line the same way.
|
||||
"""
|
||||
from core.gitclone import compare_base
|
||||
|
||||
return compare_base() or "HEAD"
|
||||
|
||||
|
||||
def select_profiles(profiles: dict, args: argparse.Namespace) -> dict:
|
||||
"""Profiles matching the selection flags."""
|
||||
if args.changed or args.added:
|
||||
@@ -352,20 +241,6 @@ def select_profiles(profiles: dict, args: argparse.Namespace) -> dict:
|
||||
return selected
|
||||
|
||||
|
||||
def _check_quota(count: int, offline: bool) -> None:
|
||||
"""Refuse a run the anonymous quota cannot carry to completion."""
|
||||
if offline or github_token():
|
||||
return
|
||||
if count * 5 > ANON_QUOTA:
|
||||
print(
|
||||
f"{count} profiles need roughly {count * 5} API calls, the anonymous "
|
||||
f"quota is {ANON_QUOTA} per hour. Log in with `gh auth login`, set "
|
||||
"GITHUB_TOKEN, or use --offline.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
raise SystemExit(1)
|
||||
|
||||
|
||||
def _refuse_flag_combinations(args: argparse.Namespace) -> None:
|
||||
"""Exit on a flag the chosen mode would not apply, before any request."""
|
||||
if args.verify_version or args.set_version:
|
||||
@@ -487,56 +362,6 @@ def _version_selection(args: argparse.Namespace, profiles: dict) -> dict:
|
||||
return select_profiles(profiles, args)
|
||||
|
||||
|
||||
def format_reading(name: str, reading: version_basis.Reading) -> str:
|
||||
mode = f"[{reading.mode}] " if reading.mode else ""
|
||||
kind = f"{reading.kind} " if reading.kind else ""
|
||||
if reading.status == version_basis.DRIFT:
|
||||
said = f"declared {reading.declared}, code {reading.read}"
|
||||
elif reading.status == version_basis.MATCH:
|
||||
said = str(reading.read)
|
||||
else:
|
||||
said = f"declared {reading.declared}"
|
||||
return f"{name}: {mode}{reading.status} {said} ({kind}{reading.where})"
|
||||
|
||||
|
||||
def run_versions(args: argparse.Namespace, profiles: dict) -> None:
|
||||
"""--verify-version and --set-version: core_version against the code."""
|
||||
selected = _version_selection(args, profiles)
|
||||
if args.set_version and not args.dry_run and not args.force:
|
||||
_refuse_dirty_tree(args.emulators_dir, list(selected))
|
||||
counts: Counter = Counter()
|
||||
rows = []
|
||||
failed = False
|
||||
for name, profile in selected.items():
|
||||
readings = version_basis.check(
|
||||
profile, args.cache_dir, args.offline, profiles, recompute=args.set_version
|
||||
)
|
||||
for reading in readings:
|
||||
counts[reading.status] += 1
|
||||
rows.append({"profile": name, **asdict(reading)})
|
||||
if not args.as_json and (not args.changed_only or reading.status != version_basis.MATCH):
|
||||
print(format_reading(name, reading))
|
||||
if args.set_version:
|
||||
path = Path(args.emulators_dir) / f"{name}.yml"
|
||||
if args.dry_run:
|
||||
continue
|
||||
try:
|
||||
if write_version(path, readings):
|
||||
print(f"{name}: core_version written")
|
||||
except YamlWriteError as exc:
|
||||
print(f"{name}: write refused: {exc}", file=sys.stderr)
|
||||
failed = True
|
||||
elif any(r.status in version_basis.FAILING for r in readings):
|
||||
failed = True
|
||||
if args.as_json:
|
||||
print(json.dumps(rows, indent=2))
|
||||
else:
|
||||
print(", ".join(f"{count} {status}" for status, count in sorted(counts.items())),
|
||||
file=sys.stderr)
|
||||
if failed:
|
||||
raise SystemExit(1)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""Build one report per selected profile, then apply writes and output."""
|
||||
args = build_parser().parse_args()
|
||||
@@ -547,44 +372,23 @@ def main() -> None:
|
||||
upstream.MOVING_TTL = 0
|
||||
profiles = load_emulator_profiles(args.emulators_dir, skip_aliases=False)
|
||||
if args.verify_version or args.set_version:
|
||||
run_versions(args, profiles)
|
||||
run_versions(args, profiles, _version_selection(args, profiles))
|
||||
return
|
||||
selected = select_profiles(profiles, args)
|
||||
_check_quota(len(selected), args.offline)
|
||||
check_quota(len(selected), args.offline)
|
||||
|
||||
writes = (
|
||||
args.backfill_commits or args.rebase_refs or args.bump_commit
|
||||
or args.realign_prose or args.attribute_refs
|
||||
)
|
||||
if writes and not args.dry_run and not args.force:
|
||||
_refuse_dirty_tree(args.emulators_dir, list(selected))
|
||||
refuse_dirty_tree(args.emulators_dir, list(selected))
|
||||
|
||||
if args.realign_prose:
|
||||
_run_realign(args, selected)
|
||||
run_realign(args, selected)
|
||||
return
|
||||
|
||||
# A profile that could not be compared or written is not a profile with
|
||||
# nothing to review: it stays in every output and fails the run.
|
||||
failed: set[str] = set()
|
||||
reports: list[ProfileReport] = []
|
||||
quiet = args.offline or len(selected) < 2
|
||||
if not quiet:
|
||||
print(
|
||||
f"reading {len(selected)} profiles against their forges, a line every "
|
||||
f"{PROGRESS_SECONDS} s. --offline answers from the cache alone.",
|
||||
file=sys.stderr, flush=True,
|
||||
)
|
||||
progress = Progress(len(selected), "read", quiet)
|
||||
complete = True
|
||||
try:
|
||||
for name, profile in selected.items():
|
||||
progress.step(len(reports), name)
|
||||
read_one_profile(args, name, profile, reports, failed, writes)
|
||||
except KeyboardInterrupt:
|
||||
# What was read is still worth printing: a ranking of 200 profiles
|
||||
# beats none after 15 minutes.
|
||||
print_interrupted(len(reports), len(selected), "the output covers those read")
|
||||
complete = False
|
||||
reports, failed, complete = read_selected(args, selected, writes)
|
||||
|
||||
# --changed-only narrows every output, not the text report alone: the
|
||||
# documented `--all --changed-only --json` listed every profile.
|
||||
@@ -593,7 +397,7 @@ def main() -> None:
|
||||
if not args.changed_only or report.needs_review() or report.name in failed
|
||||
]
|
||||
complete = emit_reports(args, selected, reports, shown) is not False and complete
|
||||
_refresh_source_paths(args)
|
||||
refresh_source_paths(args)
|
||||
if not complete:
|
||||
raise SystemExit(130)
|
||||
if failed or (args.strict and any(
|
||||
@@ -602,68 +406,6 @@ def main() -> None:
|
||||
raise SystemExit(1)
|
||||
|
||||
|
||||
def _run_realign(args: argparse.Namespace, selected: dict) -> None:
|
||||
"""--realign-prose over the selected profiles, exit 1 when one failed."""
|
||||
failed: set[str] = set()
|
||||
for name in selected:
|
||||
profile_path = Path(args.emulators_dir) / f"{name}.yml"
|
||||
if not profile_path.is_file():
|
||||
continue
|
||||
try:
|
||||
before = profile_path.read_bytes()
|
||||
for line in realign_prose(
|
||||
profile_path, args.cache_dir, args.offline, args.dry_run
|
||||
):
|
||||
print(f"{name}: {line}")
|
||||
if profile_path.read_bytes() != before:
|
||||
WRITTEN_PROFILES.add(name)
|
||||
except upstream.UpstreamError as exc:
|
||||
print(f"{name}: {exc}", file=sys.stderr)
|
||||
failed.add(name)
|
||||
except YamlWriteError as exc:
|
||||
print(f"{name}: write refused: {exc}", file=sys.stderr)
|
||||
failed.add(name)
|
||||
_refresh_source_paths(args)
|
||||
if failed:
|
||||
raise SystemExit(1)
|
||||
|
||||
|
||||
def _refresh_source_paths(args: argparse.Namespace) -> None:
|
||||
"""Rebuild the site's record of cited source paths after a write.
|
||||
|
||||
Each bump left website/src/data/source-paths.json behind its pins, and
|
||||
the site's freshness test stayed red until someone ran sitesources.py
|
||||
--fetch by hand. A run that writes nothing, or makes no request, leaves
|
||||
it alone.
|
||||
"""
|
||||
if not WRITTEN_PROFILES or args.dry_run or args.offline or os.environ.get("RETROBIOS_OFFLINE"):
|
||||
return
|
||||
from model.profiles import emulator_profiles_cache
|
||||
from sitegen import sources
|
||||
from core.artifacts import ArtifactLockBusy
|
||||
|
||||
# The run loaded the profiles before writing them, and the loader caches
|
||||
# by directory: read again, the record described the pins just replaced
|
||||
# (linapple, then ten profiles in one advance).
|
||||
emulator_profiles_cache.clear()
|
||||
profiles = load_emulator_profiles(args.emulators_dir, skip_aliases=False)
|
||||
try:
|
||||
held, unread = sources.refresh_record(profiles, [sources.TREE_CACHE], fetch=True)
|
||||
except ArtifactLockBusy as exc:
|
||||
# The profiles are written: only the record waits for the other run.
|
||||
print(
|
||||
f"source paths not refreshed ({exc}): run python scripts/sitesources.py "
|
||||
"--fetch once it finishes",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return
|
||||
print(
|
||||
f"source paths: {sum(map(len, held.values()))} in {len(held)} trees, "
|
||||
f"{len(unread)} trees not cached: {sources.SOURCE_PATHS}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
from core.cli import run_cli
|
||||
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
"""The anonymous GitHub quota a profile pass has to fit in."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
|
||||
from core.github import github_token
|
||||
|
||||
ANON_QUOTA = 60
|
||||
|
||||
|
||||
def check_quota(count: int, offline: bool) -> None:
|
||||
"""Refuse a run the anonymous quota cannot carry to completion."""
|
||||
if offline or github_token():
|
||||
return
|
||||
if count * 5 > ANON_QUOTA:
|
||||
print(
|
||||
f"{count} profiles need roughly {count * 5} API calls, the anonymous "
|
||||
f"quota is {ANON_QUOTA} per hour. Log in with `gh auth login`, set "
|
||||
"GITHUB_TOKEN, or use --offline.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
raise SystemExit(1)
|
||||
@@ -0,0 +1,39 @@
|
||||
"""--realign-prose over a selection of profiles."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from core import upstream
|
||||
from profiling.realign import realign_prose
|
||||
from profiling.run import WRITTEN_PROFILES
|
||||
from profiling.sourcepaths import refresh_source_paths
|
||||
from profiling.yamledit import YamlWriteError
|
||||
|
||||
|
||||
def run_realign(args: argparse.Namespace, selected: dict) -> None:
|
||||
"""--realign-prose over the selected profiles, exit 1 when one failed."""
|
||||
failed: set[str] = set()
|
||||
for name in selected:
|
||||
profile_path = Path(args.emulators_dir) / f"{name}.yml"
|
||||
if not profile_path.is_file():
|
||||
continue
|
||||
try:
|
||||
before = profile_path.read_bytes()
|
||||
for line in realign_prose(
|
||||
profile_path, args.cache_dir, args.offline, args.dry_run
|
||||
):
|
||||
print(f"{name}: {line}")
|
||||
if profile_path.read_bytes() != before:
|
||||
WRITTEN_PROFILES.add(name)
|
||||
except upstream.UpstreamError as exc:
|
||||
print(f"{name}: {exc}", file=sys.stderr)
|
||||
failed.add(name)
|
||||
except YamlWriteError as exc:
|
||||
print(f"{name}: write refused: {exc}", file=sys.stderr)
|
||||
failed.add(name)
|
||||
refresh_source_paths(args)
|
||||
if failed:
|
||||
raise SystemExit(1)
|
||||
@@ -25,7 +25,7 @@ from profiling.reports import (
|
||||
)
|
||||
from profiling.repos import select_repo
|
||||
from profiling.resolver import build_report
|
||||
from profiling.triage import print_triage
|
||||
from profiling.triage import PROGRESS_SECONDS, Progress, print_interrupted, print_triage
|
||||
from profiling.versions import (
|
||||
newer_release,
|
||||
latest_passed_release,
|
||||
@@ -342,6 +342,36 @@ def read_one_profile(
|
||||
failed.add(name)
|
||||
|
||||
|
||||
def read_selected(
|
||||
args: argparse.Namespace, selected: dict, writes: bool
|
||||
) -> tuple[list[ProfileReport], set[str], bool]:
|
||||
"""Every selected profile's pass: the reports, the profiles that failed,
|
||||
and whether the pass ran to its end."""
|
||||
# A profile that could not be compared or written is not a profile with
|
||||
# nothing to review: it stays in every output and fails the run.
|
||||
failed: set[str] = set()
|
||||
reports: list[ProfileReport] = []
|
||||
quiet = args.offline or len(selected) < 2
|
||||
if not quiet:
|
||||
print(
|
||||
f"reading {len(selected)} profiles against their forges, a line every "
|
||||
f"{PROGRESS_SECONDS} s. --offline answers from the cache alone.",
|
||||
file=sys.stderr, flush=True,
|
||||
)
|
||||
progress = Progress(len(selected), "read", quiet)
|
||||
complete = True
|
||||
try:
|
||||
for name, profile in selected.items():
|
||||
progress.step(len(reports), name)
|
||||
read_one_profile(args, name, profile, reports, failed, writes)
|
||||
except KeyboardInterrupt:
|
||||
# What was read is still worth printing: a ranking of 200 profiles
|
||||
# beats none after 15 minutes.
|
||||
print_interrupted(len(reports), len(selected), "the output covers those read")
|
||||
complete = False
|
||||
return reports, failed, complete
|
||||
|
||||
|
||||
# Profiles this run wrote. Their new pins name trees the site's record of
|
||||
# cited source paths does not hold yet.
|
||||
WRITTEN_PROFILES: set[str] = set()
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
"""The site's record of cited source paths, rebuilt after a pass wrote profiles."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import sys
|
||||
|
||||
from model.profiles import load_emulator_profiles
|
||||
from profiling.run import WRITTEN_PROFILES
|
||||
|
||||
|
||||
def refresh_source_paths(args: argparse.Namespace) -> None:
|
||||
"""Rebuild the site's record of cited source paths after a write.
|
||||
|
||||
Each bump left website/src/data/source-paths.json behind its pins, and
|
||||
the site's freshness test stayed red until someone ran sitesources.py
|
||||
--fetch by hand. A run that writes nothing, or makes no request, leaves
|
||||
it alone.
|
||||
"""
|
||||
if not WRITTEN_PROFILES or args.dry_run or args.offline or os.environ.get("RETROBIOS_OFFLINE"):
|
||||
return
|
||||
from core.artifacts import ArtifactLockBusy
|
||||
from model.profiles import emulator_profiles_cache
|
||||
from sitegen import sources
|
||||
|
||||
# The run loaded the profiles before writing them, and the loader caches
|
||||
# by directory: read again, the record described the pins just replaced
|
||||
# (linapple, then ten profiles in one advance).
|
||||
emulator_profiles_cache.clear()
|
||||
profiles = load_emulator_profiles(args.emulators_dir, skip_aliases=False)
|
||||
try:
|
||||
held, unread = sources.refresh_record(profiles, [sources.TREE_CACHE], fetch=True)
|
||||
except ArtifactLockBusy as exc:
|
||||
# The profiles are written: only the record waits for the other run.
|
||||
print(
|
||||
f"source paths not refreshed ({exc}): run python scripts/sitesources.py "
|
||||
"--fetch once it finishes",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return
|
||||
print(
|
||||
f"source paths: {sum(map(len, held.values()))} in {len(held)} trees, "
|
||||
f"{len(unread)} trees not cached: {sources.SOURCE_PATHS}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
@@ -0,0 +1,65 @@
|
||||
"""--verify-version and --set-version over a selection: core_version against the code."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
from collections import Counter
|
||||
from dataclasses import asdict
|
||||
from pathlib import Path
|
||||
|
||||
from profiling import version_basis
|
||||
from profiling.bump import write_version
|
||||
from profiling.worktree import refuse_dirty_tree
|
||||
from profiling.yamledit import YamlWriteError
|
||||
|
||||
|
||||
def format_reading(name: str, reading: version_basis.Reading) -> str:
|
||||
"""One reading as a line: its status, the version said, and where it was read."""
|
||||
mode = f"[{reading.mode}] " if reading.mode else ""
|
||||
kind = f"{reading.kind} " if reading.kind else ""
|
||||
if reading.status == version_basis.DRIFT:
|
||||
said = f"declared {reading.declared}, code {reading.read}"
|
||||
elif reading.status == version_basis.MATCH:
|
||||
said = str(reading.read)
|
||||
else:
|
||||
said = f"declared {reading.declared}"
|
||||
return f"{name}: {mode}{reading.status} {said} ({kind}{reading.where})"
|
||||
|
||||
|
||||
def run_versions(args: argparse.Namespace, profiles: dict, selected: dict) -> None:
|
||||
"""--verify-version and --set-version over ``selected``: core_version against the code."""
|
||||
if args.set_version and not args.dry_run and not args.force:
|
||||
refuse_dirty_tree(args.emulators_dir, list(selected))
|
||||
counts: Counter = Counter()
|
||||
rows = []
|
||||
failed = False
|
||||
for name, profile in selected.items():
|
||||
readings = version_basis.check(
|
||||
profile, args.cache_dir, args.offline, profiles, recompute=args.set_version
|
||||
)
|
||||
for reading in readings:
|
||||
counts[reading.status] += 1
|
||||
rows.append({"profile": name, **asdict(reading)})
|
||||
if not args.as_json and (not args.changed_only or reading.status != version_basis.MATCH):
|
||||
print(format_reading(name, reading))
|
||||
if args.set_version:
|
||||
path = Path(args.emulators_dir) / f"{name}.yml"
|
||||
if args.dry_run:
|
||||
continue
|
||||
try:
|
||||
if write_version(path, readings):
|
||||
print(f"{name}: core_version written")
|
||||
except YamlWriteError as exc:
|
||||
print(f"{name}: write refused: {exc}", file=sys.stderr)
|
||||
failed = True
|
||||
elif any(r.status in version_basis.FAILING for r in readings):
|
||||
failed = True
|
||||
if args.as_json:
|
||||
print(json.dumps(rows, indent=2))
|
||||
else:
|
||||
print(", ".join(f"{count} {status}" for status, count in sorted(counts.items())),
|
||||
file=sys.stderr)
|
||||
if failed:
|
||||
raise SystemExit(1)
|
||||
@@ -0,0 +1,110 @@
|
||||
"""The git state a profile pass reads: uncommitted profiles, the branch's profiles, the project's main line."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def refuse_dirty_tree(emulators_dir: str, names: list[str]) -> None:
|
||||
"""Writes need a clean copy of each profile they touch to roll back to.
|
||||
|
||||
Only the selected profiles count: a pass writing one profile after
|
||||
another used to refuse every profile after the first it wrote.
|
||||
"""
|
||||
try:
|
||||
dirty = emulators_dir_is_dirty(emulators_dir, names)
|
||||
except RuntimeError as e:
|
||||
print(f"{e}. Pass --force to write anyway.", file=sys.stderr)
|
||||
raise SystemExit(1) from e
|
||||
if dirty:
|
||||
# Another session may own the change, so the refusal names the files:
|
||||
# --force writes over them.
|
||||
one = len(dirty) == 1
|
||||
print(
|
||||
f"{', '.join(dirty)} {'has' if one else 'have'} uncommitted changes: "
|
||||
f"commit {'it' if one else 'them'} or pass --force, which writes over "
|
||||
f"{'it' if one else 'them'}.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
raise SystemExit(1)
|
||||
|
||||
|
||||
def emulators_dir_is_dirty(emulators_dir: str, names: list[str] | None = None) -> list[str]:
|
||||
"""The files of the profile directory that carry uncommitted changes.
|
||||
|
||||
Paths read as the status prints them, from the repository root.
|
||||
|
||||
``names`` narrows the question to those profiles. Git is asked from
|
||||
inside the directory, so a profile tree that lives in another
|
||||
repository answers for itself. A directory git cannot read is never
|
||||
reported clean: the writes have nothing to roll back to.
|
||||
"""
|
||||
paths = [f"{name}.yml" for name in names] if names is not None else ["."]
|
||||
result = subprocess.run(
|
||||
["git", "-C", emulators_dir, "status", "--porcelain", "--", *paths],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
if result.returncode:
|
||||
raise RuntimeError(
|
||||
f"cannot read the git status of {emulators_dir}: {result.stderr.strip()}"
|
||||
)
|
||||
return sorted(
|
||||
line[3:].split(" -> ")[-1].strip('"')
|
||||
for line in result.stdout.splitlines()
|
||||
if line.strip()
|
||||
)
|
||||
|
||||
|
||||
def _git_lines(args: list[str]) -> list[str]:
|
||||
from core.gitclone import GitRefused, required_git_lines
|
||||
|
||||
try:
|
||||
return required_git_lines(*args)
|
||||
except GitRefused as exc:
|
||||
raise SystemExit(f"ERROR: {exc}") from exc
|
||||
|
||||
|
||||
def branch_profiles(emulators_dir: str, base: str, added_only: bool) -> list[str]:
|
||||
"""Names of the profiles the branch adds (or edits) against ``base``.
|
||||
|
||||
The diff starts at the merge base, so commits main gained since the
|
||||
branch point are not counted, and ends at the working tree, so a
|
||||
profile not yet committed is checked too. A rename reads as an addition.
|
||||
"""
|
||||
if subprocess.run(["git", "rev-parse", "--verify", "--quiet", base],
|
||||
capture_output=True, check=False).returncode:
|
||||
remote = base.split("/", 1)[0] if "/" in base else "upstream"
|
||||
raise SystemExit(f"ERROR: {base} is not in this clone: run git fetch {remote} first")
|
||||
merge_base = _git_lines(["merge-base", base, "HEAD"])[0]
|
||||
paths = _git_lines([
|
||||
"diff", "--name-only", "--no-renames",
|
||||
"--diff-filter=A" if added_only else "--diff-filter=AM",
|
||||
merge_base, "--", emulators_dir,
|
||||
])
|
||||
paths += _git_lines([
|
||||
"ls-files", "--others", "--exclude-standard", "--full-name",
|
||||
"--", emulators_dir,
|
||||
])
|
||||
top = Path(_git_lines(["rev-parse", "--show-toplevel"])[0])
|
||||
root = Path(emulators_dir).resolve()
|
||||
return sorted({
|
||||
full.stem
|
||||
for path in paths
|
||||
if (full := (top / path).resolve()).suffix == ".yml" and full.parent == root
|
||||
})
|
||||
|
||||
|
||||
def project_base() -> str:
|
||||
"""The project's main line, the base --changed compares with by default.
|
||||
|
||||
In a fork's clone origin/main is the fork: once the branch is pushed it
|
||||
is HEAD, and --changed --strict found nothing and passed while the PR's
|
||||
CI then failed. validate_pr.py resolves the same line the same way.
|
||||
"""
|
||||
from core.gitclone import compare_base
|
||||
|
||||
return compare_base() or "HEAD"
|
||||
@@ -160,6 +160,14 @@ COMMANDS = {
|
||||
"standalone_probe.py": (
|
||||
"probes/standaloneemulators.py", "probes/appimage.py", "probes/xvfb.py", "probes/standalonerun.py",
|
||||
"probes/standalonerecord.py",
|
||||
"profile_sync.py": (
|
||||
"profiling/citations.py", "profiling/anchoring.py", "profiling/repos.py",
|
||||
"profiling/resolver.py", "profiling/reports.py", "profiling/versions.py",
|
||||
"profiling/version_basis.py", "profiling/detection.py", "profiling/triage.py",
|
||||
"profiling/yamledit.py", "profiling/proseedit.py", "profiling/rebase.py",
|
||||
"profiling/bump.py", "profiling/realign.py", "profiling/run.py",
|
||||
"profiling/worktree.py", "profiling/quota.py", "profiling/sourcepaths.py",
|
||||
"profiling/realignpass.py", "profiling/versioncheck.py",
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -34,7 +34,8 @@ SIBLING_IMPORTS: dict[str, frozenset[str]] = {
|
||||
# A campaign commits its findings the way the unattended jobs commit, and a
|
||||
# standalone probe lists an emulator's releases through the one GitHub reader.
|
||||
"probes": frozenset({"unattended", "scraper"}),
|
||||
"profiling": frozenset(),
|
||||
# A pass that wrote profiles rebuilds the site's record of cited source paths.
|
||||
"profiling": frozenset({"sitegen"}),
|
||||
"romrecipes": frozenset(),
|
||||
# The site prints the recipe counts and the dump-catalog coverage report
|
||||
# those two packages compute, serves the handheld launchers and prints the
|
||||
|
||||
+22
-20
@@ -30,6 +30,8 @@ from profiling import reports as profiling_reports
|
||||
from profiling import repos as profiling_repos
|
||||
from profiling import resolver
|
||||
from profiling import run as profiling_run
|
||||
from profiling import sourcepaths as profiling_sourcepaths
|
||||
from profiling import worktree as profiling_worktree
|
||||
from profiling import triage
|
||||
from profiling import versions
|
||||
from model import sourceref
|
||||
@@ -5128,7 +5130,7 @@ class TestRateLimitEndsOneProfile(unittest.TestCase):
|
||||
with mock.patch.object(profile_sync, "load_emulator_profiles", return_value={}), \
|
||||
mock.patch.object(profile_sync, "select_profiles",
|
||||
return_value={"cemu": {}, "after": {}}), \
|
||||
mock.patch.object(profile_sync, "_check_quota"), \
|
||||
mock.patch.object(profile_sync, "check_quota"), \
|
||||
mock.patch.object(profiling_run, "build_report", side_effect=build), \
|
||||
contextlib.redirect_stdout(out), \
|
||||
contextlib.redirect_stderr(err), \
|
||||
@@ -5157,16 +5159,16 @@ class AWriteRefreshesTheSourcePaths(unittest.TestCase):
|
||||
|
||||
with mock.patch.object(sources, "build_source_paths", return_value=({}, [])) as built, \
|
||||
mock.patch.dict(os.environ, {"RETROBIOS_OFFLINE": ""}), \
|
||||
mock.patch.object(profile_sync, "load_emulator_profiles", return_value={}), \
|
||||
mock.patch.object(profiling_sourcepaths, "load_emulator_profiles", return_value={}), \
|
||||
mock.patch.object(sources, "write_if_changed") as written, \
|
||||
contextlib.redirect_stderr(io.StringIO()):
|
||||
profiling_run.WRITTEN_PROFILES.clear()
|
||||
profile_sync._refresh_source_paths(self._args())
|
||||
profiling_sourcepaths.refresh_source_paths(self._args())
|
||||
self.assertFalse(built.called)
|
||||
profiling_run.WRITTEN_PROFILES.add("x")
|
||||
profile_sync._refresh_source_paths(self._args(dry_run=True))
|
||||
profiling_sourcepaths.refresh_source_paths(self._args(dry_run=True))
|
||||
self.assertFalse(built.called)
|
||||
profile_sync._refresh_source_paths(self._args())
|
||||
profiling_sourcepaths.refresh_source_paths(self._args())
|
||||
self.assertTrue(built.called and written.called)
|
||||
profiling_run.WRITTEN_PROFILES.clear()
|
||||
|
||||
@@ -5194,7 +5196,7 @@ class AWriteRefreshesTheSourcePaths(unittest.TestCase):
|
||||
contextlib.redirect_stdout(io.StringIO()):
|
||||
profiling_run.WRITTEN_PROFILES.add("p")
|
||||
self.addCleanup(profiling_run.WRITTEN_PROFILES.clear)
|
||||
profile_sync._refresh_source_paths(self._args(emulators_dir=tmp))
|
||||
profiling_sourcepaths.refresh_source_paths(self._args(emulators_dir=tmp))
|
||||
self.assertEqual(built.call_args[0][0]["p"]["source_commit"], "new")
|
||||
|
||||
def test_the_record_waits_for_a_run_holding_the_repository(self):
|
||||
@@ -5210,11 +5212,11 @@ class AWriteRefreshesTheSourcePaths(unittest.TestCase):
|
||||
with mock.patch.object(sources, "repository_output_lock", return_value=busy) as lock, \
|
||||
mock.patch.object(sources, "build_source_paths") as built, \
|
||||
mock.patch.dict(os.environ, {"RETROBIOS_OFFLINE": ""}), \
|
||||
mock.patch.object(profile_sync, "load_emulator_profiles", return_value={}), \
|
||||
mock.patch.object(profiling_sourcepaths, "load_emulator_profiles", return_value={}), \
|
||||
contextlib.redirect_stderr(io.StringIO()) as err:
|
||||
profiling_run.WRITTEN_PROFILES.add("x")
|
||||
self.addCleanup(profiling_run.WRITTEN_PROFILES.clear)
|
||||
profile_sync._refresh_source_paths(self._args())
|
||||
profiling_sourcepaths.refresh_source_paths(self._args())
|
||||
lock.assert_called_once_with(str(sources.SOURCE_PATHS))
|
||||
self.assertFalse(built.called)
|
||||
self.assertIn("sitesources.py --fetch", err.getvalue())
|
||||
@@ -5262,7 +5264,7 @@ class TestOutputModesApplyTheirFlags(unittest.TestCase):
|
||||
with mock.patch.object(profile_sync, "load_emulator_profiles", return_value={}), \
|
||||
mock.patch.object(profile_sync, "select_profiles",
|
||||
return_value={"clean": {}, "drift": {}}), \
|
||||
mock.patch.object(profile_sync, "_check_quota"), \
|
||||
mock.patch.object(profile_sync, "check_quota"), \
|
||||
mock.patch.object(profiling_run, "build_report",
|
||||
side_effect=lambda name, *a, **k: reports[name]), \
|
||||
contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
|
||||
@@ -5370,7 +5372,7 @@ class TestOutputModesApplyTheirFlags(unittest.TestCase):
|
||||
with mock.patch.object(profile_sync, "load_emulator_profiles", return_value={}), \
|
||||
mock.patch.object(profile_sync, "select_profiles",
|
||||
return_value={"clean": {}, "drift": {}}), \
|
||||
mock.patch.object(profile_sync, "_check_quota"), \
|
||||
mock.patch.object(profile_sync, "check_quota"), \
|
||||
mock.patch.object(profiling_run, "build_report", side_effect=build), \
|
||||
contextlib.redirect_stdout(out), \
|
||||
contextlib.redirect_stderr(io.StringIO()), \
|
||||
@@ -5510,7 +5512,7 @@ class TestEmulatorsDirStatus(unittest.TestCase):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
self._git("init", "-q", cwd=root)
|
||||
Path(root, "a.yml").write_text("emulator: a\n")
|
||||
self.assertTrue(profile_sync.emulators_dir_is_dirty(root))
|
||||
self.assertTrue(profiling_worktree.emulators_dir_is_dirty(root))
|
||||
|
||||
def test_only_the_selected_profiles_count(self):
|
||||
# A loop of --emulator X --rebase-refs refused every profile after
|
||||
@@ -5522,8 +5524,8 @@ class TestEmulatorsDirStatus(unittest.TestCase):
|
||||
self._git("add", "a.yml", "b.yml", cwd=root)
|
||||
self._git("-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "p", cwd=root)
|
||||
Path(root, "a.yml").write_text("emulator: a2\n")
|
||||
self.assertTrue(profile_sync.emulators_dir_is_dirty(root, ["a"]))
|
||||
self.assertFalse(profile_sync.emulators_dir_is_dirty(root, ["b"]))
|
||||
self.assertTrue(profiling_worktree.emulators_dir_is_dirty(root, ["a"]))
|
||||
self.assertFalse(profiling_worktree.emulators_dir_is_dirty(root, ["b"]))
|
||||
|
||||
def test_the_refusal_names_the_changed_profile(self):
|
||||
"""One profile changed by another session among ~375 refused the
|
||||
@@ -5535,11 +5537,11 @@ class TestEmulatorsDirStatus(unittest.TestCase):
|
||||
self._git("add", "a.yml", "b.yml", "c.yml", cwd=root)
|
||||
self._git("-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "p", cwd=root)
|
||||
Path(root, "b.yml").write_text("emulator: b2\n")
|
||||
self.assertEqual(profile_sync.emulators_dir_is_dirty(root, ["a", "b", "c"]),
|
||||
self.assertEqual(profiling_worktree.emulators_dir_is_dirty(root, ["a", "b", "c"]),
|
||||
["b.yml"])
|
||||
err = io.StringIO()
|
||||
with contextlib.redirect_stderr(err), self.assertRaises(SystemExit):
|
||||
profile_sync._refuse_dirty_tree(root, ["a", "b", "c"])
|
||||
profiling_worktree.refuse_dirty_tree(root, ["a", "b", "c"])
|
||||
self.assertIn("b.yml has uncommitted changes", err.getvalue())
|
||||
self.assertNotIn("a.yml", err.getvalue())
|
||||
|
||||
@@ -5547,7 +5549,7 @@ class TestEmulatorsDirStatus(unittest.TestCase):
|
||||
with tempfile.TemporaryDirectory() as root, mock.patch.dict(
|
||||
os.environ, {"GIT_CEILING_DIRECTORIES": str(Path(root).parent)}
|
||||
), self.assertRaises(RuntimeError):
|
||||
profile_sync.emulators_dir_is_dirty(root)
|
||||
profiling_worktree.emulators_dir_is_dirty(root)
|
||||
|
||||
|
||||
class UpstreamVendoredAsASubmodule(unittest.TestCase):
|
||||
@@ -6166,7 +6168,7 @@ class AnOnlinePassSaysWhereItIs(unittest.TestCase):
|
||||
try:
|
||||
sys.argv = ["profile_sync.py", "--all", "--triage", *argv]
|
||||
with mock.patch.object(profiling_run, "_build_full_report", side_effect=build), \
|
||||
mock.patch.object(profile_sync, "_check_quota"), \
|
||||
mock.patch.object(profile_sync, "check_quota"), \
|
||||
contextlib.redirect_stdout(out), contextlib.redirect_stderr(err), \
|
||||
self.assertRaises(SystemExit) as caught:
|
||||
profile_sync.main()
|
||||
@@ -6295,13 +6297,13 @@ class TestBranchProfiles(unittest.TestCase):
|
||||
|
||||
def test_changed_takes_added_edited_and_uncommitted(self):
|
||||
self.assertEqual(
|
||||
profile_sync.branch_profiles("emulators", "main", added_only=False),
|
||||
profiling_worktree.branch_profiles("emulators", "main", added_only=False),
|
||||
["draft", "edited", "new"],
|
||||
)
|
||||
|
||||
def test_added_leaves_edited_profiles_out(self):
|
||||
self.assertEqual(
|
||||
profile_sync.branch_profiles("emulators", "main", added_only=True),
|
||||
profiling_worktree.branch_profiles("emulators", "main", added_only=True),
|
||||
["draft", "new"],
|
||||
)
|
||||
|
||||
@@ -6309,7 +6311,7 @@ class TestBranchProfiles(unittest.TestCase):
|
||||
"""`--base upstream/main` with upstream added and never fetched
|
||||
stopped on git's "Not a valid object name" and no next step."""
|
||||
with self.assertRaises(SystemExit) as raised:
|
||||
profile_sync.branch_profiles("emulators", "upstream/main", added_only=True)
|
||||
profiling_worktree.branch_profiles("emulators", "upstream/main", added_only=True)
|
||||
self.assertIn("git fetch upstream", str(raised.exception))
|
||||
|
||||
def test_the_flag_selects_those_profiles(self):
|
||||
|
||||
@@ -74,8 +74,8 @@ class AProjectMainThatCannotBeFetched(unittest.TestCase):
|
||||
import contextlib
|
||||
import io
|
||||
|
||||
import profile_sync
|
||||
from core import cli, gitclone
|
||||
from profiling import worktree
|
||||
|
||||
def unreachable() -> None:
|
||||
raise gitclone.MainLineUnreachable("no main")
|
||||
@@ -83,7 +83,7 @@ class AProjectMainThatCannotBeFetched(unittest.TestCase):
|
||||
with mock.patch.object(gitclone, "project_main_line", side_effect=unreachable):
|
||||
err = io.StringIO()
|
||||
with contextlib.redirect_stderr(err), self.assertRaises(SystemExit) as ended:
|
||||
cli.run_cli(profile_sync.project_base)
|
||||
cli.run_cli(worktree.project_base)
|
||||
self.assertEqual(ended.exception.code, 1)
|
||||
self.assertEqual(err.getvalue(), "ERROR: no main\n")
|
||||
import validate_pr
|
||||
@@ -91,9 +91,9 @@ class AProjectMainThatCannotBeFetched(unittest.TestCase):
|
||||
validate_pr.get_changed_files()
|
||||
|
||||
def test_both_tools_compare_against_the_same_line(self):
|
||||
import profile_sync
|
||||
import validate_pr
|
||||
from core import gitclone
|
||||
from profiling import worktree
|
||||
|
||||
diffs: list[tuple[str, ...]] = []
|
||||
|
||||
@@ -106,7 +106,7 @@ class AProjectMainThatCannotBeFetched(unittest.TestCase):
|
||||
with mock.patch.object(gitclone, "project_main_line", return_value=None), \
|
||||
mock.patch.object(gitclone, "git_lines", side_effect=lines), \
|
||||
mock.patch.object(validate_pr, "git_lines", side_effect=lines):
|
||||
self.assertEqual(profile_sync.project_base(), "origin/main")
|
||||
self.assertEqual(worktree.project_base(), "origin/main")
|
||||
validate_pr.get_changed_files()
|
||||
self.assertIn(("diff", "--name-only", "origin/main...HEAD"), diffs)
|
||||
|
||||
|
||||
@@ -946,8 +946,8 @@ class TheGitHubTokenComesFromGh(unittest.TestCase):
|
||||
run.assert_not_called()
|
||||
|
||||
def test_every_api_caller_reads_it(self):
|
||||
import profile_sync
|
||||
from core import upstream
|
||||
from profiling.quota import check_quota
|
||||
from scraper import base_scraper
|
||||
|
||||
with self._gh():
|
||||
@@ -961,7 +961,7 @@ class TheGitHubTokenComesFromGh(unittest.TestCase):
|
||||
"Bearer gho_fromgh")
|
||||
os.environ.pop("GITHUB_TOKEN")
|
||||
with self._gh(), contextlib.redirect_stderr(io.StringIO()):
|
||||
profile_sync._check_quota(606, offline=False)
|
||||
check_quota(606, offline=False)
|
||||
|
||||
def test_another_forge_never_triggers_gh(self):
|
||||
from core import upstream
|
||||
|
||||
+1
-1
@@ -1366,7 +1366,7 @@ before a release (wiki/release-process.md). Its lines stay in
|
||||
| `model/` | Data loading: `database.json`, platform configs and the registry, emulator profiles, hardware targets, system ids, the region vocabulary, dump catalogues, release assets, the `source_ref` grammar (`sourceref.py`) |
|
||||
| `resolve/` | From a declaration to a file: content checks, `resolve_local_file` and its stages, archive members, launcher layouts, the cores a platform runs, validation, slots, truth |
|
||||
| `packs/` | The library behind `verify.py`, `generate_pack.py`, `cross_reference.py`, `slots.py` and `refresh_data_dirs.py`: per-file verdicts, coverage and gaps, core extras, slot arbitration, pack naming and archives, manifests, the pack check, the data directory cache |
|
||||
| `profiling/` | What `profile_sync.py` runs: citations, anchoring, the report and its forms, version checks, detection, triage, and the guarded writes (recale, bump, prose realignment, `version_basis`) |
|
||||
| `profiling/` | What `profile_sync.py` runs: citations, anchoring, the report and its forms, version checks, detection, triage, the git state a pass reads (uncommitted profiles, the branch's profiles), the anonymous quota, and the guarded writes (recale, bump, prose realignment, `version_basis`) with the site's record of cited paths rebuilt after them |
|
||||
| `romrecipes/` | What `romset_recipes.py` runs: romset recipes from profiles and DATs, the ROM pool addressed by crc32, identification and rebuilt pins, and the recipe of every archive held (`recipes/archives.json`: capture, member lookup by sha1, verified build) |
|
||||
| `acquire/` | What `provenance_report.py`, `auto_fetch.py`, `find_embedded.py` and `find_pinned_revision.py` run: dump-catalog coverage, dumps a held file already contains, the searches by hash, the rolling crc32 window, the walk of a file's upstream history |
|
||||
| `games/` | What `game_rules.py` and `generate_games_index.py` run: the checks of the region and extra-file rules against the profiles and header readers, and each part of `install/games/` (setups, fallback sets, systems, arcade, the index and its coverage floors) |
|
||||
|
||||
Reference in new issue
Block a user