File size: 6,009 Bytes
2a9dc4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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_safe(cwd: Path, rel: str) -> str | None:
    target = cwd / Path(*rel.replace("\\", "/").split("/"))
    if not target.is_file() or target.is_symlink():
        return None
    try:
        return target.read_text(encoding="utf-8", errors="replace")
    except OSError:
        return None


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] = []
    for rel in files:
        source = _read_text_safe(cwd, rel)
        if source is None:
            broken.append(f"{rel}: unreadable or missing")
            failed.append(rel)
            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",
        )
    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 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."""
    if resolve_tool_argv("pytest") is not None:
        argv = [sys.executable, "-m", "pytest", "-q", "-p", "no:cacheprovider"]
        if full_suite or not targets:
            return adapter.run_command(cwd.as_posix(), argv, gate_name="full_regression")
        return 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 adapter.run_command(cwd.as_posix(), argv, gate_name="full_regression")
        argv = [sys.executable, "-m", "unittest", "-q", *[t.replace("\\", "/") for t in targets]]
        return 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])