Download lingologos_python/gates.py from tailot/codex-python: direct link, hf CLI and curl.
- Browser
- Download file 9.69 kB
-
https://huggingface.co/datasets/tailot/codex-python/resolve/main/lingologos_python/gates.py
- Command line
-
hf download hf://datasets/tailot/codex-python/lingologos_python/gates.py
-
curl -L -o gates.py https://huggingface.co/datasets/tailot/codex-python/resolve/main/lingologos_python/gates.py
9.69 kB
| """Python quality and test gates with strict three-valued outcomes. | |
| Every gate returns GateResult(CONFIRMED | REJECTED | ABSTAIN). A missing | |
| toolchain never produces CONFIRMED or REJECTED; it returns ABSTAIN with a | |
| clear diagnostic note so the codex decision rule can block honestly. | |
| """ | |
| from __future__ import annotations | |
| import ast | |
| import importlib.util | |
| import re | |
| import shutil | |
| import sys | |
| from pathlib import Path | |
| from typing import TYPE_CHECKING, List, Sequence, Tuple | |
| from lingologos_python._codex_bridge import ensure_codex_on_path | |
| ensure_codex_on_path() | |
| from lingologos_codex.types import ABSTAIN, CONFIRMED, REJECTED, GateResult # noqa: E402 | |
| if TYPE_CHECKING: | |
| from lingologos_codex.adapter_contract import BaseLanguageAdapter | |
| FAILED_TARGET_PATTERNS: Tuple[str, ...] = ( | |
| r"FAILED (?P<target>[\w./\\-]+(?:::\S+)?)", | |
| r"^(?P<target>[\w./\\-]+\.py):\d+:", | |
| r'E\s+File "(?P<target>[^"]+)"', | |
| r'File "(?P<target>[^"]+\.py)", line \d+', | |
| r"ERROR: .* \((?P<target>[\w./\\-]+\.py)\)", | |
| ) | |
| SIGNATURE_RULES: Tuple[Tuple[str, str], ...] = ( | |
| (r"in [\d.]+s", "in <t>"), | |
| (r"Ran \d+ tests? in [\d.]+s", "Ran <n> tests in <t>"), | |
| (r"rootdir: \S+", "rootdir: <path>"), | |
| (r"plugins?: \S.*", "plugins: <set>"), | |
| (r"Found \d+ errors? in \d+ files?", "Found <n> errors in <m> files"), | |
| ) | |
| def _read_text_state(cwd: Path, rel: str) -> Tuple[str | None, str]: | |
| """Return (source, state) for one workspace file: ok, missing, undecodable or unreadable.""" | |
| target = cwd / Path(*rel.replace("\\", "/").split("/")) | |
| if not target.is_file() or target.is_symlink(): | |
| return None, "missing" | |
| try: | |
| # utf-8-sig: a byte-order mark is not part of the code, and the compiler | |
| # reading the file would skip it the same way. | |
| return target.read_text(encoding="utf-8-sig"), "ok" | |
| except UnicodeDecodeError: | |
| return None, "undecodable" | |
| except OSError: | |
| return None, "unreadable" | |
| def has_python_module(module_name: str) -> bool: | |
| """Return True when module_name is importable in the active Python interpreter.""" | |
| return importlib.util.find_spec(module_name) is not None | |
| def resolve_tool_argv(tool: str) -> List[str] | None: | |
| """Resolve a CLI tool binary on PATH or via python -m <tool>.""" | |
| binary = shutil.which(tool) | |
| if binary: | |
| return [binary] | |
| if has_python_module(tool): | |
| return [sys.executable, "-m", tool] | |
| return None | |
| def run_syntax_gate(cwd: Path, target_files: Sequence[str]) -> GateResult: | |
| """Validate Python syntax and code-object compilation in memory without writing .pyc.""" | |
| files = [f.replace("\\", "/") for f in target_files if f] | |
| if not files: | |
| return GateResult(CONFIRMED, "ast.parse + compile (no target files)") | |
| broken: List[str] = [] | |
| failed: List[str] = [] | |
| silent: List[str] = [] | |
| for rel in files: | |
| source, state = _read_text_state(cwd, rel) | |
| if state == "missing": | |
| broken.append(f"{rel}: missing") | |
| failed.append(rel) | |
| continue | |
| if source is None: | |
| # A file that is not UTF-8 text gives the gate nothing to parse. Calling | |
| # that a syntax error would be a lie about the file, and calling it a | |
| # pass would be a lie about the gate: it simply has no judgement. | |
| silent.append(f"{rel}: {state}") | |
| continue | |
| try: | |
| tree = ast.parse(source, filename=rel) | |
| compile(tree, filename=rel, mode="exec", dont_inherit=True) | |
| except SyntaxError as exc: | |
| broken.append(f"{rel}: line {exc.lineno}: {exc.msg}") | |
| failed.append(rel) | |
| except ValueError as exc: | |
| broken.append(f"{rel}: {exc}") | |
| failed.append(rel) | |
| command = "ast.parse " + " ".join(files) | |
| if broken: | |
| return GateResult( | |
| REJECTED, | |
| command, | |
| output="\n".join(broken), | |
| failed_targets=tuple(failed), | |
| note=f"{len(broken)} file(s) failed syntax verification", | |
| ) | |
| if silent: | |
| return GateResult( | |
| ABSTAIN, | |
| command, | |
| output="\n".join(silent), | |
| note=f"{len(silent)} file(s) could not be read as UTF-8 text, the gate has no judgement on them", | |
| ) | |
| return GateResult(CONFIRMED, command) | |
| def run_tool_gate( | |
| adapter: BaseLanguageAdapter, | |
| cwd: Path, | |
| tool: str, | |
| args: Sequence[str], | |
| target_files: Sequence[str], | |
| ) -> GateResult: | |
| """Run an external Python static checker or return ABSTAIN when unavailable.""" | |
| argv_prefix = resolve_tool_gate_prefix(tool) | |
| if argv_prefix is None: | |
| return GateResult( | |
| ABSTAIN, | |
| f"{tool} {' '.join(args)}".strip(), | |
| note=f"{tool} is not installed on this host, the gate has no judgement", | |
| ) | |
| if not target_files: | |
| return GateResult(CONFIRMED, f"{tool} (no target files)") | |
| return adapter.run_command( | |
| cwd.as_posix(), | |
| [*argv_prefix, *args, *[f.replace("\\", "/") for f in target_files]], | |
| gate_name=tool, | |
| ) | |
| def resolve_tool_gate_prefix(tool: str) -> List[str] | None: | |
| """Resolve supported Python static analysis tools.""" | |
| return resolve_tool_argv(tool) | |
| def _ran_no_tests(output: str) -> bool: | |
| """True when a test runner reported that it ran zero tests.""" | |
| low = (output or "").lower() | |
| return "no tests ran" in low or "ran 0 tests" in low | |
| def _zero_run_is_an_abstain(gate: GateResult) -> GateResult: | |
| """A runner that collected nothing cannot confirm or reject anything. | |
| The unittest fallback imports the target module and asks unittest to collect | |
| it. Tests written for pytest stay invisible there, so unittest reports an | |
| empty run and exits. Reporting that as REJECTED would invent a failure, and | |
| as CONFIRMED would invent a pass, so the gate abstains and says so. | |
| """ | |
| if _ran_no_tests(gate.output or ""): | |
| return GateResult( | |
| ABSTAIN, | |
| gate.command, | |
| output=gate.output, | |
| note="the test runner collected no tests, the gate has no judgement", | |
| ) | |
| return gate | |
| def _unittest_module_names(targets: Sequence[str]) -> Tuple[List[str], List[str]]: | |
| """Map relative test paths to importable dotted module names for unittest.""" | |
| names: List[str] = [] | |
| unmapped: List[str] = [] | |
| for target in targets: | |
| parts = [p for p in target.replace("\\", "/").split("/") if p and p != "."] | |
| if parts and parts[-1].endswith(".py"): | |
| parts = [*parts[:-1], parts[-1][:-3]] | |
| if parts and parts[-1] == "__init__": | |
| parts = parts[:-1] | |
| if not parts or ".." in parts or not all(p.isidentifier() for p in parts): | |
| unmapped.append(target) | |
| continue | |
| names.append(".".join(parts)) | |
| return names, unmapped | |
| def run_python_tests( | |
| adapter: BaseLanguageAdapter, | |
| cwd: Path, | |
| targets: Sequence[str], | |
| full_suite: bool = False, | |
| ) -> GateResult: | |
| """Run pytest (no cacheprovider) or fall back to unittest discovery.""" | |
| pytest_binary = shutil.which("pytest") | |
| if has_python_module("pytest"): | |
| # The active interpreter runs its own pytest, so the gate judges the same | |
| # environment the adapter and the kernel are running in. | |
| argv = [sys.executable, "-m", "pytest", "-q", "-p", "no:cacheprovider"] | |
| elif pytest_binary: | |
| argv = [pytest_binary, "-q", "-p", "no:cacheprovider"] | |
| else: | |
| argv = None | |
| if argv is not None: | |
| if full_suite or not targets: | |
| return _zero_run_is_an_abstain( | |
| adapter.run_command(cwd.as_posix(), argv, gate_name="full_regression") | |
| ) | |
| return _zero_run_is_an_abstain( | |
| adapter.run_command( | |
| cwd.as_posix(), | |
| argv + [t.replace("\\", "/") for t in targets], | |
| gate_name="selected_tests", | |
| ) | |
| ) | |
| if has_python_module("unittest"): | |
| if full_suite or not targets: | |
| argv = [sys.executable, "-m", "unittest", "discover", "-q"] | |
| return _zero_run_is_an_abstain( | |
| adapter.run_command(cwd.as_posix(), argv, gate_name="full_regression") | |
| ) | |
| modules, unmapped = _unittest_module_names(targets) | |
| if unmapped: | |
| # unittest takes importable names, not file paths. Passing a path | |
| # through would exit with an import error that says nothing about | |
| # the code, so the gate refuses to judge rather than misjudge. | |
| return GateResult( | |
| ABSTAIN, | |
| "python -m unittest -q " + " ".join(str(t) for t in unmapped), | |
| note="these targets are not importable module names for the unittest fallback: " | |
| + ", ".join(str(t) for t in unmapped), | |
| ) | |
| argv = [sys.executable, "-m", "unittest", "-q", *modules] | |
| return _zero_run_is_an_abstain( | |
| adapter.run_command(cwd.as_posix(), argv, gate_name="selected_tests") | |
| ) | |
| return GateResult( | |
| ABSTAIN, | |
| "python -m pytest", | |
| note="neither pytest nor unittest is available in this interpreter", | |
| ) | |
| def parse_failed_targets(output: str) -> Tuple[str, ...]: | |
| """Extract normalized failed target paths or node ids from Python tool output.""" | |
| found: List[str] = [] | |
| for pattern in FAILED_TARGET_PATTERNS: | |
| for match in re.finditer(pattern, output, re.MULTILINE): | |
| value = match.group("target").replace("\\", "/") | |
| if value and value not in found: | |
| found.append(value) | |
| return tuple(found[:50]) | |