refactor: move the review's glue to devtools

This commit is contained in:
Abdessamad Derraz committed 2026-11-22 00:58:05 +01:00
1 parent 19bcc76c8f
commit e146a8f349
9 files changed
+40 -29

No files matched your search

+1 -1
View File
@@ -1 +1 @@
"""The repository's own tooling: commit rules, pull request checks, the test runner, disk cleanup, the bios/ migration."""
"""The repository's own tooling: commit rules, pull request checks, the BIOS review's files and report, the test runner, disk cleanup, the bios/ migration."""
+111
View File
@@ -0,0 +1,111 @@
"""The files a review reads and writes: a branch's changed BIOS files, folders expanded, files placed."""
from __future__ import annotations
import os
import shutil
import sys
from pathlib import Path
from typing import TYPE_CHECKING
from core.gitclone import compare_base, git_lines
if TYPE_CHECKING:
from resolve.review import ValidationResult
def get_changed_files() -> list[str]:
"""BIOS files this checkout changes against the project's main line.
Committed changes are read against the project's main line: the remote
that names the project (upstream/<base> first, then origin/<base>), or
the project's main fetched when no remote does. Uncommitted and
untracked files count too,
since CONTRIBUTING has the file copied into bios/ before any commit.
A git that fails outright is an error, never "nothing changed".
"""
changed: list[str] = []
base = compare_base()
committed = git_lines("diff", "--name-only", f"{base}...HEAD") if base else None
compared = committed is not None
changed.extend(committed or [])
staged = git_lines("diff", "--cached", "--name-only")
local = git_lines("diff", "--name-only")
untracked = git_lines("ls-files", "--others", "--exclude-standard", "--", "bios")
if staged is None and local is None and untracked is None:
raise RuntimeError("git cannot read this checkout")
for found in (staged, local, untracked):
changed.extend(found or [])
if not compared:
print(
"no upstream/ or origin/ main line to compare against, reading the "
"staged, modified and untracked files only",
file=sys.stderr,
)
return [f for f in dict.fromkeys(changed) if f.startswith("bios/") and os.path.isfile(f)]
def expand_folders(paths: list[str]) -> list[str]:
"""Each folder named replaced by the files under it, subfolders included.
A card's BIOS folder was refused as "Not a regular file", and the
contributor had to list its files by hand. A link inside the folder
stays listed, so it is refused like a named one, and an empty folder
stays as itself to be reported.
"""
out: list[str] = []
for path in paths:
if not os.path.isdir(path) or os.path.islink(path):
out.append(path)
continue
found = sorted(
str(f) for f in Path(path).rglob("*") if f.is_symlink() or f.is_file()
)
out.extend(found or [path])
return out
class SelectionError(ValueError):
"""The files named and --changed do not select a set to review."""
class ChangedFilesUnreadable(Exception):
"""git could not say which files this checkout changes."""
def files_to_validate(files: list[str], changed: bool) -> list[str]:
"""The files named on the command line, or the changed ones."""
if changed and files:
# Named files were dropped for the git diff, and the run reported
# "No changed BIOS files detected" about files it never looked at.
raise SelectionError("--changed reads the git diff: name files or pass --changed, not both")
if not changed:
if not files:
raise SelectionError("No files specified. Use --changed or provide file paths.")
return expand_folders(files)
try:
return get_changed_files()
except (RuntimeError, OSError) as exc:
raise ChangedFilesUnreadable(str(exc)) from exc
def place(results: list[ValidationResult]) -> list[str]:
"""Copy each placeable file to its destination, never over a file.
The report named the folder of each file and left 40 copies from a card
to be made by hand, each .variants/ name retyped. The source is copied,
not moved: it is often a card or another tree the contributor keeps.
"""
placed = []
for r in results:
if not (r.passed and r.destination and not r.outcome):
continue
target = Path(r.destination)
if target.exists():
print(f"not placed: {target} exists", file=sys.stderr)
continue
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(r.filepath, target)
placed.append(r.destination)
print(f"placed {r.filepath} at {r.destination}", file=sys.stderr)
return placed
+64
View File
@@ -0,0 +1,64 @@
"""A review's results as JSON rows, a pull request comment, or terminal lines."""
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from resolve.review import ValidationResult
# The terminal's word for each check status. Any other status is "info".
MARKERS = {"PASS": "ok", "FAIL": "fail", "WARN": "warn"}
def json_rows(results: list[ValidationResult]) -> list[dict]:
"""One JSON object per file reviewed."""
return [
{
"file": r.filepath,
"passed": r.passed,
# A file that failed, unread or refused, is not a new one.
"outcome": r.outcome or ("new" if r.passed else "failed"),
"destination": r.destination,
"sha1": r.sha1,
"md5": r.md5,
"size": r.size,
"checks": [{"status": s, "message": m} for s, m in r.checks],
}
for r in results
]
def markdown_report(results: list[ValidationResult]) -> str:
"""The report posted as a pull request comment."""
lines = ["## BIOS Validation Report", ""]
held = sum(r.outcome == "held" for r in results)
unknown = sum(r.outcome == "unknown" for r in results)
review = ", ".join(part for part in (
f"{held} already held" if held else "",
f"{unknown} not recognised" if unknown else "",
) if part)
status = ("some checks failed" if not all(r.passed for r in results)
else f"no check failed, to review: {review}" if review
else "all checks passed")
lines.append(f"**Status**: {status}")
lines.append("")
for r in results:
lines.append(r.to_markdown())
lines.append("")
return "\n".join(lines)
def text_lines(results: list[ValidationResult]) -> list[str]:
"""The terminal report, each file headed by a blank line."""
lines: list[str] = []
for r in results:
lines.extend(("", f"[{r.status}] {r.filepath}"))
if r.sha1:
lines.append(f" SHA1: {r.sha1}")
lines.append(f" MD5: {r.md5}")
lines.append(f" Size: {r.size:,}")
lines.extend(f" [{MARKERS.get(s, 'info')}] {m}" for s, m in r.checks)
return lines