File size: 8,619 Bytes
4bc63c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Locate, plan, apply, prove. The edit pair is one transaction.

Section 5 of SPECIFICATION.md: the source edit and the lock test are written together or
not at all. The honesty gate reads the pair back from disk and refuses when the test was
not written first in the record, or when the edit removed an assertion.
"""

import ast
import os
import shutil
import subprocess
import sys
from typing import Any, Dict, List, Optional, Tuple

from . import catalog, preflight, shapes

TEST_DIR = "tests"
RECORD_NAME = "_thinkingpython_locks"


def locate(workspace: str, frame: str, anchor: Optional[str],
           entries: List[Dict[str, Any]]) -> Tuple[List[Dict[str, Any]], List[str]]:
    """Return candidates: {file, target, entry} plus reasons."""
    reasons: List[str] = []
    found: List[Dict[str, Any]] = []
    for rel in preflight.python_files(workspace):
        if rel.startswith(TEST_DIR + "/"):
            continue
        path = os.path.join(workspace, rel)
        try:
            with open(path, "r", encoding="utf-8") as handle:
                source = handle.read()
        except (OSError, UnicodeDecodeError):
            reasons.append("NOT_ASCII_TARGET")
            continue
        hits, why = shapes.match(frame, source)
        if not hits:
            if why and why != "NO_SHAPE":
                reasons.append(why)
            continue
        if anchor:
            picked = [h for h in hits if h.get("symbol") == anchor] or hits
        else:
            picked = hits
        entry = catalog.by_id(entries, frame) or {}
        for target in picked:
            found.append({"file": rel, "target": target, "entry": entry,
                          "evidence": target.get("evidence", "")})
    if not found:
        reasons.append("NO_MATCH")
    return found[:catalog.MAX_CANDIDATES], sorted(set(reasons))


def plan(candidate: Dict[str, Any]) -> Dict[str, Any]:
    """The plan is language free: frame, file, line window, edits, lock."""
    entry = candidate["entry"]
    rel = candidate["file"]
    target = candidate["target"]
    with open(os.path.join(os.getcwd(), rel) if not os.path.isabs(rel) else rel,
              "r", encoding="utf-8") as handle:
        source = handle.read()
    return {"frame": entry.get("id", ""), "file": rel, "line": target["line"],
            "end": target["end"], "symbol": target["symbol"],
            "edits": shapes.edits(entry.get("id", ""), rel, source, target),
            "lock": shapes.lock(entry.get("id", ""), target),
            "expected": list(entry.get("refusals") or [])}


def run_suite(workspace: str, timeout: int = 120) -> Dict[str, Any]:
    try:
        proc = subprocess.run([sys.executable, "-m", "pytest", "-q", "--no-header", TEST_DIR],
                              cwd=workspace, capture_output=True, text=True, timeout=timeout)
    except subprocess.TimeoutExpired:
        return {"status": "SUITE_RED", "output": "timeout"}
    out = (proc.stdout or "") + (proc.stderr or "")
    return {"status": "GREEN" if proc.returncode == 0 else "SUITE_RED", "output": out[-4000:]}


def _drops_assertion(edits: List[Dict[str, str]], source: str) -> bool:
    for edit in edits:
        if "assert" in (edit.get("search") or "") and "assert" not in (edit.get("replace") or ""):
            return True
    projected = source
    for edit in edits:
        if edit.get("search"):
            projected = projected.replace(edit["search"], edit.get("replace", ""), 1)
    try:
        before = sum(1 for n in ast.walk(ast.parse(source)) if isinstance(n, ast.Assert))
        after = sum(1 for n in ast.walk(ast.parse(projected)) if isinstance(n, ast.Assert))
    except SyntaxError:
        return False
    return after < before


def apply_pair(workspace: str, planned: Dict[str, Any]) -> Dict[str, Any]:
    """Write source edit and lock test in one transaction. Returns a receipt."""
    if not planned.get("edits"):
        return {"applied": False, "reason": "NO_EDIT"}
    probe = os.path.join(workspace, TEST_DIR, "test_lock_%s.py" % planned["symbol"])
    if os.path.exists(probe):
        return {"applied": False, "reason": "ALREADY_APPLIED"}
    try:
        with open(os.path.join(workspace, plan_rel(planned)), "r", encoding="utf-8") as handle:
            original_source = handle.read()
    except OSError:
        return {"applied": False, "reason": "SEARCH_NOT_FOUND"}
    if _drops_assertion(planned["edits"], original_source):
        return {"applied": False, "reason": "ASSERTION_REMOVED"}
    backup: Dict[str, Optional[str]] = {}
    written: List[str] = []
    try:
        for edit in planned["edits"]:
            rel = edit["file"]
            path = os.path.join(workspace, rel)
            if os.path.islink(path):
                raise OSError("LINKED_PATH_IN_WORKSPACE")
            with open(path, "r", encoding="utf-8") as handle:
                original = handle.read()
            if rel not in backup:
                backup[rel] = original
            if edit["search"] not in original:
                raise ValueError("SEARCH_NOT_FOUND")
            new = original.replace(edit["search"], edit["replace"], 1)
            ast.parse(new)
            with open(path, "w", encoding="utf-8") as handle:
                handle.write(new)
            written.append(rel)
        lock_path = os.path.join(workspace, TEST_DIR, "test_lock_%s.py" % planned["symbol"])
        os.makedirs(os.path.dirname(lock_path), exist_ok=True)
        if os.path.exists(lock_path):
            raise ValueError("ALREADY_APPLIED")
        backup[os.path.relpath(lock_path, workspace).replace("\\", "/")] = None
        with open(lock_path, "w", encoding="utf-8") as handle:
            handle.write(_lock_header(plan_rel(planned)) + planned["lock"])
        written.append(os.path.relpath(lock_path, workspace).replace("\\", "/"))
    except Exception as exc:  # rollback
        reason = str(exc) if str(exc) in ("LINKED_PATH_IN_WORKSPACE", "ALREADY_APPLIED") \
            else "PAIR_DISHONEST"
        for rel, original in backup.items():
            path = os.path.join(workspace, rel)
            if original is None:
                if os.path.exists(path):
                    os.remove(path)
            else:
                with open(path, "w", encoding="utf-8") as handle:
                    handle.write(original)
        for rel in written:
            path = os.path.join(workspace, rel)
            if os.path.exists(path) and backup.get(rel) is None:
                os.remove(path)
        return {"applied": False, "reason": reason}
    return {"applied": True, "files": written}


def plan_rel(planned: Dict[str, Any]) -> str:
    return str(planned.get("file", "")).replace("\\", "/")


def _lock_header(rel: str) -> str:
    return (
        '"""Lock test written with the edit that it pins. Do not edit by hand."""\n'
        "import ast\n"
        "import os\n\n"
        "ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n"
        "TARGET = os.path.join(ROOT, %(rel)r)\n\n"
        "def _source():\n"
        "    with open(TARGET, 'r', encoding='utf-8') as handle:\n"
        "        return handle.read()\n\n"
        "def _tree():\n"
        "    return ast.parse(_source())\n\n"
        "def _is_doc(stmt):\n"
        "    return (isinstance(stmt, ast.Expr) and isinstance(stmt.value, ast.Constant)\n"
        "            and isinstance(stmt.value.value, str))\n\n"
        "def _function(name):\n"
        "    for node in ast.walk(_tree()):\n"
        "        if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name == name:\n"
        "            return node\n"
        "    raise AssertionError('no function named ' + name)\n\n"
        "def _imports_name(src, name):\n"
        "    tree = ast.parse(src)\n"
        "    for node in ast.walk(tree):\n"
        "        if isinstance(node, ast.Import):\n"
        "            for alias in node.names:\n"
        "                if (alias.asname or alias.name).split('.')[0] == name:\n"
        "                    return True\n"
        "        if isinstance(node, ast.ImportFrom):\n"
        "            for alias in node.names:\n"
        "                if (alias.asname or alias.name) == name:\n"
        "                    return True\n"
        "    return False\n\n"
    ) % {"rel": rel}


def verdict(receipt: Dict[str, Any], suite: Dict[str, Any]) -> Tuple[str, str]:
    if not receipt.get("applied"):
        return "REFUSED", receipt.get("reason", "NO_EDIT")
    if suite["status"] != "GREEN":
        return "REFUSED", suite["status"]
    return "VERIFIED", ""