code-review-lab / demo /src /validation.py
alirezaaminzadeh's picture
Publish CodeReview Python lab diffs and versioned ruleset
32e0071 verified
Raw History Blame Contribute Delete
2.25 kB
from __future__ import annotations
from src.domain import LANGUAGE, MAX_BYTES, MAX_CHANGED_LINES, MAX_FILES, MAX_RELATED_FILES
from src.schemas import ChangeSet, ValidationReport
def empty_report() -> ValidationReport:
return ValidationReport(ok=True)
def validate_size(text: str, label: str) -> ValidationReport:
report = empty_report()
if text is None:
report.add("empty", f"{label} is missing.", label)
return report
raw = text.encode("utf-8")
if len(raw) == 0 or not str(text).strip():
report.add("empty", f"{label} is empty.", label)
if len(raw) > MAX_BYTES:
report.add("too_large", f"{label} exceeds {MAX_BYTES} bytes.", label)
return report
def validate_changeset(change: ChangeSet | None, required: bool = True) -> ValidationReport:
report = empty_report()
if change is None:
if required:
report.add("missing_diff", "The change could not be parsed.", "diff")
return report
if not change.files:
report.add("no_files", "The diff contains no Python files.", "diff")
if len(change.files) > MAX_FILES:
report.add("too_many_files", f"More than {MAX_FILES} files were changed.", "diff")
if change.changed_line_count > MAX_CHANGED_LINES:
report.add(
"too_many_lines",
f"The change has {change.changed_line_count} lines; the cap is {MAX_CHANGED_LINES}.",
"diff",
)
if len(change.related) > MAX_RELATED_FILES:
report.add("too_many_related", f"More than {MAX_RELATED_FILES} related files were provided.", "related")
for item in change.files:
if not item.path.endswith(".py"):
report.add("unsupported_language", f"{item.path} is not Python. MVP language is {LANGUAGE}.", item.path)
if item.after and len(item.after.encode("utf-8")) > MAX_BYTES:
report.add("too_large", f"{item.path} exceeds {MAX_BYTES} bytes.", item.path)
return report
def merge_reports(*reports: ValidationReport) -> ValidationReport:
out = empty_report()
for report in reports:
if report is None:
continue
out.issues.extend(report.issues)
if not report.ok:
out.ok = False
return out