featmap 0.1.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- featmap-0.1.1.dist-info/METADATA +95 -0
- featmap-0.1.1.dist-info/RECORD +130 -0
- featmap-0.1.1.dist-info/WHEEL +5 -0
- featmap-0.1.1.dist-info/entry_points.txt +2 -0
- featmap-0.1.1.dist-info/licenses/LICENSE +24 -0
- featmap-0.1.1.dist-info/licenses/fmap/vendor/typescript/LICENSE.txt +55 -0
- featmap-0.1.1.dist-info/licenses/fmap/vendor/typescript/ThirdPartyNoticeText.txt +193 -0
- featmap-0.1.1.dist-info/top_level.txt +1 -0
- fmap/__init__.py +1 -0
- fmap/__main__.py +3 -0
- fmap/axum.py +485 -0
- fmap/cache.py +25 -0
- fmap/cli.py +907 -0
- fmap/goext/go.mod +3 -0
- fmap/goext/main.go +547 -0
- fmap/goext.py +43 -0
- fmap/graph.py +920 -0
- fmap/impact.py +171 -0
- fmap/index.py +66 -0
- fmap/pyx.py +1133 -0
- fmap/routes.py +163 -0
- fmap/rsx.py +381 -0
- fmap/scip.py +80 -0
- fmap/trace_site.py +63 -0
- fmap/tsx.cjs +1258 -0
- fmap/tsx.py +98 -0
- fmap/vendor/typescript/LICENSE.txt +55 -0
- fmap/vendor/typescript/ThirdPartyNoticeText.txt +193 -0
- fmap/vendor/typescript/lib/lib.d.ts +22 -0
- fmap/vendor/typescript/lib/lib.decorators.d.ts +384 -0
- fmap/vendor/typescript/lib/lib.decorators.legacy.d.ts +22 -0
- fmap/vendor/typescript/lib/lib.dom.asynciterable.d.ts +41 -0
- fmap/vendor/typescript/lib/lib.dom.d.ts +39429 -0
- fmap/vendor/typescript/lib/lib.dom.iterable.d.ts +571 -0
- fmap/vendor/typescript/lib/lib.es2015.collection.d.ts +147 -0
- fmap/vendor/typescript/lib/lib.es2015.core.d.ts +597 -0
- fmap/vendor/typescript/lib/lib.es2015.d.ts +28 -0
- fmap/vendor/typescript/lib/lib.es2015.generator.d.ts +77 -0
- fmap/vendor/typescript/lib/lib.es2015.iterable.d.ts +605 -0
- fmap/vendor/typescript/lib/lib.es2015.promise.d.ts +81 -0
- fmap/vendor/typescript/lib/lib.es2015.proxy.d.ts +128 -0
- fmap/vendor/typescript/lib/lib.es2015.reflect.d.ts +144 -0
- fmap/vendor/typescript/lib/lib.es2015.symbol.d.ts +46 -0
- fmap/vendor/typescript/lib/lib.es2015.symbol.wellknown.d.ts +326 -0
- fmap/vendor/typescript/lib/lib.es2016.array.include.d.ts +116 -0
- fmap/vendor/typescript/lib/lib.es2016.d.ts +21 -0
- fmap/vendor/typescript/lib/lib.es2016.full.d.ts +23 -0
- fmap/vendor/typescript/lib/lib.es2016.intl.d.ts +31 -0
- fmap/vendor/typescript/lib/lib.es2017.arraybuffer.d.ts +21 -0
- fmap/vendor/typescript/lib/lib.es2017.d.ts +26 -0
- fmap/vendor/typescript/lib/lib.es2017.date.d.ts +31 -0
- fmap/vendor/typescript/lib/lib.es2017.full.d.ts +23 -0
- fmap/vendor/typescript/lib/lib.es2017.intl.d.ts +44 -0
- fmap/vendor/typescript/lib/lib.es2017.object.d.ts +49 -0
- fmap/vendor/typescript/lib/lib.es2017.sharedmemory.d.ts +135 -0
- fmap/vendor/typescript/lib/lib.es2017.string.d.ts +45 -0
- fmap/vendor/typescript/lib/lib.es2017.typedarrays.d.ts +53 -0
- fmap/vendor/typescript/lib/lib.es2018.asyncgenerator.d.ts +77 -0
- fmap/vendor/typescript/lib/lib.es2018.asynciterable.d.ts +53 -0
- fmap/vendor/typescript/lib/lib.es2018.d.ts +24 -0
- fmap/vendor/typescript/lib/lib.es2018.full.d.ts +24 -0
- fmap/vendor/typescript/lib/lib.es2018.intl.d.ts +83 -0
- fmap/vendor/typescript/lib/lib.es2018.promise.d.ts +30 -0
- fmap/vendor/typescript/lib/lib.es2018.regexp.d.ts +37 -0
- fmap/vendor/typescript/lib/lib.es2019.array.d.ts +79 -0
- fmap/vendor/typescript/lib/lib.es2019.d.ts +24 -0
- fmap/vendor/typescript/lib/lib.es2019.full.d.ts +24 -0
- fmap/vendor/typescript/lib/lib.es2019.intl.d.ts +23 -0
- fmap/vendor/typescript/lib/lib.es2019.object.d.ts +33 -0
- fmap/vendor/typescript/lib/lib.es2019.string.d.ts +37 -0
- fmap/vendor/typescript/lib/lib.es2019.symbol.d.ts +24 -0
- fmap/vendor/typescript/lib/lib.es2020.bigint.d.ts +765 -0
- fmap/vendor/typescript/lib/lib.es2020.d.ts +27 -0
- fmap/vendor/typescript/lib/lib.es2020.date.d.ts +42 -0
- fmap/vendor/typescript/lib/lib.es2020.full.d.ts +24 -0
- fmap/vendor/typescript/lib/lib.es2020.intl.d.ts +474 -0
- fmap/vendor/typescript/lib/lib.es2020.number.d.ts +28 -0
- fmap/vendor/typescript/lib/lib.es2020.promise.d.ts +47 -0
- fmap/vendor/typescript/lib/lib.es2020.sharedmemory.d.ts +99 -0
- fmap/vendor/typescript/lib/lib.es2020.string.d.ts +44 -0
- fmap/vendor/typescript/lib/lib.es2020.symbol.wellknown.d.ts +41 -0
- fmap/vendor/typescript/lib/lib.es2021.d.ts +23 -0
- fmap/vendor/typescript/lib/lib.es2021.full.d.ts +24 -0
- fmap/vendor/typescript/lib/lib.es2021.intl.d.ts +166 -0
- fmap/vendor/typescript/lib/lib.es2021.promise.d.ts +48 -0
- fmap/vendor/typescript/lib/lib.es2021.string.d.ts +33 -0
- fmap/vendor/typescript/lib/lib.es2021.weakref.d.ts +78 -0
- fmap/vendor/typescript/lib/lib.es2022.array.d.ts +121 -0
- fmap/vendor/typescript/lib/lib.es2022.d.ts +25 -0
- fmap/vendor/typescript/lib/lib.es2022.error.d.ts +75 -0
- fmap/vendor/typescript/lib/lib.es2022.full.d.ts +24 -0
- fmap/vendor/typescript/lib/lib.es2022.intl.d.ts +145 -0
- fmap/vendor/typescript/lib/lib.es2022.object.d.ts +26 -0
- fmap/vendor/typescript/lib/lib.es2022.regexp.d.ts +39 -0
- fmap/vendor/typescript/lib/lib.es2022.string.d.ts +25 -0
- fmap/vendor/typescript/lib/lib.es2023.array.d.ts +924 -0
- fmap/vendor/typescript/lib/lib.es2023.collection.d.ts +21 -0
- fmap/vendor/typescript/lib/lib.es2023.d.ts +22 -0
- fmap/vendor/typescript/lib/lib.es2023.full.d.ts +24 -0
- fmap/vendor/typescript/lib/lib.es2023.intl.d.ts +56 -0
- fmap/vendor/typescript/lib/lib.es2024.arraybuffer.d.ts +65 -0
- fmap/vendor/typescript/lib/lib.es2024.collection.d.ts +29 -0
- fmap/vendor/typescript/lib/lib.es2024.d.ts +26 -0
- fmap/vendor/typescript/lib/lib.es2024.full.d.ts +24 -0
- fmap/vendor/typescript/lib/lib.es2024.object.d.ts +29 -0
- fmap/vendor/typescript/lib/lib.es2024.promise.d.ts +35 -0
- fmap/vendor/typescript/lib/lib.es2024.regexp.d.ts +25 -0
- fmap/vendor/typescript/lib/lib.es2024.sharedmemory.d.ts +68 -0
- fmap/vendor/typescript/lib/lib.es2024.string.d.ts +29 -0
- fmap/vendor/typescript/lib/lib.es5.d.ts +4601 -0
- fmap/vendor/typescript/lib/lib.es6.d.ts +23 -0
- fmap/vendor/typescript/lib/lib.esnext.array.d.ts +35 -0
- fmap/vendor/typescript/lib/lib.esnext.collection.d.ts +96 -0
- fmap/vendor/typescript/lib/lib.esnext.d.ts +29 -0
- fmap/vendor/typescript/lib/lib.esnext.decorators.d.ts +28 -0
- fmap/vendor/typescript/lib/lib.esnext.disposable.d.ts +193 -0
- fmap/vendor/typescript/lib/lib.esnext.error.d.ts +24 -0
- fmap/vendor/typescript/lib/lib.esnext.float16.d.ts +445 -0
- fmap/vendor/typescript/lib/lib.esnext.full.d.ts +24 -0
- fmap/vendor/typescript/lib/lib.esnext.intl.d.ts +21 -0
- fmap/vendor/typescript/lib/lib.esnext.iterator.d.ts +148 -0
- fmap/vendor/typescript/lib/lib.esnext.promise.d.ts +34 -0
- fmap/vendor/typescript/lib/lib.esnext.sharedmemory.d.ts +25 -0
- fmap/vendor/typescript/lib/lib.scripthost.d.ts +322 -0
- fmap/vendor/typescript/lib/lib.webworker.asynciterable.d.ts +41 -0
- fmap/vendor/typescript/lib/lib.webworker.d.ts +13150 -0
- fmap/vendor/typescript/lib/lib.webworker.importscripts.d.ts +23 -0
- fmap/vendor/typescript/lib/lib.webworker.iterable.d.ts +340 -0
- fmap/vendor/typescript/lib/typescript.js +200276 -0
- fmap/vendor/typescript/package.json +120 -0
fmap/cli.py
ADDED
|
@@ -0,0 +1,907 @@
|
|
|
1
|
+
"""fmap CLI (spec §7, §8, §9)."""
|
|
2
|
+
import argparse
|
|
3
|
+
import itertools
|
|
4
|
+
import json
|
|
5
|
+
import math
|
|
6
|
+
import os
|
|
7
|
+
import re
|
|
8
|
+
import stat
|
|
9
|
+
import shutil
|
|
10
|
+
import subprocess
|
|
11
|
+
import sys
|
|
12
|
+
import tomllib
|
|
13
|
+
import unicodedata
|
|
14
|
+
from collections import deque
|
|
15
|
+
|
|
16
|
+
from . import graph as G
|
|
17
|
+
from . import index as I
|
|
18
|
+
from . import impact
|
|
19
|
+
|
|
20
|
+
TRAVERSE = set(G.RESOLVED)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
# ---------- output ----------
|
|
24
|
+
class Out:
|
|
25
|
+
"""Lines tagged with a cut rank: 0 never cut, higher ranks are cut first (spec §7.3)."""
|
|
26
|
+
|
|
27
|
+
def __init__(self):
|
|
28
|
+
self.lines = []
|
|
29
|
+
self.short = {} # line index -> compact form used when uncut lines alone exceed the budget
|
|
30
|
+
self.data = {}
|
|
31
|
+
|
|
32
|
+
def add(self, line, rank=0, what="detail", short=None):
|
|
33
|
+
if short is not None and len(short.encode()) < len(line.encode()):
|
|
34
|
+
self.short[len(self.lines)] = (short, what)
|
|
35
|
+
self.lines.append((line, rank, what))
|
|
36
|
+
|
|
37
|
+
def render(self, budget=None):
|
|
38
|
+
lines = list(self.lines)
|
|
39
|
+
cut = {}
|
|
40
|
+
if budget:
|
|
41
|
+
limit = budget * 3
|
|
42
|
+
sizes = [len(line.encode()) for line, _, _ in lines]
|
|
43
|
+
byte_count = sum(sizes) + max(0, len(lines) - 1)
|
|
44
|
+
# the printed text also carries the `truncated:` line, so every decision counts it
|
|
45
|
+
total = lambda: byte_count + (len(truncated_line(cut).encode()) + 1 if cut else 0)
|
|
46
|
+
by_rank = {}
|
|
47
|
+
for index, (_, rank, _) in enumerate(lines):
|
|
48
|
+
if rank > 0:
|
|
49
|
+
by_rank.setdefault(rank, []).append(index)
|
|
50
|
+
removed = set()
|
|
51
|
+
for rank in sorted(by_rank, reverse=True):
|
|
52
|
+
for index in reversed(by_rank[rank]):
|
|
53
|
+
if total() <= limit:
|
|
54
|
+
break
|
|
55
|
+
what = lines[index][2]
|
|
56
|
+
cut[what] = cut.get(what, 0) + 1
|
|
57
|
+
removed.add(index)
|
|
58
|
+
byte_count -= sizes[index] + (len(lines) - len(removed) > 0)
|
|
59
|
+
if total() <= limit:
|
|
60
|
+
break
|
|
61
|
+
# then compact what may not be cut: fewest compactions that fit, else the shortest output
|
|
62
|
+
cands = [i for i in self.short if i not in removed]
|
|
63
|
+
if total() > limit and cands:
|
|
64
|
+
def size(chosen):
|
|
65
|
+
c = dict(cut)
|
|
66
|
+
for i in chosen:
|
|
67
|
+
c[f"{self.short[i][1]} kısaltıldı"] = c.get(f"{self.short[i][1]} kısaltıldı", 0) + 1
|
|
68
|
+
saved = sum(sizes[i] - len(self.short[i][0].encode()) for i in chosen)
|
|
69
|
+
return byte_count - saved + (len(truncated_line(c).encode()) + 1 if c else 0)
|
|
70
|
+
# shortcut: subsets only for the few short forms commands emit (files, reach); many -> prefixes
|
|
71
|
+
options = ([c for k in range(len(cands) + 1) for c in itertools.combinations(cands, k)]
|
|
72
|
+
if len(cands) <= 6 else [tuple(cands[:k]) for k in range(len(cands) + 1)])
|
|
73
|
+
best = min(options, key=lambda c: (size(c) > limit, len(c) if size(c) <= limit else size(c)))
|
|
74
|
+
for i in best:
|
|
75
|
+
cut[f"{self.short[i][1]} kısaltıldı"] = cut.get(f"{self.short[i][1]} kısaltıldı", 0) + 1
|
|
76
|
+
byte_count -= sizes[i] - len(self.short[i][0].encode())
|
|
77
|
+
lines[i] = (self.short[i][0], *lines[i][1:])
|
|
78
|
+
lines = [line for index, line in enumerate(lines) if index not in removed]
|
|
79
|
+
text = [l for l, _, _ in lines]
|
|
80
|
+
if cut:
|
|
81
|
+
text.append(truncated_line(cut))
|
|
82
|
+
if budget and len("\n".join(text).encode()) > budget * 3:
|
|
83
|
+
text.append(f"bütçe aşıldı: kesilemeyen satırlar {budget} token'dan uzun (tam liste --json)")
|
|
84
|
+
if budget:
|
|
85
|
+
text.append(f"~{tokens(chr(10).join(text))} token (tahmin: bayt/3)")
|
|
86
|
+
return "\n".join(text)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def truncated_line(cut):
|
|
90
|
+
return "truncated: " + ", ".join(f"{w} ({n} satır)" for w, n in sorted(cut.items()))
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def tokens(s):
|
|
94
|
+
return math.ceil(len(s.encode()) / 3)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def emit(args, out):
|
|
98
|
+
if args.json:
|
|
99
|
+
print(json.dumps(out.data, ensure_ascii=False, indent=1, sort_keys=True))
|
|
100
|
+
else:
|
|
101
|
+
print(out.render(args.budget))
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def norm(s):
|
|
105
|
+
s = unicodedata.normalize("NFC", s).casefold().replace("̇", "").replace("ı", "i")
|
|
106
|
+
return " ".join(s.split())
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def word_hit(query, value):
|
|
110
|
+
return f" {query} " in f" {re.sub(r'[-_]+', ' ', norm(value)).strip()} "
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
# ---------- graph helpers ----------
|
|
114
|
+
def add_files(out, locs):
|
|
115
|
+
"""Every file stays listed under a budget; only the line numbers are dropped (spec §7.3)."""
|
|
116
|
+
full = files_line(locs)
|
|
117
|
+
by = {}
|
|
118
|
+
for loc in set(locs):
|
|
119
|
+
by[loc.rpartition(":")[0]] = by.get(loc.rpartition(":")[0], 0) + 1
|
|
120
|
+
short = "files: " + (", ".join(f"{f} ({n})" for f, n in sorted(by.items())) if by else "(yok)")
|
|
121
|
+
out.add(full, what="files", short=short)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
REACH_SHORT = 8
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def files_line(locs):
|
|
128
|
+
"""Full file:line list, grouped per file: `a.py:3,40, b.py:7` (never truncated)."""
|
|
129
|
+
by = {}
|
|
130
|
+
for loc in set(locs):
|
|
131
|
+
f, _, line = loc.rpartition(":")
|
|
132
|
+
by.setdefault(f, set()).add(int(line) if line.isdigit() else 0)
|
|
133
|
+
parts = [f"{f}:{','.join(map(str, sorted(ls)))}" for f, ls in sorted(by.items())]
|
|
134
|
+
return "files: " + (", ".join(parts) if parts else "(yok)")
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def load(args, untracked=None):
|
|
138
|
+
root = G.repo_root(args.root)
|
|
139
|
+
g, errors, files = G.cached_build(root, untracked=args.untracked if untracked is None else untracked)
|
|
140
|
+
warn_incomplete(g)
|
|
141
|
+
return root, g, errors, files
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def warn_incomplete(g):
|
|
145
|
+
for warning in g["meta"].get("missing_tools", {}).values():
|
|
146
|
+
print(warning, file=sys.stderr)
|
|
147
|
+
for program in g["meta"]["programs"]:
|
|
148
|
+
if program.get("failed"):
|
|
149
|
+
print(program["failed"], file=sys.stderr)
|
|
150
|
+
elif program["deps"] != "ok":
|
|
151
|
+
print(f"deps missing in {program['name']}: {program.get('missing', 0)} imports", file=sys.stderr)
|
|
152
|
+
if g["meta"].get("entry_points_not_extracted"):
|
|
153
|
+
print("entry points not extracted: " + ", ".join(g["meta"]["entry_points_not_extracted"]), file=sys.stderr)
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def pick(ix, q, out):
|
|
157
|
+
found = ix.find_symbol(q)
|
|
158
|
+
if len(found) == 1:
|
|
159
|
+
return found[0]
|
|
160
|
+
if not found:
|
|
161
|
+
out.add(f"sembol yok: {q}")
|
|
162
|
+
for n in closest(q, list(ix.nodes)):
|
|
163
|
+
out.add(f" yakın: {n}")
|
|
164
|
+
else:
|
|
165
|
+
out.add(f"birden fazla eşleşme: {q}")
|
|
166
|
+
for n in found:
|
|
167
|
+
out.add(f" {n} ({ix.loc(n)})")
|
|
168
|
+
out.data = {"query": q, "candidates": found}
|
|
169
|
+
return None
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def closest(q, names, limit=10):
|
|
173
|
+
nq = norm(q)
|
|
174
|
+
|
|
175
|
+
def lcp(a):
|
|
176
|
+
a = norm(a.rsplit(":", 1)[-1])
|
|
177
|
+
n = 0
|
|
178
|
+
while n < min(len(a), len(nq)) and a[n] == nq[n]:
|
|
179
|
+
n += 1
|
|
180
|
+
return n
|
|
181
|
+
|
|
182
|
+
scored = [(lcp(n), n) for n in names]
|
|
183
|
+
best = max((s for s, _ in scored), default=0)
|
|
184
|
+
return sorted(n for s, n in scored if s == best and s > 0)[:limit]
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
# ---------- commands ----------
|
|
188
|
+
def cmd_build(args):
|
|
189
|
+
root = G.repo_root(args.root)
|
|
190
|
+
config = G.load_config(root)
|
|
191
|
+
g, errors, files = G.build(root, config=config)
|
|
192
|
+
path = os.path.join(root, "featmap.json")
|
|
193
|
+
text = G.dumps(g)
|
|
194
|
+
old = G.read(root, "featmap.json") if os.path.exists(path) else None
|
|
195
|
+
# the same rule/config errors `check` reports: an invalid rule must not shape a written map;
|
|
196
|
+
# a partial graph (missing tool/deps) fails anyway: only its reference checks would be false errors
|
|
197
|
+
partial = incomplete(g)
|
|
198
|
+
config_errors = list(dict.fromkeys(errors + G.validate(g, config, files, references=not partial)))
|
|
199
|
+
for e in config_errors:
|
|
200
|
+
print(f"error: {e}", file=sys.stderr)
|
|
201
|
+
if config_errors or partial:
|
|
202
|
+
return 1
|
|
203
|
+
if old == text:
|
|
204
|
+
print("featmap.json: değişiklik yok")
|
|
205
|
+
else:
|
|
206
|
+
with open(path, "w", encoding="utf-8") as fh:
|
|
207
|
+
fh.write(text)
|
|
208
|
+
print(f"featmap.json: yazıldı ({len(g['nodes'])} düğüm, {len(g['edges'])} kenar)")
|
|
209
|
+
unsup = g["meta"]["unsupported"]
|
|
210
|
+
if unsup:
|
|
211
|
+
print("unsupported: " + ", ".join(f"{n} {ext} files" for ext, n in sorted(unsup.items())))
|
|
212
|
+
if g["meta"].get("entry_points_not_extracted"):
|
|
213
|
+
print("entry points not extracted: " + ", ".join(g["meta"]["entry_points_not_extracted"]))
|
|
214
|
+
return 0
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def incomplete(g):
|
|
218
|
+
return bool(g["meta"].get("missing_tools")) or any(p["deps"] != "ok" for p in g["meta"]["programs"])
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def check_errors(root, g, errors, files, config):
|
|
222
|
+
errs = list(errors)
|
|
223
|
+
path = os.path.join(root, "featmap.json")
|
|
224
|
+
current = G.read(root, "featmap.json") if os.path.exists(path) else None
|
|
225
|
+
if impact.fmap_json_ignored(root):
|
|
226
|
+
pass # the map is not committed (gitignored): queries rebuild it, so there is nothing to keep fresh
|
|
227
|
+
elif current != G.dumps(g):
|
|
228
|
+
errs.append("featmap.json bayat ya da yok: `featmap build` çalıştır")
|
|
229
|
+
for e in g["edges"]:
|
|
230
|
+
if e["kind"] == "unresolved":
|
|
231
|
+
errs.append(f"unresolved {', '.join(e['at'])}: `{e.get('expr', '')}` (kural ya da [[ignore]] ekle)")
|
|
232
|
+
partial = incomplete(g)
|
|
233
|
+
errs += G.validate(g, config, files, references=not partial)
|
|
234
|
+
errs += [f"onay bekliyor: {kind} {key} (`fmap approve {key}`)" for kind, key in G.proposed(config)]
|
|
235
|
+
un = G.unassigned(g, config)
|
|
236
|
+
notes = list(g.get("_notes", []))
|
|
237
|
+
if partial:
|
|
238
|
+
notes.append("not: featmap.toml başvuru denetimi atlandı (sembol/giriş varlığı; kural biçimi denetlendi) — grafik eksik (araç ya da bağımlılık eksik)")
|
|
239
|
+
if config.get("feature") and len(un) > UNASSIGNED_LIST:
|
|
240
|
+
# one error, not one per entry: a repo mapping its first feature must not drown in old entries
|
|
241
|
+
errs.append(f"{len(un)} atanmamış giriş noktası: "
|
|
242
|
+
+ ", ".join(f"{e['kind']}:{e['value']} ({e['at'][0]})" for e in un[:UNASSIGNED_LIST]) + ", …")
|
|
243
|
+
groups = {}
|
|
244
|
+
for e in un:
|
|
245
|
+
groups.setdefault(unassigned_group(e), []).append(e)
|
|
246
|
+
notes.append("ipucu: gruplar — her birini bir özelliğin reach listesine dağıt ya da bilerek sahipsizse "
|
|
247
|
+
+ "; ".join(f"`[[unassigned]] entry = {json.dumps(g, ensure_ascii=False)} reason = \"...\"` ({len(v)})"
|
|
248
|
+
for g, v in sorted(groups.items(), key=lambda kv: (-len(kv[1]), kv[0]))[:UNASSIGNED_LIST * 2]))
|
|
249
|
+
elif config.get("feature"):
|
|
250
|
+
errs += [f"atanmamış giriş noktası {e['kind']}:{e['value']} ({e['at'][0]})" for e in un]
|
|
251
|
+
if un:
|
|
252
|
+
keys = [f"{e['kind']}:{e['value']}" for e in un]
|
|
253
|
+
notes.append(f"ipucu: {len(un)} atanmamış giriş noktası — bir özelliğin reach listesine ekle: "
|
|
254
|
+
f"reach = {json.dumps(keys, ensure_ascii=False)} ya da bilerek sahipsizse her biri için "
|
|
255
|
+
f"`[[unassigned]] entry = {json.dumps(keys[0], ensure_ascii=False)} reason = \"...\"`")
|
|
256
|
+
elif un:
|
|
257
|
+
notes.append(f"{len(un)} atanmamış giriş noktası (henüz özellik yok, bloklamıyor)")
|
|
258
|
+
return list(dict.fromkeys(errs)), notes
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
UNASSIGNED_LIST = 5
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def unassigned_group(e):
|
|
265
|
+
"""A glob `[[unassigned]] entry` covering this entry's neighbours: `route:/admin/*`, `flag:*`."""
|
|
266
|
+
if e["kind"] == "route":
|
|
267
|
+
method, _, path = e["value"].rpartition(" ")
|
|
268
|
+
parts = path.strip("/").split("/")
|
|
269
|
+
n = next((i for i, x in enumerate(parts) if not re.fullmatch(r"api|v\d+", x)), len(parts)) # /api/v1/<area>
|
|
270
|
+
head = "/".join(parts[:n + 1])
|
|
271
|
+
return f"route:{method + ' ' if method else ''}/{head}*" if head else f"route:{e['value']}"
|
|
272
|
+
return f"{e['kind']}:*"
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def cmd_check(args):
|
|
276
|
+
root = G.repo_root(args.root)
|
|
277
|
+
config = G.load_config(root)
|
|
278
|
+
g, errors, files = G.build(root, config=config)
|
|
279
|
+
errs, notes = check_errors(root, g, errors, files, config)
|
|
280
|
+
for e in errs:
|
|
281
|
+
print(f"error: {e}")
|
|
282
|
+
for n in notes:
|
|
283
|
+
print(n)
|
|
284
|
+
print("check: ok" if not errs else f"check: {len(errs)} hata")
|
|
285
|
+
return 1 if errs else 0
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
PROPOSED_LINE = re.compile(r"^\s*proposed\s*=\s*true\s*(#.*)?$")
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def cmd_approve(args):
|
|
292
|
+
"""Drops `proposed = true` from the named featmap.toml blocks; no names lists what is pending."""
|
|
293
|
+
root = G.repo_root(args.root)
|
|
294
|
+
config = G.load_config(root)
|
|
295
|
+
pending = {key for _, key in G.proposed(config)}
|
|
296
|
+
if not args.ids and not args.all:
|
|
297
|
+
for kind, key in G.proposed(config):
|
|
298
|
+
print(f"{kind} {key}")
|
|
299
|
+
print(f"{len(pending)} öneri onay bekliyor" if pending else "onay bekleyen öneri yok")
|
|
300
|
+
return 0
|
|
301
|
+
want = pending if args.all else set(args.ids)
|
|
302
|
+
missing = want - pending
|
|
303
|
+
if missing:
|
|
304
|
+
print("error: onay bekleyen öneri değil: " + ", ".join(sorted(missing)))
|
|
305
|
+
return 2
|
|
306
|
+
path = os.path.join(root, "featmap.toml")
|
|
307
|
+
lines = G.read(root, "featmap.toml").splitlines(keepends=True)
|
|
308
|
+
starts = [i for i, l in enumerate(lines) if l.startswith("[") and "=" not in l.split("]")[0]]
|
|
309
|
+
out = lines[:starts[0]] if starts else lines
|
|
310
|
+
for a, b in zip(starts, starts[1:] + [len(lines)]):
|
|
311
|
+
block = lines[a:b]
|
|
312
|
+
header = block[0].strip().split("#")[0].strip()
|
|
313
|
+
body = tomllib.loads("".join(block[1:]))
|
|
314
|
+
key = {"[[unassigned]]": body.get("entry"), "[[dispatch]]": body.get("expr")}.get(
|
|
315
|
+
header, header[len("[feature."):-1] if header.startswith("[feature.") else None)
|
|
316
|
+
out += [l for l in block if not (key in want and PROPOSED_LINE.match(l))]
|
|
317
|
+
with open(path, "w", encoding="utf-8") as fh:
|
|
318
|
+
fh.write("".join(out))
|
|
319
|
+
left = {key for _, key in G.proposed(G.load_config(root))}
|
|
320
|
+
if want & left: # e.g. `proposed = true` written inline in an unexpected form
|
|
321
|
+
print("error: featmap.toml içinde kaldırılamadı: " + ", ".join(sorted(want & left)))
|
|
322
|
+
return 1
|
|
323
|
+
print(f"onaylandı: {len(want)}")
|
|
324
|
+
return 0
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def cmd_callers(args, reverse=True):
|
|
328
|
+
root, g, _, _ = load(args)
|
|
329
|
+
ix, out = I.Index(g), Out()
|
|
330
|
+
nid = pick(ix, args.symbol, out)
|
|
331
|
+
if nid is None:
|
|
332
|
+
emit(args, out)
|
|
333
|
+
return 2
|
|
334
|
+
rows, locs, possible_total = [], [], 0
|
|
335
|
+
frontier, seen = [nid], {nid}
|
|
336
|
+
for depth in range(1, args.depth + 1):
|
|
337
|
+
nxt = []
|
|
338
|
+
for n in frontier:
|
|
339
|
+
if reverse:
|
|
340
|
+
res, poss = ix.callers(n, args.possible)
|
|
341
|
+
possible_total += poss if depth == 1 else 0
|
|
342
|
+
pairs = [(e, e["from"], p) for e, p in res]
|
|
343
|
+
else:
|
|
344
|
+
pairs = [(e, t, e["kind"] == "method?") for e, t in ix.callees(n, args.possible)]
|
|
345
|
+
for e, other, p in pairs:
|
|
346
|
+
rows.append((depth, n, other, e, p))
|
|
347
|
+
locs.extend(e["at"] if reverse else [ix.loc(other)])
|
|
348
|
+
if other not in seen:
|
|
349
|
+
seen.add(other)
|
|
350
|
+
nxt.append(other)
|
|
351
|
+
frontier = nxt
|
|
352
|
+
name = "callers" if reverse else "callees"
|
|
353
|
+
out.add(f"{name} {nid} ({ix.loc(nid)})")
|
|
354
|
+
add_files(out, locs)
|
|
355
|
+
for depth, n, other, e, p in rows:
|
|
356
|
+
arrow = f"{other} → {n}" if reverse else f"{n} → {other}"
|
|
357
|
+
tag = " (olası)" if p else ""
|
|
358
|
+
out.add(f" {' ' * (depth - 1)}{arrow} {e['kind']}{tag} {', '.join(e['at'])}",
|
|
359
|
+
rank=1 if depth == 1 else 10 + depth, what="derin seviye" if depth > 1 else "kenar detayı")
|
|
360
|
+
if reverse and possible_total and not args.possible:
|
|
361
|
+
out.add(f"olası çağıran (method?): {possible_total} (--possible ile göster)")
|
|
362
|
+
out.data = {"symbol": nid, "files": sorted(set(locs), key=G.at_key),
|
|
363
|
+
"edges": [{"depth": d, "from": (o if reverse else n), "to": (n if reverse else o),
|
|
364
|
+
"kind": e["kind"], "at": e["at"], "possible": p} for d, n, o, e, p in rows]}
|
|
365
|
+
if reverse:
|
|
366
|
+
out.data["possible_callers"] = possible_total
|
|
367
|
+
emit(args, out)
|
|
368
|
+
return 0
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
def cmd_affected(args):
|
|
372
|
+
root, g, _, _ = load(args)
|
|
373
|
+
ix, out = I.Index(g), Out()
|
|
374
|
+
nid = pick(ix, args.symbol, out)
|
|
375
|
+
if nid is None:
|
|
376
|
+
emit(args, out)
|
|
377
|
+
return 2
|
|
378
|
+
seen = ix.affected([nid], possible=args.possible)
|
|
379
|
+
seen.pop(nid)
|
|
380
|
+
out.add(f"affected {nid} ({ix.loc(nid)})")
|
|
381
|
+
locs = sorted({ix.loc(n) for n in seen}, key=G.at_key)
|
|
382
|
+
add_files(out, locs)
|
|
383
|
+
for n, (d, p) in sorted(seen.items(), key=lambda kv: (kv[1][0], kv[0])):
|
|
384
|
+
out.add(f" {d} {n} ({ix.loc(n)}){' (olası)' if p else ''}", rank=1 if d == 1 else 10 + d,
|
|
385
|
+
what="derin seviye" if d > 1 else "kenar detayı")
|
|
386
|
+
out.data = {"symbol": nid, "files": locs, "affected": {n: {"depth": d, "possible": p} for n, (d, p) in seen.items()}}
|
|
387
|
+
emit(args, out)
|
|
388
|
+
return 0
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
def cmd_path(args):
|
|
392
|
+
root, g, _, _ = load(args)
|
|
393
|
+
ix, out = I.Index(g), Out()
|
|
394
|
+
a = pick(ix, args.a, out)
|
|
395
|
+
b = pick(ix, args.b, out) if a else None
|
|
396
|
+
if not a or not b:
|
|
397
|
+
emit(args, out)
|
|
398
|
+
return 2
|
|
399
|
+
# BFS; parents keep every shortest predecessor so we can count alternatives
|
|
400
|
+
dist, parents = {a: 0}, {a: []}
|
|
401
|
+
q = deque([a])
|
|
402
|
+
while q:
|
|
403
|
+
n = q.popleft()
|
|
404
|
+
for e, t in sorted(ix.callees(n, args.possible), key=lambda x: x[1]):
|
|
405
|
+
if t not in dist:
|
|
406
|
+
dist[t] = dist[n] + 1
|
|
407
|
+
parents[t] = [(n, e)]
|
|
408
|
+
q.append(t)
|
|
409
|
+
elif dist[t] == dist[n] + 1:
|
|
410
|
+
parents[t].append((n, e))
|
|
411
|
+
if b not in dist:
|
|
412
|
+
unknown = sum(1 for n in dist for e in ix.fwd.get(n, []) if e["to"] == "?")
|
|
413
|
+
out.add(f"yol yok: {a} → {b}")
|
|
414
|
+
out.add(f"{a}'dan erişilebilir {unknown} `?` kenarı var; yolun yokluğu kanıt değildir")
|
|
415
|
+
out.data = {"path": None, "reachable_unknown": unknown}
|
|
416
|
+
emit(args, out)
|
|
417
|
+
return 1
|
|
418
|
+
|
|
419
|
+
def count(n, memo={}):
|
|
420
|
+
if n == a:
|
|
421
|
+
return 1
|
|
422
|
+
if n not in memo:
|
|
423
|
+
memo[n] = sum(count(p) for p, _ in parents[n])
|
|
424
|
+
return memo[n]
|
|
425
|
+
|
|
426
|
+
steps, n = [], b
|
|
427
|
+
while n != a:
|
|
428
|
+
p, e = min(parents[n], key=lambda x: x[0])
|
|
429
|
+
steps.append((p, n, e))
|
|
430
|
+
n = p
|
|
431
|
+
steps.reverse()
|
|
432
|
+
out.add(f"path {a} → {b}")
|
|
433
|
+
locs = sorted({ix.loc(a)} | {at for _, _, e in steps for at in e["at"]}, key=G.at_key)
|
|
434
|
+
add_files(out, locs)
|
|
435
|
+
out.add(f" {a} ({ix.loc(a)})")
|
|
436
|
+
for i, (p, n, e) in enumerate(steps, 1):
|
|
437
|
+
out.add(f" {' ' * i}→ {n} ({ix.loc(n)}) {e['kind']} {', '.join(e['at'])}")
|
|
438
|
+
others = count(b) - 1
|
|
439
|
+
if others:
|
|
440
|
+
out.add(f"{others} başka en kısa yol")
|
|
441
|
+
out.data = {"path": [a] + [n for _, n, _ in steps], "files": locs, "other_shortest": others}
|
|
442
|
+
emit(args, out)
|
|
443
|
+
return 0
|
|
444
|
+
|
|
445
|
+
|
|
446
|
+
def cmd_unknown(args):
|
|
447
|
+
root, g, _, _ = load(args)
|
|
448
|
+
out = Out()
|
|
449
|
+
groups = {}
|
|
450
|
+
for e in g["edges"]:
|
|
451
|
+
if e["to"] == "?" or e["kind"] == "ignored":
|
|
452
|
+
groups.setdefault(e["kind"], []).append(e)
|
|
453
|
+
out.add("unknown: " + (", ".join(f"{k} {len(v)}" for k, v in sorted(groups.items())) or "yok"))
|
|
454
|
+
order = ["unresolved"] + sorted(k for k in groups if k != "unresolved")
|
|
455
|
+
for k in order:
|
|
456
|
+
for e in groups.get(k, []):
|
|
457
|
+
extra = f" adaylar: {', '.join(e['candidates'])}" if e.get("candidates") else ""
|
|
458
|
+
extra += f" ({e['reason']})" if e.get("reason") else ""
|
|
459
|
+
out.add(f" {k} {', '.join(e['at'])} `{e.get('expr', '')}`{extra}") # spec §7.3: never cut
|
|
460
|
+
out.data = {k: v for k, v in groups.items()}
|
|
461
|
+
emit(args, out)
|
|
462
|
+
return 0
|
|
463
|
+
|
|
464
|
+
|
|
465
|
+
def feature_view(ix, fid, f, out, full=True, root=None):
|
|
466
|
+
locs, callers, callees = [], [], []
|
|
467
|
+
for sym in f.get("entry", []):
|
|
468
|
+
if sym not in ix.nodes:
|
|
469
|
+
continue
|
|
470
|
+
locs.append(ix.loc(sym))
|
|
471
|
+
for e, _ in ix.callers(sym)[0]:
|
|
472
|
+
callers.append((sym, e))
|
|
473
|
+
locs.extend(e["at"])
|
|
474
|
+
# the whole definite forward chain, the mirror of impact's reverse closure: `verified` and files must see deep callees
|
|
475
|
+
frontier = [s for s in f.get("entry", []) if s in ix.nodes]
|
|
476
|
+
seen, depth = set(frontier), 0
|
|
477
|
+
while frontier:
|
|
478
|
+
depth, nxt = depth + 1, []
|
|
479
|
+
for sym in frontier:
|
|
480
|
+
for e, t in ix.callees(sym):
|
|
481
|
+
callees.append((depth, sym, t, e))
|
|
482
|
+
locs.append(ix.loc(t))
|
|
483
|
+
if t in ix.nodes and t not in seen:
|
|
484
|
+
seen.add(t)
|
|
485
|
+
nxt.append(t)
|
|
486
|
+
frontier = nxt
|
|
487
|
+
reach_sites = {f"{e['kind']}:{e['value']}": e["at"] for e in ix.g["entries"] + ix.g.get("reach", [])}
|
|
488
|
+
for r in f.get("reach", []):
|
|
489
|
+
locs.extend(reach_sites.get(r, [])[:1])
|
|
490
|
+
out.add(f"feature {fid} — {f.get('title', '')}")
|
|
491
|
+
add_files(out, locs)
|
|
492
|
+
if not full:
|
|
493
|
+
return locs
|
|
494
|
+
out.add("entry:")
|
|
495
|
+
for sym in f.get("entry", []):
|
|
496
|
+
out.add(f" {sym} ({ix.loc(sym)})")
|
|
497
|
+
if callers:
|
|
498
|
+
out.add("callers:", rank=1, what="kenar detayı")
|
|
499
|
+
for sym, e in callers:
|
|
500
|
+
out.add(f" {e['from']} → {sym} {e['kind']} {', '.join(e['at'])}", rank=1, what="kenar detayı")
|
|
501
|
+
if callees:
|
|
502
|
+
out.add("callees:", rank=2, what="kenar detayı")
|
|
503
|
+
for d, sym, t, e in callees:
|
|
504
|
+
out.add(f" {' ' * (d - 1)}{sym} → {t} ({ix.loc(t)}) {e['kind']}",
|
|
505
|
+
rank=2 if d == 1 else 10 + d, what="kenar detayı" if d == 1 else "derin seviye")
|
|
506
|
+
if f.get("reach"):
|
|
507
|
+
reach = f["reach"]
|
|
508
|
+
out.add("reach: " + " ".join(reach), what="reach",
|
|
509
|
+
short="reach: " + " ".join(reach[:REACH_SHORT]) + (f" (+{len(reach) - REACH_SHORT} daha)"
|
|
510
|
+
if len(reach) > REACH_SHORT else ""))
|
|
511
|
+
out.add("test: " + ("; ".join(f.get("test", [])) or
|
|
512
|
+
("(yok — elle doğrula, aşağıda)" if f.get("verify") else "(yok — doğrulanamaz)")))
|
|
513
|
+
if f.get("verify"):
|
|
514
|
+
out.add("verify:")
|
|
515
|
+
for step in f["verify"]:
|
|
516
|
+
out.add(f" {step}")
|
|
517
|
+
if f.get("expect"):
|
|
518
|
+
out.add("expect: " + f["expect"])
|
|
519
|
+
if root:
|
|
520
|
+
out.add("verified: " + verified_status(root, f.get("verified"), locs,
|
|
521
|
+
[s for s in f.get("entry", []) if s not in ix.nodes]))
|
|
522
|
+
for gotcha in f.get("gotchas", []):
|
|
523
|
+
out.add("gotcha: " + gotcha, rank=50, what="gotcha")
|
|
524
|
+
if f.get("does"):
|
|
525
|
+
out.add("does: " + f["does"], rank=100, what="does")
|
|
526
|
+
return locs
|
|
527
|
+
|
|
528
|
+
|
|
529
|
+
def verified_status(root, sha, locs, missing=()):
|
|
530
|
+
"""Whether the feature's files changed since the commit its verify steps last passed at."""
|
|
531
|
+
if not sha:
|
|
532
|
+
return "hiç (adımlar denenip `verified = \"<sha>\"` yazılmadı)"
|
|
533
|
+
if G.git(root, "cat-file", "-e", f"{sha}^{{commit}}", check=False).returncode != 0:
|
|
534
|
+
return f"{sha} bulunamadı — adımları yeniden dene"
|
|
535
|
+
if missing:
|
|
536
|
+
return f"{sha} — bayat: giriş artık yok ({', '.join(missing)})"
|
|
537
|
+
files = sorted({loc.rpartition(":")[0] for loc in locs})
|
|
538
|
+
changed = sorted({p for args in (("diff", "--name-only", "-z", sha), ("ls-files", "-z", "--others", "--exclude-standard"))
|
|
539
|
+
for p in G.git(root, *args, "--", *files).stdout.split("\0") if p}) if files else [] # untracked = new since sha
|
|
540
|
+
return (f"{sha} — bayat: o günden beri {len(changed)} dosya değişti ({', '.join(changed[:3])}"
|
|
541
|
+
+ (", …" if len(changed) > 3 else "") + ")") if changed else f"{sha} — güncel"
|
|
542
|
+
|
|
543
|
+
|
|
544
|
+
def cmd_show(args):
|
|
545
|
+
root, g, _, _ = load(args)
|
|
546
|
+
ix, out = I.Index(g), Out()
|
|
547
|
+
feats = g["features"]
|
|
548
|
+
if args.feature not in feats:
|
|
549
|
+
out.add(f"özellik yok: {args.feature}")
|
|
550
|
+
for n in closest(args.feature, list(feats)):
|
|
551
|
+
out.add(f" yakın: {n}")
|
|
552
|
+
emit(args, out)
|
|
553
|
+
return 2
|
|
554
|
+
locs = feature_view(ix, args.feature, feats[args.feature], out, root=root)
|
|
555
|
+
out.data = {"feature": args.feature, **feats[args.feature], "files": sorted(set(locs), key=G.at_key)}
|
|
556
|
+
emit(args, out)
|
|
557
|
+
return 0
|
|
558
|
+
|
|
559
|
+
|
|
560
|
+
def cmd_find(args):
|
|
561
|
+
root, g, _, _ = load(args)
|
|
562
|
+
ix, out = I.Index(g), Out()
|
|
563
|
+
q = norm(args.text)
|
|
564
|
+
hit = lambda s: norm(s) == q or norm(s).startswith(q)
|
|
565
|
+
feats = [fid for fid, f in sorted(g["features"].items())
|
|
566
|
+
if word_hit(q, fid) or any(hit(s) for s in [fid, f.get("title", "")] + f.get("aliases", []))]
|
|
567
|
+
entries = [e for e in g["entries"] + g.get("reach", []) if hit(e["value"]) or hit(f"{e['kind']}:{e['value']}")
|
|
568
|
+
or (e["kind"] == "route" and q.startswith("/") and q == norm(e["value"]).partition(" ")[2])
|
|
569
|
+
or (e["kind"] in ("text", "testid") and q in norm(e["value"]))]
|
|
570
|
+
syms = sorted(n for n in g["nodes"] if hit(n.rsplit(":", 1)[-1]) or hit(n.rsplit(":", 1)[-1].rsplit(".", 1)[-1])
|
|
571
|
+
or word_hit(q, n.rsplit(":", 1)[-1].rsplit(".", 1)[-1]))
|
|
572
|
+
if not (feats or entries or syms):
|
|
573
|
+
out.add(f"yok: {args.text}")
|
|
574
|
+
names = list(g["features"]) + [a for f in g["features"].values() for a in f.get("aliases", [])]
|
|
575
|
+
names += [e["value"] for e in g["entries"] + g.get("reach", [])] + list(g["nodes"])
|
|
576
|
+
near = closest(args.text, names)
|
|
577
|
+
for n in near:
|
|
578
|
+
out.add(f" yakın: {n}")
|
|
579
|
+
out.data = {"query": args.text, "features": [], "entries": [], "symbols": [], "near": near}
|
|
580
|
+
emit(args, out)
|
|
581
|
+
return 1
|
|
582
|
+
locs_all = []
|
|
583
|
+
for fid in feats:
|
|
584
|
+
locs_all += feature_view(ix, fid, g["features"][fid], out, full=False)
|
|
585
|
+
by_reach, reach_nodes = {}, {}
|
|
586
|
+
sites = {f"{e['kind']}:{e['value']}": e.get("nodes", []) for e in g["entries"] + g.get("reach", [])}
|
|
587
|
+
for fid, f in g["features"].items():
|
|
588
|
+
reach_nodes[fid] = [n for r in f.get("reach", []) for n in sites.get(r, [])]
|
|
589
|
+
for r in f.get("reach", []):
|
|
590
|
+
by_reach.setdefault(r, []).append(fid)
|
|
591
|
+
owned_entries = []
|
|
592
|
+
for e in entries:
|
|
593
|
+
key = f"{e['kind']}:{e['value']}"
|
|
594
|
+
owners = list(by_reach.get(key, []))
|
|
595
|
+
# screen text -> its component -> every feature whose entry reaches that component (spec §10.1)
|
|
596
|
+
up = ix.affected(e.get("nodes", []), possible=False)
|
|
597
|
+
owners += [fid for fid, f in sorted(g["features"].items())
|
|
598
|
+
if fid not in owners and any(s in up for s in f.get("entry", []) + reach_nodes.get(fid, []))]
|
|
599
|
+
owned_entries.append({**e, "owners": owners})
|
|
600
|
+
out.add(f"{key} {', '.join(e['at'])} → {', '.join(owners) or '(atanmamış)'}")
|
|
601
|
+
for n in syms:
|
|
602
|
+
out.add(f"symbol {n} ({ix.loc(n)})", rank=1, what="sembol")
|
|
603
|
+
out.data = {"query": args.text, "features": feats, "entries": owned_entries, "symbols": syms, "near": []}
|
|
604
|
+
emit(args, out)
|
|
605
|
+
return 0
|
|
606
|
+
|
|
607
|
+
|
|
608
|
+
def cmd_entries(args):
|
|
609
|
+
root, g, _, _ = load(args)
|
|
610
|
+
config = G.load_config(root)
|
|
611
|
+
out = Out()
|
|
612
|
+
owners = {}
|
|
613
|
+
for fid, f in config.get("feature", {}).items():
|
|
614
|
+
for r in f.get("reach", []):
|
|
615
|
+
owners.setdefault(r, []).append(fid)
|
|
616
|
+
for u in config.get("unassigned", []):
|
|
617
|
+
owners.setdefault(u.get("entry"), []).append("[unassigned]")
|
|
618
|
+
un = 0
|
|
619
|
+
for e in g["entries"]:
|
|
620
|
+
key = f"{e['kind']}:{e['value']}"
|
|
621
|
+
o = owners.get(key)
|
|
622
|
+
un += not o
|
|
623
|
+
out.add(f"{key} {', '.join(o) if o else 'ATANMAMIŞ'} {', '.join(e['at'])}")
|
|
624
|
+
out.add(f"{len(g['entries'])} giriş noktası, {un} atanmamış")
|
|
625
|
+
out.data = {"entries": g["entries"], "owners": owners}
|
|
626
|
+
emit(args, out)
|
|
627
|
+
return 0
|
|
628
|
+
|
|
629
|
+
|
|
630
|
+
# ---------- impact / verify ----------
|
|
631
|
+
def load_impact(args):
|
|
632
|
+
root = G.repo_root(args.root)
|
|
633
|
+
config = G.load_config(root)
|
|
634
|
+
after, _, files = G.build(root, untracked=True, config=config)
|
|
635
|
+
warn_incomplete(after)
|
|
636
|
+
return impact.impact_data(root, args.rev, args.possible, config, after, files)
|
|
637
|
+
|
|
638
|
+
|
|
639
|
+
def cmd_impact(args):
|
|
640
|
+
d = load_impact(args)
|
|
641
|
+
ia, out = d["ia"], Out()
|
|
642
|
+
out.add(f"impact vs {d['rev']}")
|
|
643
|
+
if d["note"]:
|
|
644
|
+
out.add(d["note"])
|
|
645
|
+
locs = [ia.loc(n) for n in d["changed"]] + [ia.loc(n) for n in d["affected"]]
|
|
646
|
+
add_files(out, locs)
|
|
647
|
+
if d["unverified"]:
|
|
648
|
+
out.add("unverified: " + ", ".join(d["unverified"]) + " (testi yok)")
|
|
649
|
+
for n in d["unreached"]:
|
|
650
|
+
out.add(f"unverified: {n} ({ia.loc(n)}) — seçilen hiçbir test ulaşmıyor")
|
|
651
|
+
for fid in d["manual"]:
|
|
652
|
+
out.add(f"elle doğrula: {fid} (testi yok; adımlar: featmap show {fid})")
|
|
653
|
+
for fid in d["steps"]:
|
|
654
|
+
out.add(f"doğrula: {fid} (testlere ek elle adımlar; geçince verified güncelle: featmap show {fid})")
|
|
655
|
+
if d["fallback"]:
|
|
656
|
+
out.add("run: tam takım eklendi — statik olarak ulaşılmayan değişiklik var")
|
|
657
|
+
for edge in d["framework_callbacks"]:
|
|
658
|
+
out.add(f"?callback: {edge['from']} — {edge['expr']} ({edge['reason']})")
|
|
659
|
+
if d["changed"] or d["removed"]:
|
|
660
|
+
out.add("changed:", rank=1, what="kenar detayı")
|
|
661
|
+
for n in d["changed"]:
|
|
662
|
+
out.add(f" {n} ({ia.loc(n)})", rank=1, what="kenar detayı")
|
|
663
|
+
for n in d["removed"]:
|
|
664
|
+
out.add(f" silindi: {n}", rank=1, what="kenar detayı")
|
|
665
|
+
if d["keys_changed"]:
|
|
666
|
+
out.add("giriş anahtarı değişti: " + ", ".join(d["keys_changed"]))
|
|
667
|
+
aff = {n: v for n, v in d["affected"].items() if n not in d["changed"]}
|
|
668
|
+
if aff:
|
|
669
|
+
out.add("affected:", rank=1, what="kenar detayı")
|
|
670
|
+
for n, (dep, p) in sorted(aff.items(), key=lambda kv: (kv[1][0], kv[0])):
|
|
671
|
+
out.add(f" {dep} {n} ({ia.loc(n)}){' (olası)' if p else ''}", rank=1 if dep == 1 else 10 + dep,
|
|
672
|
+
what="derin seviye" if dep > 1 else "kenar detayı")
|
|
673
|
+
out.add("features: " + (", ".join(d["features"]) or "(yok)"))
|
|
674
|
+
out.add("run:")
|
|
675
|
+
for c, why in d["commands"]:
|
|
676
|
+
out.add(f" {c} # {why}")
|
|
677
|
+
if not d["commands"]:
|
|
678
|
+
out.add(" (koşulacak test yok)")
|
|
679
|
+
out.data = {k: v for k, v in d.items() if k not in ("ia", "root")}
|
|
680
|
+
out.data["affected"] = {n: {"depth": a, "possible": b} for n, (a, b) in d["affected"].items()}
|
|
681
|
+
emit(args, out)
|
|
682
|
+
return 0
|
|
683
|
+
|
|
684
|
+
|
|
685
|
+
def trace_env(root):
|
|
686
|
+
"""A sitecustomize shim on PYTHONPATH, so every Python (sub)process the tests start is traced."""
|
|
687
|
+
common = G.git(root, "rev-parse", "--git-common-dir").stdout.strip()
|
|
688
|
+
tdir = os.path.join(root, common, "fmap", "trace")
|
|
689
|
+
shutil.rmtree(tdir, ignore_errors=True)
|
|
690
|
+
os.makedirs(tdir)
|
|
691
|
+
shutil.copy(os.path.join(os.path.dirname(os.path.abspath(__file__)), "trace_site.py"),
|
|
692
|
+
os.path.join(tdir, "sitecustomize.py"))
|
|
693
|
+
env = dict(os.environ, FMAP_TRACE_ROOT=root, FMAP_TRACE_OUT=tdir)
|
|
694
|
+
# shortcut: shadows a project's own sitecustomize.py, upgrade if a target repo ships one
|
|
695
|
+
env["PYTHONPATH"] = os.pathsep.join([tdir] + [p for p in [os.environ.get("PYTHONPATH")] if p])
|
|
696
|
+
return env, tdir
|
|
697
|
+
|
|
698
|
+
|
|
699
|
+
def trace_report(ix, tdir, changed):
|
|
700
|
+
nodes = ix.nodes
|
|
701
|
+
by_file = {}
|
|
702
|
+
for nid, n in nodes.items():
|
|
703
|
+
by_file.setdefault(n["file"], []).append(nid)
|
|
704
|
+
|
|
705
|
+
def node_of(k):
|
|
706
|
+
f, qual, _first, body = k
|
|
707
|
+
if qual == "<module>":
|
|
708
|
+
return f"{f}:<module>"
|
|
709
|
+
nid = f"{f}:{qual.replace('.<locals>', '')}"
|
|
710
|
+
if nid in nodes:
|
|
711
|
+
return nid
|
|
712
|
+
inner = [i for i in by_file.get(f, []) if nodes[i]["kind"] != "module"
|
|
713
|
+
and nodes[i]["line"] <= body <= nodes[i]["end_line"]]
|
|
714
|
+
return max(inner, key=lambda i: nodes[i]["line"]) if inner else f"{f}:<module>"
|
|
715
|
+
|
|
716
|
+
ran, observed = set(), set()
|
|
717
|
+
for name in sorted(os.listdir(tdir)):
|
|
718
|
+
if not name.startswith("trace-"):
|
|
719
|
+
continue
|
|
720
|
+
with open(os.path.join(tdir, name)) as fh:
|
|
721
|
+
for a, b in json.load(fh):
|
|
722
|
+
callee = node_of(b)
|
|
723
|
+
ran.add(callee)
|
|
724
|
+
if a and not (b[1].rsplit(".", 1)[-1].startswith("__") and b[1].rsplit(".", 1)[-1] != "__init__"):
|
|
725
|
+
observed.add((node_of(a), callee))
|
|
726
|
+
lines = []
|
|
727
|
+
py_changed = [n for n in changed if n in nodes and nodes[n]["file"].endswith(".py")]
|
|
728
|
+
for n in sorted(set(py_changed) - ran):
|
|
729
|
+
lines.append(f"unverified: {n} ({ix.loc(n)}) — hiçbir test çalıştırmadı")
|
|
730
|
+
for a, b in sorted(observed):
|
|
731
|
+
if a == b or any(e["to"] == b or b in e.get("candidates", []) for e in ix.fwd.get(a, [])
|
|
732
|
+
if e["kind"] in TRAVERSE or e["kind"] in ("method?", "?http")):
|
|
733
|
+
continue
|
|
734
|
+
unknown = [e for e in ix.fwd.get(a, []) if e["kind"] in ("unresolved", "?callback", "method?", "ignored")]
|
|
735
|
+
rule = (f'[[dispatch]] at = "{nodes[a]["file"] if a in nodes else a}" expr = "{unknown[0]["expr"]}" targets = ["{b}"]'
|
|
736
|
+
if len(unknown) == 1 and unknown[0].get("expr") else "kural için çağrı yerine bak")
|
|
737
|
+
lines.append(f"statikte yok: {a} → {b} öneri: {rule}")
|
|
738
|
+
other = sorted({os.path.splitext(nodes[n]["file"])[1] for n in changed
|
|
739
|
+
if n in nodes and not nodes[n]["file"].endswith(".py")})
|
|
740
|
+
if other:
|
|
741
|
+
lines.append(f"trace unsupported: {', '.join(other)} (bu semboller unverified sayılmaz)")
|
|
742
|
+
return lines
|
|
743
|
+
|
|
744
|
+
|
|
745
|
+
def cmd_verify(args):
|
|
746
|
+
d = load_impact(args)
|
|
747
|
+
env, tdir = trace_env(d["root"]) if args.trace else (None, None)
|
|
748
|
+
failed = 0
|
|
749
|
+
for c, why in d["commands"]:
|
|
750
|
+
print(f"$ {c} # {why}", flush=True)
|
|
751
|
+
r = subprocess.run(c, shell=True, cwd=d["root"], env=env)
|
|
752
|
+
status = "geçti" if r.returncode == 0 else f"kaldı (exit {r.returncode})"
|
|
753
|
+
failed += r.returncode != 0
|
|
754
|
+
print(f" → {status}")
|
|
755
|
+
for fid in d["unverified"]:
|
|
756
|
+
print(f"doğrulanamadı: {fid} (testi yok)")
|
|
757
|
+
for fid in d["manual"]:
|
|
758
|
+
print(f"elle doğrula: {fid} (testi yok; adımlar: featmap show {fid})")
|
|
759
|
+
for fid in d["steps"]:
|
|
760
|
+
print(f"doğrula: {fid} (testlere ek elle adımlar; geçince verified güncelle: featmap show {fid})")
|
|
761
|
+
for n in d["unreached"]:
|
|
762
|
+
print(f"doğrulanamadı: {n} ({d['ia'].loc(n)}) — seçilen hiçbir test ulaşmıyor")
|
|
763
|
+
if args.trace:
|
|
764
|
+
for line in trace_report(d["ia"], tdir, d["changed"]):
|
|
765
|
+
print(line)
|
|
766
|
+
if not d["commands"]:
|
|
767
|
+
if d["changed"] or d["removed"]:
|
|
768
|
+
print(f"verify: doğrulanamadı — {len(d['changed']) + len(d['removed'])} değişen sembol için "
|
|
769
|
+
"seçilen test yok")
|
|
770
|
+
return 1
|
|
771
|
+
if G.git(d["root"], "status", "--porcelain", "--untracked-files=no").stdout.strip():
|
|
772
|
+
print("verify: doğrulanacak sembol değişmedi")
|
|
773
|
+
return 0
|
|
774
|
+
print("verify: değişiklik yok")
|
|
775
|
+
return 0
|
|
776
|
+
print(f"verify: {len(d['commands']) - failed}/{len(d['commands'])} geçti"
|
|
777
|
+
+ (f", {len(d['unverified']) + len(d['unreached']) + len(d['manual'])} doğrulanamadı"
|
|
778
|
+
if d["unverified"] or d["unreached"] or d["manual"] else ""))
|
|
779
|
+
return 1 if failed else 0
|
|
780
|
+
|
|
781
|
+
|
|
782
|
+
# ---------- hook ----------
|
|
783
|
+
def cmd_hook(args):
|
|
784
|
+
root = G.repo_root(args.root)
|
|
785
|
+
if args.action == "install":
|
|
786
|
+
return hook_install(root)
|
|
787
|
+
unstaged = G.git(root, "diff", "--name-only").stdout.split()
|
|
788
|
+
staged = G.git(root, "diff", "--cached", "--name-only").stdout.split()
|
|
789
|
+
src = lambda p: p == "featmap.toml" or os.path.splitext(p)[1] in G.SOURCE_EXT | G.UNSUPPORTED_EXT
|
|
790
|
+
dirty = [p for p in unstaged if src(p)]
|
|
791
|
+
if dirty:
|
|
792
|
+
print("fmap: önce stage'le ya da stash'le — stage'lenmemiş değişiklik: " + ", ".join(dirty))
|
|
793
|
+
return 1
|
|
794
|
+
if not any(src(p) for p in staged):
|
|
795
|
+
return 0
|
|
796
|
+
args.untracked = False
|
|
797
|
+
if cmd_build(args):
|
|
798
|
+
return 1
|
|
799
|
+
G.git(root, "add", "featmap.json")
|
|
800
|
+
return cmd_check(args)
|
|
801
|
+
|
|
802
|
+
|
|
803
|
+
def hook_install(root):
|
|
804
|
+
path = os.path.join(root, "tools", "hooks", "pre-commit")
|
|
805
|
+
hooks_path = G.git(root, "config", "--get", "core.hooksPath", check=False).stdout.strip()
|
|
806
|
+
if hooks_path and hooks_path != "tools/hooks":
|
|
807
|
+
print(f"core.hooksPath zaten '{hooks_path}' (husky/lefthook?). Mevcut pre-commit hook'una şu satırı ekle:")
|
|
808
|
+
print(" featmap hook run")
|
|
809
|
+
return 1
|
|
810
|
+
os.makedirs(os.path.dirname(path), exist_ok=True)
|
|
811
|
+
with open(path, "w") as fh:
|
|
812
|
+
fh.write("#!/bin/sh\nexec featmap hook run\n")
|
|
813
|
+
os.chmod(path, os.stat(path).st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
|
|
814
|
+
if not hooks_path:
|
|
815
|
+
G.git(root, "config", "core.hooksPath", "tools/hooks")
|
|
816
|
+
print("tools/hooks/pre-commit yazıldı; core.hooksPath=tools/hooks. Dosyayı commit et.")
|
|
817
|
+
return 0
|
|
818
|
+
|
|
819
|
+
|
|
820
|
+
# ---------- main ----------
|
|
821
|
+
def positive_int(text):
|
|
822
|
+
value = int(text) if re.fullmatch(r"[+-]?\d+", text.strip()) else None
|
|
823
|
+
if value is None or value <= 0:
|
|
824
|
+
raise argparse.ArgumentTypeError(f"pozitif bir tam sayı olmalı: {text!r}")
|
|
825
|
+
return value
|
|
826
|
+
|
|
827
|
+
|
|
828
|
+
def main(argv=None):
|
|
829
|
+
ap = argparse.ArgumentParser(prog="featmap", description="Exact code + feature map for coding agents")
|
|
830
|
+
ap.add_argument("-C", dest="root", default=".", help="repo dizini")
|
|
831
|
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
|
832
|
+
|
|
833
|
+
def common(p, possible=False):
|
|
834
|
+
p.add_argument("--json", action="store_true")
|
|
835
|
+
p.add_argument("--budget", type=positive_int, default=None)
|
|
836
|
+
p.add_argument("--possible", default=possible,
|
|
837
|
+
action=argparse.BooleanOptionalAction if possible else "store_true",
|
|
838
|
+
help="method? kenarlarını da izle" + (" (varsayılan: açık)" if possible else ""))
|
|
839
|
+
p.set_defaults(untracked=True)
|
|
840
|
+
return p
|
|
841
|
+
|
|
842
|
+
sub.add_parser("build")
|
|
843
|
+
sub.add_parser("check")
|
|
844
|
+
for name in ("callers", "callees"):
|
|
845
|
+
p = common(sub.add_parser(name))
|
|
846
|
+
p.add_argument("symbol")
|
|
847
|
+
p.add_argument("--depth", type=int, default=1)
|
|
848
|
+
common(sub.add_parser("affected")).add_argument("symbol")
|
|
849
|
+
p = common(sub.add_parser("path"))
|
|
850
|
+
p.add_argument("a")
|
|
851
|
+
p.add_argument("b")
|
|
852
|
+
common(sub.add_parser("show")).add_argument("feature")
|
|
853
|
+
common(sub.add_parser("find")).add_argument("text")
|
|
854
|
+
common(sub.add_parser("unknown"))
|
|
855
|
+
common(sub.add_parser("entries"))
|
|
856
|
+
common(sub.add_parser("impact"), possible=True).add_argument("rev", nargs="?", default="HEAD")
|
|
857
|
+
p = sub.add_parser("verify")
|
|
858
|
+
p.add_argument("--possible", action=argparse.BooleanOptionalAction, default=True,
|
|
859
|
+
help="method? kenarlarını da izle (varsayılan: açık)")
|
|
860
|
+
p.add_argument("rev", nargs="?", default="HEAD")
|
|
861
|
+
p.add_argument("--trace", action="store_true")
|
|
862
|
+
p = sub.add_parser("approve")
|
|
863
|
+
p.add_argument("ids", nargs="*")
|
|
864
|
+
p.add_argument("--all", action="store_true")
|
|
865
|
+
sub.add_parser("hook").add_argument("action", choices=["run", "install"])
|
|
866
|
+
|
|
867
|
+
argv = list(sys.argv[1:] if argv is None else argv)
|
|
868
|
+
i = 0 # the subcommand slot: after the global `-C DIR` / `-CDIR` options
|
|
869
|
+
while i < len(argv) and argv[i].startswith("-C"):
|
|
870
|
+
i += 2 if argv[i] == "-C" else 1
|
|
871
|
+
if argv[i:i + 1] == ["find"]: # `fmap find --flag`: an unknown option-looking query is a positional
|
|
872
|
+
opts, rest, k = [], [], i + 1 # known find options stay options wherever they are; they go before the inserted `--`
|
|
873
|
+
while k < len(argv) and argv[k] != "--":
|
|
874
|
+
a = argv[k]
|
|
875
|
+
n = 2 if a == "--budget" else 1 if a in ("--json", "--possible") or a.startswith("--budget=") else 0
|
|
876
|
+
if n:
|
|
877
|
+
opts += argv[k:k + n]
|
|
878
|
+
else:
|
|
879
|
+
rest.append(a)
|
|
880
|
+
k += n or 1
|
|
881
|
+
rest += argv[k:]
|
|
882
|
+
if rest and rest[0].startswith("-") and rest[0] not in ("--", "--help", "-h"):
|
|
883
|
+
rest.insert(0, "--")
|
|
884
|
+
argv[i + 1:] = opts + rest
|
|
885
|
+
args = ap.parse_args(argv)
|
|
886
|
+
for k, v in (("json", False), ("budget", None), ("possible", False), ("untracked", False)):
|
|
887
|
+
if not hasattr(args, k):
|
|
888
|
+
setattr(args, k, v)
|
|
889
|
+
fn = {
|
|
890
|
+
"build": cmd_build, "check": cmd_check, "callers": cmd_callers,
|
|
891
|
+
"callees": lambda a: cmd_callers(a, reverse=False), "affected": cmd_affected, "path": cmd_path,
|
|
892
|
+
"show": cmd_show, "find": cmd_find, "unknown": cmd_unknown, "entries": cmd_entries,
|
|
893
|
+
"impact": cmd_impact, "approve": cmd_approve, "verify": cmd_verify, "hook": cmd_hook,
|
|
894
|
+
}[args.cmd]
|
|
895
|
+
try:
|
|
896
|
+
code = fn(args)
|
|
897
|
+
sys.stdout.flush()
|
|
898
|
+
return code
|
|
899
|
+
except BrokenPipeError: # `fmap ... | head`
|
|
900
|
+
sys.stdout = open(os.devnull, "w")
|
|
901
|
+
return 0
|
|
902
|
+
except KeyboardInterrupt: # Ctrl-C: context managers already removed the revision worktree
|
|
903
|
+
return 130
|
|
904
|
+
|
|
905
|
+
|
|
906
|
+
if __name__ == "__main__":
|
|
907
|
+
raise SystemExit(main())
|