context-pack.py: reads, symbol checks and capped caller lists
Read anchors resolve like file_changes (r<k> rows, MISSING when absent at base), anchors with a symbol must hold it in the mapped window or gain SYMBOL_MISSING, and one capped git-grep caller list per symbol follows the windows within --max-lines. Specs without reads or symbols print what v1 did. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
0ac55b729f
commit
c29671c4ac
3 changed files with 224 additions and 33 deletions
|
|
@ -1,21 +1,26 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Carry a cut_spec's file_changes anchors from the spec's base to a worktree.
|
||||
|
||||
Usage: context-pack.py <cut_spec id> <worktree> [--since <sha>] [--only <k>[,<k>...]]
|
||||
Usage: context-pack.py <cut_spec id> <worktree> [--since <sha>] [--only <k>|r<k>[,...]]
|
||||
[--spec-json <file>] [--max-lines <n>]
|
||||
|
||||
Prints a header, a status table (one line per anchor) and bounded windows of the
|
||||
code each anchor names, numbered in the worktree's lines. Exit: 0 every anchor
|
||||
carried; 3 an anchor cannot be carried (OUT_OF_RANGE, UNRESOLVED, GONE outside
|
||||
Prints a header, a status table (one line per anchor: file_changes as <k>, reads
|
||||
as r<k>) and bounded windows of the code each anchor names, numbered in the
|
||||
worktree's lines: edit windows, then READ windows, then one caller list per
|
||||
distinct symbol. A symbol an anchor names must be in its mapped window or the
|
||||
status gains SYMBOL_MISSING. Exit: 0 every anchor carried; 3 an anchor cannot be
|
||||
carried (OUT_OF_RANGE, UNRESOLVED, MISSING read, SYMBOL_MISSING, GONE outside
|
||||
the spec's deletes); 2 usage; 4 spec unreadable. Standard library plus git.
|
||||
Errors name a field and a code, never an input value.
|
||||
--max-lines bounds the windows, not the table: the table always lists every
|
||||
anchor, so a budget smaller than the table prints the table and no window.
|
||||
--max-lines bounds the windows and caller lists, not the table: the table always
|
||||
lists every anchor, so a budget smaller than the table prints the table and no
|
||||
window. Precedence: table, edit windows, read windows, caller lists.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shlex
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
|
|
@ -26,6 +31,12 @@ WINDOW_CAP = 100
|
|||
CONTEXT = 3
|
||||
DEFAULT_MAX_LINES = 800
|
||||
HUNK = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@")
|
||||
MAX_CALLER_SYMBOLS = 8
|
||||
MAX_CALLER_HITS = 50
|
||||
MAX_CALLER_FILES = 20
|
||||
HIT_TEXT = 160
|
||||
ONLY = re.compile(r"^(r?)([0-9]+)$")
|
||||
IDENT = re.compile(r"^[A-Za-z0-9_]+$")
|
||||
HEX = re.compile(r"^[0-9a-fA-F]{7,40}$")
|
||||
|
||||
|
||||
|
|
@ -84,6 +95,17 @@ def check_spec_shape(spec):
|
|||
raise Fail(4, "spec: %s: InvalidInput" % field)
|
||||
if not isinstance(spec["base"], str):
|
||||
bad("base")
|
||||
def check_loc(at, loc):
|
||||
if not isinstance(loc, dict):
|
||||
bad(at)
|
||||
if not isinstance(loc.get("path"), str):
|
||||
bad(at + ".path")
|
||||
if not is_int(loc.get("line")):
|
||||
bad(at + ".line")
|
||||
if loc.get("end_line") is not None and not is_int(loc["end_line"]):
|
||||
bad(at + ".end_line")
|
||||
if loc.get("symbol") is not None and not isinstance(loc["symbol"], str):
|
||||
bad(at + ".symbol")
|
||||
fcs = spec["file_changes"]
|
||||
if not isinstance(fcs, list):
|
||||
bad("file_changes")
|
||||
|
|
@ -91,17 +113,21 @@ def check_spec_shape(spec):
|
|||
at = "file_changes[%d]" % k
|
||||
if not isinstance(fc, dict):
|
||||
bad(at)
|
||||
loc = fc.get("location")
|
||||
if not isinstance(loc, dict):
|
||||
bad(at + ".location")
|
||||
if not isinstance(loc.get("path"), str):
|
||||
bad(at + ".location.path")
|
||||
if not is_int(loc.get("line")):
|
||||
bad(at + ".location.line")
|
||||
if loc.get("end_line") is not None and not is_int(loc["end_line"]):
|
||||
bad(at + ".location.end_line")
|
||||
check_loc(at + ".location", fc.get("location"))
|
||||
if "change" in fc and not isinstance(fc["change"], str):
|
||||
bad(at + ".change")
|
||||
reads = spec.get("reads")
|
||||
if reads is None:
|
||||
reads = []
|
||||
if not isinstance(reads, list):
|
||||
bad("reads")
|
||||
for k, rd in enumerate(reads, 1):
|
||||
at = "reads[%d]" % k
|
||||
if not isinstance(rd, dict):
|
||||
bad(at)
|
||||
check_loc(at + ".location", rd.get("location"))
|
||||
if "why" in rd and not isinstance(rd["why"], str):
|
||||
bad(at + ".why")
|
||||
dels = spec.get("deletes", [])
|
||||
if not isinstance(dels, list):
|
||||
bad("deletes")
|
||||
|
|
@ -236,12 +262,34 @@ def safe_path(path):
|
|||
and ".." not in path.replace("\\", "/").split("/")
|
||||
|
||||
|
||||
def resolve(tree, k, fc, deleted_ok, base_ok, listed):
|
||||
def has_symbol(symbol, lines):
|
||||
text = "\n".join(lines)
|
||||
if IDENT.match(symbol):
|
||||
return re.search(r"(?<![A-Za-z0-9_])" + re.escape(symbol) + r"(?![A-Za-z0-9_])", text) is not None
|
||||
return symbol in text
|
||||
|
||||
|
||||
def resolve(tree, label, fc, deleted_ok, base_ok, listed, read=False):
|
||||
"""One anchor: carried to the worktree, then its symbol (if any) looked up in
|
||||
the mapped window (the AT BASE window for GONE)."""
|
||||
a = carry_anchor(tree, label, fc, deleted_ok, base_ok, listed, read)
|
||||
sym = fc["location"].get("symbol")
|
||||
a["symbol"] = sym or None
|
||||
if sym and a["window"]:
|
||||
kind, path, s, e = a["window"]
|
||||
lines = tree.base_lines(path) if kind == "base" else tree.wt_lines(path)
|
||||
if lines is not None and not has_symbol(sym, lines[s - 1:e]):
|
||||
a["status"] += " SYMBOL_MISSING " + sym
|
||||
a["exit"] = 3
|
||||
return a
|
||||
|
||||
|
||||
def carry_anchor(tree, label, fc, deleted_ok, base_ok, listed, read):
|
||||
loc = fc["location"]
|
||||
path, s = loc["path"], int(loc["line"])
|
||||
e = int(loc.get("end_line") or s)
|
||||
a = {"k": k, "path": path, "s": s, "e": e, "change": str(fc.get("change", "")),
|
||||
"rank": 1, "exit": 0, "status": "", "now": None, "window": None}
|
||||
a = {"k": label, "path": path, "s": s, "e": e, "change": str(fc.get("change", "")),
|
||||
"rank": 1, "exit": 0, "status": "", "now": None, "window": None, "read": read}
|
||||
if not base_ok:
|
||||
a.update(rank=0, exit=3, status="UNRESOLVED base not a commit here: git fetch origin " + tree.base)
|
||||
return a
|
||||
|
|
@ -249,6 +297,9 @@ def resolve(tree, k, fc, deleted_ok, base_ok, listed):
|
|||
a.update(rank=0, exit=3, status="UNRESOLVED path or git diff unusable")
|
||||
return a
|
||||
base = tree.base_lines(path)
|
||||
if base is None and read:
|
||||
a.update(rank=0, exit=3, status="MISSING (read path absent at base)")
|
||||
return a
|
||||
if base is None:
|
||||
sib = [p for p in tree.siblings() if p.rsplit("/", 1)[-1] == path.rsplit("/", 1)[-1]][:3]
|
||||
a.update(rank=0, status="NEW" + (" (at base: " + ", ".join(sib) + ")" if sib else ""))
|
||||
|
|
@ -285,7 +336,7 @@ def resolve(tree, k, fc, deleted_ok, base_ok, listed):
|
|||
|
||||
|
||||
def table_line(a):
|
||||
line = "[%d] %s:%d-%d %s" % (a["k"], a["path"], a["s"], a["e"], a["status"])
|
||||
line = "[%s] %s:%d-%d %s" % (a["k"], a["path"], a["s"], a["e"], a["status"])
|
||||
if a["now"]:
|
||||
line += " -> %s:%d-%d" % a["now"]
|
||||
return line + " # " + " ".join(a["change"].split())[:70]
|
||||
|
|
@ -294,7 +345,8 @@ def table_line(a):
|
|||
def window_body(tree, a):
|
||||
kind, path, s, e = a["window"]
|
||||
lines = tree.base_lines(path) if kind == "base" else tree.wt_lines(path)
|
||||
cap = "== [%d] %s:%d-%d%s %s" % (a["k"], path, s, e, " AT BASE" if kind == "base" else "", a["status"])
|
||||
where = "%s:%d-%d%s %s" % (path, s, e, " AT BASE" if kind == "base" else "", a["status"])
|
||||
cap = ("== READ %s: %s (%s)" % (a["k"], a["change"][:200], where)) if a["read"] else "== [%s] %s" % (a["k"], where)
|
||||
if lines is None:
|
||||
return cap, ["(file not readable in the worktree)"]
|
||||
lo, hi = max(1, s - CONTEXT), min(len(lines), e + CONTEXT)
|
||||
|
|
@ -318,6 +370,46 @@ def overlaps_since(tree, since, a):
|
|||
return False
|
||||
|
||||
|
||||
def caller_list(wt, symbol, windows):
|
||||
"""The lines of one CALLERS list: hits of the symbol in the worktree outside
|
||||
every mapped window of the spec."""
|
||||
args = ["grep", "-n", "-I", "--no-color", "-z", "-F"] + (["-w"] if IDENT.match(symbol) else []) + ["-e", symbol]
|
||||
raw = git(wt, *args) or b""
|
||||
hits = []
|
||||
for rec in raw.decode("utf-8", "replace").split("\n"):
|
||||
parts = rec.split("\0", 2)
|
||||
if len(parts) < 3 or not parts[1].isdigit():
|
||||
continue
|
||||
path, n = parts[0], int(parts[1])
|
||||
if any(path == wp and ws <= n <= we for wp, ws, we in windows):
|
||||
continue
|
||||
hits.append((path, n, parts[2].rstrip("\r")))
|
||||
counts = {}
|
||||
for path, _, _ in hits:
|
||||
counts[path] = counts.get(path, 0) + 1
|
||||
out = ["CALLERS %s: %d hits in %d files" % (symbol, len(hits), len(counts))]
|
||||
if len(hits) <= MAX_CALLER_HITS:
|
||||
out += ["%s:%d: %s" % (path, n, text[:HIT_TEXT]) for path, n, text in hits]
|
||||
else:
|
||||
ranked = sorted(counts.items(), key=lambda kv: (-kv[1], kv[0]))
|
||||
out += ["%6d %s" % (c, path) for path, c in ranked[:MAX_CALLER_FILES]]
|
||||
if len(ranked) > MAX_CALLER_FILES:
|
||||
out.append("(%d more files)" % (len(ranked) - MAX_CALLER_FILES))
|
||||
out.append("narrow: git grep -n -I %s-F -e %s -- <path>" % ("-w " if IDENT.match(symbol) else "", shlex.quote(symbol)))
|
||||
return out
|
||||
|
||||
|
||||
def parse_only(text, p):
|
||||
"""Labels: <k> for file_changes, r<k> for reads."""
|
||||
labels = set()
|
||||
for x in text.split(","):
|
||||
m = ONLY.match(x)
|
||||
if not m:
|
||||
p.error("")
|
||||
labels.add(m.group(1) + str(int(m.group(2))))
|
||||
return labels
|
||||
|
||||
|
||||
def main(argv):
|
||||
p = Parser(prog="context-pack.py")
|
||||
p.add_argument("spec_id")
|
||||
|
|
@ -329,19 +421,18 @@ def main(argv):
|
|||
ns = p.parse_args(argv)
|
||||
if ns.max_lines < 1:
|
||||
p.error("")
|
||||
only = None
|
||||
if ns.only is not None:
|
||||
try:
|
||||
only = {int(x) for x in ns.only.split(",")}
|
||||
except ValueError:
|
||||
p.error("")
|
||||
only = parse_only(ns.only, p) if ns.only is not None else None
|
||||
wt = ns.worktree
|
||||
if git(wt, "rev-parse", "--git-dir") is None:
|
||||
raise Fail(2, "worktree: not a git worktree")
|
||||
spec = load_spec(ns.spec_id, ns.spec_json)
|
||||
fcs = spec["file_changes"]
|
||||
if only is not None and not only <= set(range(1, len(fcs) + 1)):
|
||||
raise Fail(2, "--only: index outside file_changes")
|
||||
reads = spec.get("reads") or []
|
||||
if only is not None:
|
||||
if not {x for x in only if x[0] != "r"} <= {str(i) for i in range(1, len(fcs) + 1)}:
|
||||
raise Fail(2, "--only: index outside file_changes")
|
||||
if not {x for x in only if x[0] == "r"} <= {"r%d" % i for i in range(1, len(reads) + 1)}:
|
||||
raise Fail(2, "--only: index outside reads")
|
||||
base = str(spec["base"])
|
||||
resolved = HEX.match(base) and git(wt, "rev-parse", "--verify", "--quiet", base + "^{commit}")
|
||||
tree = Tree(wt, base)
|
||||
|
|
@ -352,7 +443,9 @@ def main(argv):
|
|||
git(wt, "rev-parse", "--verify", "--quiet", ns.since + "^{commit}") is None):
|
||||
raise Fail(2, "--since: not a commit in this worktree")
|
||||
deleted_ok = {d["path"] for d in spec.get("deletes", [])}
|
||||
anchors = [resolve(tree, i + 1, fc, deleted_ok, bool(resolved), listed) for i, fc in enumerate(fcs)]
|
||||
anchors = [resolve(tree, str(i + 1), fc, deleted_ok, bool(resolved), listed) for i, fc in enumerate(fcs)]
|
||||
anchors += [resolve(tree, "r%d" % (i + 1), {"location": rd["location"], "change": rd.get("why", "")},
|
||||
deleted_ok, bool(resolved), listed, read=True) for i, rd in enumerate(reads)]
|
||||
|
||||
head = (git(wt, "rev-parse", "--short", "HEAD") or b"none").decode().strip()
|
||||
out = ["context-pack %s base %s HEAD %s modified %d" % (
|
||||
|
|
@ -361,8 +454,8 @@ def main(argv):
|
|||
out.append("")
|
||||
want = [a for a in anchors if a["window"] and (only is None or a["k"] in only)
|
||||
and (ns.since is None or overlaps_since(tree, ns.since, a))]
|
||||
table_len = len(fcs)
|
||||
skipped = []
|
||||
table_len = len(anchors)
|
||||
skipped, skipped_need = [], 0
|
||||
left = ns.max_lines - len(out)
|
||||
for idx, a in enumerate(want):
|
||||
cap, body = window_body(tree, a)
|
||||
|
|
@ -376,14 +469,36 @@ def main(argv):
|
|||
need = 1 + len(body) + 1
|
||||
if need > left - reserve:
|
||||
skipped.append(a["k"])
|
||||
skipped_need += need
|
||||
continue
|
||||
out.append(cap)
|
||||
out += body
|
||||
if len(body) < full:
|
||||
out.append("%d more lines: --only %d --max-lines %d" % (full - len(body), a["k"], table_len + full + 3))
|
||||
out.append("%d more lines: --only %s --max-lines %d" % (full - len(body), a["k"], table_len + full + 3))
|
||||
left -= need
|
||||
if skipped:
|
||||
out.append("not expanded: --only " + ",".join(map(str, skipped)))
|
||||
out.append("not expanded: --only " + ",".join(skipped))
|
||||
left -= 1
|
||||
windows = [(a["window"][1], a["window"][2], a["window"][3]) for a in anchors
|
||||
if a["window"] and a["window"][0] == "wt"]
|
||||
symbols = list(dict.fromkeys(a["symbol"] for a in want if a["symbol"]))
|
||||
lists = [(sym, caller_list(wt, sym, windows)) for sym in symbols[:MAX_CALLER_SYMBOLS]]
|
||||
unlisted = symbols[MAX_CALLER_SYMBOLS:]
|
||||
cut = []
|
||||
fits_all = sum(len(ls) for _, ls in lists) + (1 if unlisted else 0) <= left
|
||||
for idx, (sym, ls) in enumerate(lists):
|
||||
reserve = 0 if fits_all else 1
|
||||
if len(ls) > left - reserve:
|
||||
cut.append((sym, len(ls)))
|
||||
continue
|
||||
out += ls
|
||||
left -= len(ls)
|
||||
if cut:
|
||||
out.append("callers not printed: %s: --max-lines %d" % (
|
||||
",".join(c[0] for c in cut),
|
||||
len(out) - (1 if skipped else 0) + skipped_need + sum(c[1] for c in cut) + (1 if unlisted else 0)))
|
||||
if unlisted:
|
||||
out.append("callers not listed: " + ",".join(unlisted))
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace", newline="\n")
|
||||
sys.stdout.write("\n".join(out) + "\n")
|
||||
return max([a["exit"] for a in anchors] or [0])
|
||||
|
|
|
|||
Loading…
Reference in a new issue