featuregraph-cli 0.1.0__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.
@@ -0,0 +1,491 @@
1
+ """
2
+ featuregraph.core.annotator
3
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
4
+ Auto-suggest and optionally write `# @feature` tags for un-annotated
5
+ Python and TypeScript/JS symbols.
6
+
7
+ Strategy
8
+ --------
9
+ 1. Walk the workspace (same ignore rules as WorkspaceScanner).
10
+ 2. For each file, parse symbols that are NOT already tagged.
11
+ 3. Derive a stable feature ID from the file path + symbol name.
12
+ 4. Optionally write the tag as the line immediately before the def/class/export.
13
+
14
+ ID generation (deterministic)
15
+ Derives from file path + symbol name, NOT sequence order.
16
+ Two runs on the same codebase produce identical IDs.
17
+
18
+ Python:
19
+ path: featuregraph/core/scanner.py symbol: WorkspaceScanner
20
+ -> category "SCANNER" symbol slug "WORKSPACESCANNER" -> SCANNER-WORKSPACESCANNER
21
+
22
+ TypeScript/JS:
23
+ path: src/components/AuthButton.tsx symbol: AuthButton
24
+ -> category "AUTHBUTTON" symbol slug "AUTHBUTTON" -> AUTHBUTTON-AUTHBUTTON
25
+
26
+ Per-category dedup counter (SCHEMA-1, SCHEMA-2) increments only when the
27
+ same slug appears multiple times in the same category (same file, two
28
+ functions with identical names — rare but possible).
29
+ """
30
+
31
+ from __future__ import annotations
32
+
33
+ import ast
34
+ import os
35
+ import re
36
+ import sys
37
+ import tempfile
38
+ from pathlib import Path
39
+ from typing import NamedTuple
40
+
41
+ from . import lexmask
42
+ from .scanner import WorkspaceScanner
43
+
44
+ # ──────────────────────────────────────────────────────────────────────────────
45
+ # Types
46
+ # ──────────────────────────────────────────────────────────────────────────────
47
+
48
+ # @feature [ANNOTATOR-01] Suggestion
49
+ class Suggestion(NamedTuple):
50
+ file: Path
51
+ line: int # 1-indexed line *before which* the tag will be inserted
52
+ indent: str # leading whitespace of the decorated symbol
53
+ feature_id: str
54
+ name: str
55
+ symbol: str
56
+ lang: str # "python" | "typescript"
57
+
58
+
59
+ # ──────────────────────────────────────────────────────────────────────────────
60
+ # Helpers
61
+ # ──────────────────────────────────────────────────────────────────────────────
62
+
63
+ FEATURE_TAG_RE = re.compile(r"@feature\s+\[", re.IGNORECASE)
64
+ _SAFE_ID_RE = re.compile(r"[^A-Z0-9_]")
65
+
66
+
67
+ def _to_slug(text: str, max_len: int = 16) -> str:
68
+ """Convert arbitrary text to an UPPER_ALPHA_NUM slug."""
69
+ upper = text.upper()
70
+ slug = _SAFE_ID_RE.sub("_", upper).strip("_")
71
+ slug = re.sub(r"_+", "_", slug)
72
+ return slug[:max_len].strip("_")
73
+
74
+
75
+ def _category_from_path(rel_path: Path) -> str:
76
+ """Derive a feature category token from the file's module path."""
77
+ parts = rel_path.with_suffix("").parts # drop extension
78
+ # Ignore common top-level noise folders
79
+ skip = {"src", "app", "lib", "components", "pages", "views",
80
+ "featuregraph", "tests", "test", "__init__"}
81
+ meaningful = [p for p in parts if p.lower() not in skip]
82
+ token = meaningful[-1] if meaningful else parts[-1]
83
+ return _to_slug(token, 12)
84
+
85
+
86
+ def _human_name(symbol: str, rel_path: Path) -> str:
87
+ """Make a readable feature name from a camelCase/snake_case symbol."""
88
+ # CamelCase → words
89
+ name = re.sub(r"([a-z])([A-Z])", r"\1 \2", symbol)
90
+ # snake_case → words
91
+ name = name.replace("_", " ").strip()
92
+ # Capitalise first word only
93
+ return name.capitalize() or rel_path.stem.capitalize()
94
+
95
+
96
+ # ──────────────────────────────────────────────────────────────────────────────
97
+ # Python
98
+ # ──────────────────────────────────────────────────────────────────────────────
99
+
100
+ def _leading_indent(source_lines: list[str], lineno: int) -> str:
101
+ """Return the leading whitespace of the line at 1-indexed lineno."""
102
+ if 1 <= lineno <= len(source_lines):
103
+ line = source_lines[lineno - 1]
104
+ return line[: len(line) - len(line.lstrip())]
105
+ return ""
106
+
107
+
108
+ def _has_tag_above(
109
+ source_lines: list[str], comment_lines: list[str], lineno: int, lookahead: int = 6
110
+ ) -> bool:
111
+ """True if the contiguous comment block above lineno contains a @feature tag."""
112
+ for i in range(lineno - 2, max(-1, lineno - 2 - lookahead), -1):
113
+ if source_lines[i].strip() and not comment_lines[i].strip():
114
+ break # code line: tags above it belong to a previous symbol
115
+ if FEATURE_TAG_RE.search(comment_lines[i]):
116
+ return True
117
+ return False
118
+
119
+
120
+ def _lexer_lang(lang: str) -> str:
121
+ """Map annotator language names onto lexmask lexers."""
122
+ return "js" if lang == "typescript" else lang
123
+
124
+
125
+ def _next_feat_id(
126
+ used: dict[str, int],
127
+ cat: str,
128
+ slug: str,
129
+ reserved: set[str] | frozenset[str] = frozenset(),
130
+ ) -> str:
131
+ """Return a deterministic feature ID that never collides with an existing tag."""
132
+ counter = used.setdefault(f"{cat}:{slug}", 0) + 1
133
+ used[f"{cat}:{slug}"] = counter
134
+ if counter == 1:
135
+ feat_id = f"{cat.upper()}-{slug.upper()}"
136
+ else:
137
+ feat_id = f"{cat.upper()}-{slug.upper()}-{counter - 1:02d}"
138
+ while feat_id in reserved:
139
+ counter += 1
140
+ used[f"{cat}:{slug}"] = counter
141
+ feat_id = f"{cat.upper()}-{slug.upper()}-{counter - 1:02d}"
142
+ return feat_id
143
+
144
+
145
+ # @feature [ANNOTATOR-02] Suggest python
146
+ def suggest_python(
147
+ file_path: Path,
148
+ root: Path,
149
+ used_ids: dict[str, int],
150
+ reserved: set[str] | frozenset[str] = frozenset(),
151
+ ) -> list[Suggestion]:
152
+ """Return Suggestion objects for un-annotated Python symbols."""
153
+ try:
154
+ source = file_path.read_text(encoding="utf-8")
155
+ tree = ast.parse(source, filename=str(file_path))
156
+ except (SyntaxError, UnicodeDecodeError, ValueError):
157
+ return []
158
+
159
+ lines = source.splitlines()
160
+ comment_lines = lexmask.comment_only(source, "python").splitlines()
161
+ rel = file_path.relative_to(root)
162
+ results = []
163
+
164
+ for node in ast.walk(tree):
165
+ if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
166
+ continue
167
+
168
+ # Skip private / dunder helpers
169
+ name = getattr(node, "name", "")
170
+ if name.startswith("_") and not name.startswith("__") or name == "":
171
+ continue
172
+ if name.startswith("__") and name.endswith("__"):
173
+ continue # dunder methods
174
+
175
+ if _has_tag_above(lines, comment_lines, min([node.lineno] + [d.lineno for d in node.decorator_list])):
176
+ continue # already tagged
177
+
178
+ first_line = min([node.lineno] + [d.lineno for d in node.decorator_list])
179
+ cat = _category_from_path(rel)
180
+ slug = _to_slug(name)
181
+ feat_id = _next_feat_id(used_ids, cat, slug, reserved)
182
+ human = _human_name(name, rel)
183
+ indent = _leading_indent(lines, first_line)
184
+
185
+ results.append(Suggestion(
186
+ file=file_path,
187
+ line=first_line,
188
+ indent=indent,
189
+ feature_id=feat_id,
190
+ name=human,
191
+ symbol=name,
192
+ lang="python",
193
+ ))
194
+
195
+ # Sort so we insert from bottom to top (keeps line numbers valid)
196
+ results.sort(key=lambda s: s.line, reverse=True)
197
+ return results
198
+
199
+
200
+ # ──────────────────────────────────────────────────────────────────────────────
201
+ # TypeScript / JavaScript
202
+ # ──────────────────────────────────────────────────────────────────────────────
203
+
204
+ # Matches: export const/function/class Foo OR export default function Foo
205
+ _TS_EXPORT_RE = re.compile(
206
+ r"^(?P<indent>[ \t]*)export[ \t]+(?:default[ \t]+)?(?:const|function|class|async[ \t]+function)[ \t]+"
207
+ r"(?P<name>[A-Za-z_][A-Za-z0-9_]*)",
208
+ re.MULTILINE,
209
+ )
210
+
211
+
212
+ # @feature [ANNOTATOR-03] Suggest typescript
213
+ def suggest_typescript(
214
+ file_path: Path,
215
+ root: Path,
216
+ used_ids: dict[str, int],
217
+ reserved: set[str] | frozenset[str] = frozenset(),
218
+ ) -> list[Suggestion]:
219
+ """Return Suggestion objects for un-annotated TypeScript/JS exports."""
220
+ try:
221
+ content = file_path.read_text(encoding="utf-8")
222
+ except (UnicodeDecodeError, OSError):
223
+ return []
224
+
225
+ lines = content.splitlines()
226
+ code = lexmask.code_only(content, "js")
227
+ comment_lines = lexmask.comment_only(content, "js").splitlines()
228
+ rel = file_path.relative_to(root)
229
+ results = []
230
+
231
+ for match in _TS_EXPORT_RE.finditer(code):
232
+ # Compute 1-indexed line number of this match
233
+ lineno = code[: match.start()].count("\n") + 1
234
+ name = match.group("name")
235
+ indent = match.group("indent")
236
+
237
+ if _has_tag_above(lines, comment_lines, lineno, lookahead=4):
238
+ continue
239
+
240
+ cat = _category_from_path(rel)
241
+ slug = _to_slug(name)
242
+ feat_id = _next_feat_id(used_ids, cat, slug, reserved)
243
+ human = _human_name(name, rel)
244
+
245
+ results.append(Suggestion(
246
+ file=file_path,
247
+ line=lineno,
248
+ indent=indent,
249
+ feature_id=feat_id,
250
+ name=human,
251
+ symbol=name,
252
+ lang="typescript",
253
+ ))
254
+
255
+ results.sort(key=lambda s: s.line, reverse=True)
256
+ return results
257
+
258
+
259
+ # ──────────────────────────────────────────────────────────────────────────────
260
+ # Generic Multi-Language (Go, Rust, Java, C#, PHP, Ruby, Swift, Dart, Shell)
261
+ # ──────────────────────────────────────────────────────────────────────────────
262
+
263
+ _GENERIC_DECL_RE = re.compile(
264
+ r"^(?P<indent>[ \t]*)(?:(?:public|private|protected|static|async|fn|func|function|def|class|struct|interface|impl|enum|type)[ \t]+)+"
265
+ r"(?P<name>[A-Za-z_][A-Za-z0-9_]*)",
266
+ re.MULTILINE,
267
+ )
268
+
269
+
270
+ def suggest_generic(
271
+ file_path: Path,
272
+ root: Path,
273
+ used_ids: dict[str, int],
274
+ reserved: set[str] | frozenset[str] = frozenset(),
275
+ ) -> list[Suggestion]:
276
+ """Return Suggestion objects for un-annotated Go, Rust, Java, C#, PHP, Ruby, etc. symbols."""
277
+ try:
278
+ content = file_path.read_text(encoding="utf-8", errors="replace")
279
+ except (UnicodeDecodeError, OSError):
280
+ return []
281
+
282
+ lines = content.splitlines()
283
+ rel = file_path.relative_to(root)
284
+ results = []
285
+
286
+ ext = file_path.suffix.lower()
287
+ from .parser_generic import SUPPORTED_EXTENSIONS
288
+ lang = SUPPORTED_EXTENSIONS.get(ext, "generic")
289
+ code = lexmask.code_only(content, lang)
290
+ comment_lines = lexmask.comment_only(content, lang).splitlines()
291
+
292
+ for match in _GENERIC_DECL_RE.finditer(code):
293
+ lineno = code[: match.start()].count("\n") + 1
294
+ name = match.group("name")
295
+ indent = match.group("indent")
296
+
297
+ if _has_tag_above(lines, comment_lines, lineno, lookahead=4):
298
+ continue
299
+
300
+ cat = _category_from_path(rel)
301
+ slug = _to_slug(name)
302
+ feat_id = _next_feat_id(used_ids, cat, slug, reserved)
303
+ human = _human_name(name, rel)
304
+
305
+ results.append(Suggestion(
306
+ file=file_path,
307
+ line=lineno,
308
+ indent=indent,
309
+ feature_id=feat_id,
310
+ name=human,
311
+ symbol=name,
312
+ lang=lang,
313
+ ))
314
+
315
+ results.sort(key=lambda s: s.line, reverse=True)
316
+ return results
317
+
318
+
319
+ # ──────────────────────────────────────────────────────────────────────────────
320
+ # Writer
321
+ # ──────────────────────────────────────────────────────────────────────────────
322
+
323
+ def _comment_prefix(lang: str) -> str:
324
+ if lang in {"python", "ruby", "shell"}:
325
+ return "#"
326
+ return "//"
327
+
328
+
329
+ def _warn(message: str) -> None:
330
+ print(f"warning: {message}", file=sys.stderr)
331
+
332
+
333
+ def _atomic_write(file_path: Path, text: str) -> None:
334
+ """Replace *file_path* through a same-directory temp file so a crash cannot truncate it."""
335
+ tmp_path: Path | None = None
336
+ try:
337
+ with tempfile.NamedTemporaryFile(
338
+ "w", encoding="utf-8", dir=file_path.parent, delete=False
339
+ ) as handle:
340
+ handle.write(text)
341
+ tmp_path = Path(handle.name)
342
+ os.chmod(tmp_path, file_path.stat().st_mode)
343
+ os.replace(tmp_path, file_path)
344
+ tmp_path = None
345
+ finally:
346
+ if tmp_path is not None:
347
+ try:
348
+ tmp_path.unlink()
349
+ except OSError:
350
+ pass
351
+
352
+
353
+ def _feature_ids(file_path: Path) -> set:
354
+ """Return the feature IDs the scanner would see in this file right now."""
355
+ suffix = file_path.suffix.lower()
356
+ try:
357
+ if suffix == ".py":
358
+ from .parser_py import PythonFeatureParser
359
+ parsed = PythonFeatureParser.parse_file(file_path)
360
+ elif suffix in {".ts", ".tsx", ".js", ".jsx"}:
361
+ from .parser_ts import TypeScriptFeatureParser
362
+ parsed = TypeScriptFeatureParser.parse_file(file_path)
363
+ else:
364
+ from .parser_generic import GenericFeatureParser
365
+ parsed = GenericFeatureParser.parse_file(file_path)
366
+ except Exception:
367
+ return set()
368
+ return {f["feature_id"] for f in parsed}
369
+
370
+
371
+ # @feature [ANNOTATOR-04] Apply suggestions
372
+ def apply_suggestions(suggestions: list[Suggestion]) -> dict[Path, int]:
373
+ """
374
+ Write `# @feature` / `// @feature` tags into source files.
375
+
376
+ Inserts one line immediately before each suggested symbol. Suggestions
377
+ whose insertion point is not code are skipped, files are replaced
378
+ atomically, and every write is re-parsed: if a tag does not survive the
379
+ round trip the original file is restored.
380
+
381
+ Returns mapping of {file: count_written}.
382
+ """
383
+ # Group by file
384
+ by_file: dict[Path, list[Suggestion]] = {}
385
+ for s in suggestions:
386
+ by_file.setdefault(s.file, []).append(s)
387
+
388
+ written: dict[Path, int] = {}
389
+
390
+ for file_path, file_suggestions in by_file.items():
391
+ try:
392
+ original = file_path.read_text(encoding="utf-8")
393
+ except (OSError, UnicodeDecodeError):
394
+ continue
395
+
396
+ lines = original.splitlines(keepends=True)
397
+ starts = [0]
398
+ for line in lines:
399
+ starts.append(starts[-1] + len(line))
400
+ cls = lexmask.classify(original, _lexer_lang(file_suggestions[0].lang))
401
+
402
+ # Sort descending by line so we insert from bottom; avoids offset drift
403
+ file_suggestions.sort(key=lambda s: s.line, reverse=True)
404
+
405
+ count = 0
406
+ inserted = set()
407
+ for sg in file_suggestions:
408
+ insert_at = sg.line - 1 # 0-indexed
409
+ if not 0 <= insert_at < len(lines):
410
+ _warn(f"{file_path}:{sg.line}: skipped {sg.feature_id} (line out of range)")
411
+ continue
412
+ line = lines[insert_at]
413
+ lead = len(line) - len(line.lstrip())
414
+ pos = starts[insert_at] + lead
415
+ if line.strip() and (pos >= len(cls) or cls[pos] != lexmask.CODE):
416
+ _warn(f"{file_path}:{sg.line}: skipped {sg.feature_id} (insertion point is not code)")
417
+ continue
418
+ prefix = _comment_prefix(sg.lang)
419
+ tag_line = f"{sg.indent}{prefix} @feature [{sg.feature_id}] {sg.name}\n"
420
+ lines.insert(insert_at, tag_line)
421
+ inserted.add(sg.feature_id)
422
+ count += 1
423
+
424
+ if not count:
425
+ continue
426
+
427
+ before = _feature_ids(file_path)
428
+ try:
429
+ _atomic_write(file_path, "".join(lines))
430
+ except OSError as exc:
431
+ _warn(f"{file_path}: write failed ({exc}); file left unchanged")
432
+ continue
433
+
434
+ got = _feature_ids(file_path)
435
+ if not (inserted <= got <= before | inserted):
436
+ _atomic_write(file_path, original)
437
+ _warn(f"{file_path}: re-parse verification failed; restored original")
438
+ continue
439
+
440
+ written[file_path] = count
441
+
442
+ return written
443
+
444
+
445
+ # ──────────────────────────────────────────────────────────────────────────────
446
+ # Public API — orchestrator used by CLI
447
+ # ──────────────────────────────────────────────────────────────────────────────
448
+
449
+ # @feature [ANNOTATOR-05] Collect suggestions
450
+ def collect_suggestions(
451
+ root: Path,
452
+ extra_ignore: set | None = None,
453
+ ) -> list[Suggestion]:
454
+ """
455
+ Walk *root*, find all un-annotated Python/TS/JS symbols, return Suggestions.
456
+
457
+ File selection matches WorkspaceScanner: git repo file lists are used when
458
+ available (so .gitignore'd trees are skipped), and .featureignore is honoured.
459
+
460
+ IDs are derived deterministically from file path + symbol name so that two
461
+ runs on the same codebase produce the same IDs. Per-category dedup counters
462
+ increment only when identical slugs collide.
463
+
464
+ The returned list is ordered: Python files first, then TS/JS, both groups
465
+ sorted by (file, line) ascending — ready for pretty printing.
466
+ """
467
+ scanner = WorkspaceScanner(root)
468
+ scanner.ignore_patterns |= set(extra_ignore or set())
469
+ used_ids: dict[str, int] = {} # "cat:slug" -> count
470
+ reserved: set[str] = set()
471
+ for path_obj in scanner._source_files():
472
+ reserved |= _feature_ids(path_obj[0])
473
+ all_suggestions: list[Suggestion] = []
474
+
475
+ for path_obj in scanner.iter_files():
476
+ if path_obj.suffix == ".py":
477
+ sug = suggest_python(path_obj, root, used_ids, reserved)
478
+ sug.sort(key=lambda s: s.line)
479
+ all_suggestions.extend(sug)
480
+ elif path_obj.suffix in {".ts", ".tsx", ".js", ".jsx"}:
481
+ sug = suggest_typescript(path_obj, root, used_ids, reserved)
482
+ sug.sort(key=lambda s: s.line)
483
+ all_suggestions.extend(sug)
484
+ else:
485
+ from .parser_generic import GenericFeatureParser
486
+ if GenericFeatureParser.is_supported(path_obj):
487
+ sug = suggest_generic(path_obj, root, used_ids, reserved)
488
+ sug.sort(key=lambda s: s.line)
489
+ all_suggestions.extend(sug)
490
+
491
+ return all_suggestions