#!/usr/bin/env python3 """ icat_app structural validator. Non-interactive checks intended to run locally on Windows + Linux and in CI via .github/workflows/repo_validate.yml. Exits non-zero on the first failure so the diagnostic is unambiguous. Checks performed: 1. py_compile every tracked *.py file (catches syntax errors anywhere in the repo, not just in changed files — ruff via gate.yml only sees changed files). 2. requirements.txt is parseable as PEP 508 requirement lines, with line comments and blank lines tolerated. 3. README.md HF Spaces frontmatter contains the expected keys with sensible values (title, sdk, sdk_version, app_file, python_version). Usage: python scripts/repo_validate.py Exit codes: 0 all checks passed 1 at least one check failed (details printed to stderr before exit) """ from __future__ import annotations import ast import py_compile import re import subprocess import sys from pathlib import Path REPO_ROOT = Path(__file__).resolve().parent.parent # README HF frontmatter keys we expect. These must match the actual values that # the HF Spaces runner cares about. Update this list (and update the doc tree) # if HF Spaces changes its frontmatter contract. REQUIRED_README_FRONTMATTER_KEYS = { "title", "sdk", "sdk_version", "app_file", "python_version", } def _log_failure(check: str, message: str) -> None: print(f"[repo_validate] FAIL {check}: {message}", file=sys.stderr) def _log_pass(check: str, detail: str = "") -> None: suffix = f" — {detail}" if detail else "" print(f"[repo_validate] PASS {check}{suffix}") def _tracked_python_files() -> list[Path]: """Return every tracked *.py file. Uses git ls-files when available; falls back to a filesystem walk otherwise.""" try: result = subprocess.run( ["git", "ls-files", "*.py"], cwd=REPO_ROOT, check=True, capture_output=True, text=True, ) rel_paths = [line for line in result.stdout.splitlines() if line.strip()] return [REPO_ROOT / p for p in rel_paths] except (subprocess.CalledProcessError, FileNotFoundError): # Fallback: walk the tree. Best-effort; will include ignored files, # which is acceptable since this branch is only hit when git is not # available (very unusual). return [ p for p in REPO_ROOT.rglob("*.py") if "__pycache__" not in p.parts and ".venv" not in p.parts ] def check_py_compile() -> bool: """Run py_compile on every tracked *.py. Report all failures, exit on aggregate.""" files = _tracked_python_files() if not files: _log_failure("py_compile", "no Python files found — repo is empty?") return False failures: list[tuple[Path, str]] = [] for path in files: try: py_compile.compile(str(path), doraise=True) except py_compile.PyCompileError as exc: failures.append((path, str(exc))) except OSError as exc: failures.append((path, f"could not read file: {exc}")) if failures: for path, msg in failures: _log_failure("py_compile", f"{path.relative_to(REPO_ROOT)}: {msg}") return False _log_pass("py_compile", f"{len(files)} file(s) compiled cleanly") return True def check_requirements_parseable() -> bool: """Verify every non-blank, non-comment line in requirements.txt looks like a PEP 508 requirement. We don't resolve them — that is the installer's job — we just confirm the file is structurally sane.""" req_file = REPO_ROOT / "requirements.txt" if not req_file.exists(): _log_failure("requirements", "requirements.txt missing") return False # PEP 508 is rich. We use a conservative regex that allows the common # forms used in this repo: name, name==x, name>=x, name>=x,=|<|>|~=)\s*[A-Za-z0-9.*+!_-]+ (\s*,\s*(==|!=|<=|>=|<|>|~=)\s*[A-Za-z0-9.*+!_-]+)* )? (\s*;\s*[^#]+)? # optional PEP 508 marker \s*(\#.*)? # optional trailing comment $ """, re.VERBOSE, ) lines = req_file.read_text(encoding="utf-8").splitlines() bad: list[tuple[int, str]] = [] parsed = 0 for n, raw in enumerate(lines, 1): line = raw.strip() if not line or line.startswith("#"): continue if not pattern.match(line): bad.append((n, raw)) continue parsed += 1 if bad: for n, raw in bad: _log_failure( "requirements", f"requirements.txt line {n}: not a recognizable PEP 508 requirement: {raw!r}", ) return False _log_pass("requirements", f"{parsed} requirement line(s) parsed") return True def check_readme_frontmatter() -> bool: """Verify README.md starts with an HF Spaces YAML frontmatter block and contains the keys HF Spaces expects.""" readme = REPO_ROOT / "README.md" if not readme.exists(): _log_failure("readme_frontmatter", "README.md missing") return False text = readme.read_text(encoding="utf-8") if not text.startswith("---\n") and not text.startswith("---\r\n"): _log_failure( "readme_frontmatter", "README.md does not start with an HF Spaces YAML frontmatter delimiter (---).", ) return False # Find the closing delimiter body = text.split("\n", 1)[1] if text.startswith("---\n") else text.split("\r\n", 1)[1] closing_match = re.search(r"^---\s*$", body, re.MULTILINE) if not closing_match: _log_failure( "readme_frontmatter", "README.md frontmatter has no closing --- delimiter.", ) return False frontmatter_text = body[: closing_match.start()] # Minimal YAML key:value parser sufficient for HF frontmatter (flat key/value pairs). found_keys: set[str] = set() for line in frontmatter_text.splitlines(): stripped = line.strip() if not stripped or stripped.startswith("#"): continue if ":" in stripped: key = stripped.split(":", 1)[0].strip() found_keys.add(key) missing = REQUIRED_README_FRONTMATTER_KEYS - found_keys if missing: _log_failure( "readme_frontmatter", f"missing required HF Spaces frontmatter key(s): {sorted(missing)}", ) return False _log_pass("readme_frontmatter", f"frontmatter has {sorted(found_keys & REQUIRED_README_FRONTMATTER_KEYS)}") return True def main() -> int: print(f"[repo_validate] repo root: {REPO_ROOT}") checks = [ ("py_compile", check_py_compile), ("requirements", check_requirements_parseable), ("readme_frontmatter", check_readme_frontmatter), ] overall_ok = True for name, fn in checks: ok = fn() if not ok: overall_ok = False # Fail fast keeps the diagnostic obvious. If you want to see all # failures in one run, comment out the next line. print(f"[repo_validate] stopping after first failure ({name})", file=sys.stderr) return 1 if overall_ok: print("[repo_validate] all checks passed") return 0 return 1 if __name__ == "__main__": # Sanity import-guard for older Python versions (HF Space runs 3.12, but # the local dev machine may be 3.11 or earlier on Windows). if sys.version_info < (3, 9): print("[repo_validate] requires Python 3.9 or later", file=sys.stderr) sys.exit(1) # ast import is here only so a typo above is caught by py_compile when this # very file is validated by the script itself. _ = ast sys.exit(main())