Spaces:
Sleeping
Sleeping
File size: 8,254 Bytes
7a5c442 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 | #!/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,<y, with
# optional extras and markers.
pattern = re.compile(
r"""
^ # start
[A-Za-z0-9][A-Za-z0-9._-]* # project name
(\[[A-Za-z0-9,_.-]+\])? # optional extras: [extra1,extra2]
\s*
( # optional version specifier
(==|!=|<=|>=|<|>|~=)\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())
|