Files
claude-config/bin/touch_predictions/file_parts.py
T

96 lines
4.6 KiB
Python

"""The parts of a file that given lines lie in, by the names a prediction uses for them.
Where each language's boundaries come from:
- Python, a path ending .py: the standard `ast` module. A part is a function or class, named with the classes and functions around it, as in `Plan.branch`; a top-level assignment, by the name it sets; or `(module)` for any other top-level line.
- Markdown, a path ending .md: the heading lines outside fenced code. A part is the nearest heading above, spelt as its line, as in `## Goals`; `(top)` before the first.
- Any other file, and Python that doesn't parse: no names, so diff_parts falls back to line ranges.
A separator is a blank line that Python holds between two statements, or Markdown anywhere. It names no part: git ends the hunk of an inserted function with the blank lines after it, and opens an appended section's with the one before it."""
import ast
import io
import re
import typing
MODULE = "(module)"
TOP = "(top)"
HEADING = re.compile(r"#{1,6} \S")
FENCE = re.compile(r" {0,3}(`{3,}|~{3,})(.*)")
DEFINITION = ast.FunctionDef | ast.AsyncFunctionDef | ast.ClassDef
def part_names(path: str, text: str, lines: typing.Iterable[int], separators: bool = False) -> set[str] | None:
"""The part each of lines, counted from 1, lies in; None where the file's kind has no names. A separator among lines names its part only where separators is set."""
if path.endswith(".py"):
return python_parts(text, lines, separators)
if path.endswith(".md"):
return markdown_parts(text, lines, separators)
return None
def python_parts(text: str, lines: typing.Iterable[int], separators: bool) -> set[str] | None:
try:
tree = ast.parse(text)
except (SyntaxError, ValueError):
return None
# Each top-level statement's first and last line, then each part's with its name.
statements = [(first_line(statement), statement.end_lineno or statement.lineno) for statement in tree.body]
spans = [(*lines_, assigned(statement)) for lines_, statement in zip(statements, tree.body) if not isinstance(statement, DEFINITION)]
spans.extend(nested(tree, ""))
blank = {number for number, row in enumerate(io.StringIO(text), 1) if not row.strip()}
names: set[str] = set()
for line in lines:
if not any(first <= line <= last for first, last in statements):
if line in blank and not separators:
continue
if not statements:
names.add(MODULE)
continue
# A line between two statements, such as a comment, goes with the one below it; one after the last, with the last.
line = min((first for first, _ in statements if first > line), default=statements[-1][0])
names.add(max((span for span in spans if span[0] <= line <= span[1]), key=lambda span: span[0])[2])
return names
def nested(node: ast.AST, prefix: str) -> list[tuple[int, int, str]]:
"""Each function and class under node, at any depth, named from prefix."""
found = []
for child in ast.iter_child_nodes(node):
if isinstance(child, DEFINITION):
found.append((first_line(child), child.end_lineno or child.lineno, prefix + child.name))
found.extend(nested(child, f"{prefix}{child.name}."))
else:
found.extend(nested(child, prefix))
return found
def first_line(statement: ast.stmt) -> int:
"""A statement's first line, which is its first decorator's where it has one."""
return min([statement.lineno, *(decorator.lineno for decorator in getattr(statement, "decorator_list", []))])
def assigned(statement: ast.stmt) -> str:
"""The part a top-level statement that is no function or class makes: the one name it assigns, else the module."""
targets = statement.targets if isinstance(statement, ast.Assign) else [statement.target] if isinstance(statement, ast.AnnAssign) else []
return targets[0].id if len(targets) == 1 and isinstance(targets[0], ast.Name) else MODULE
def markdown_parts(text: str, lines: typing.Iterable[int], separators: bool) -> set[str]:
wanted, names = set(lines), set()
# fence is the run of characters that opened the fenced code a line lies in, and empty outside one.
heading, fence = TOP, ""
for number, line in enumerate(text.splitlines(), 1):
found = FENCE.match(line)
if fence:
# CommonMark: a fence closes on a run of its own character, at least as long, with no text after it.
if found and found.group(1).startswith(fence) and not found.group(2).strip():
fence = ""
elif found:
fence = found.group(1)
elif HEADING.match(line):
heading = line.rstrip()
if number in wanted and (separators or line.strip()):
names.add(heading)
# A line past the end, as a deletion at the end names, lies under the last heading.
return names | ({heading} if any(line > len(text.splitlines()) for line in wanted) else set())