Repository navigation
Expand file tree
/
Copy pathdeep_report.py
More file actions
991 lines (853 loc) · 36.5 KB
/
Copy pathdeep_report.py
File metadata and controls
991 lines (853 loc) · 36.5 KB
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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
"""Deep analysis report generation based on deep_report_spec.md."""
from __future__ import annotations
import ast
import hashlib
import json
import mimetypes
import os
import re
from collections import defaultdict
from dataclasses import dataclass, field, asdict, fields
from pathlib import Path
from typing import Iterable, Optional
from report import ProjectReport, FileInfo
@dataclass
class DeepAnalysisOptions:
"""Toggles to control size/detail of deep analysis reports."""
include_functions: bool = True
include_classes: bool = True
include_api_index: bool = True
include_dependency_map: bool = True
include_call_graph: bool = True
include_cli_inventory: bool = True
include_config_schema: bool = True
include_ui_catalogue: bool = True
include_tests: bool = True
include_string_catalogue: bool = True
include_binary_manifest: bool = True
include_llm_bundle: bool = True
include_complexity_panel: bool = True
@classmethod
def from_dict(cls, data: dict[str, bool] | None) -> "DeepAnalysisOptions":
if not data:
return cls()
kwargs = {}
for f in fields(cls):
if f.name in data:
kwargs[f.name] = data[f.name]
else:
kwargs[f.name] = f.default
return cls(**kwargs)
@dataclass
class SignatureSummary:
"""Represents a function or class signature summary."""
name: str
signature: str
doc: str | None
decorators: list[str] = field(default_factory=list)
lineno: int | None = None
@dataclass
class DeepFileAnalysis:
"""Structured, non-recoverable view of a file."""
path: str
language: str
size_bytes: int
mtime_iso: str
sloc: int
todo_count: int
responsibility: str | None
constructs: dict[str, list[str]]
functions: list[SignatureSummary]
classes: list[SignatureSummary]
imports: list[str]
internal_imports: list[str]
external_imports: list[str]
call_targets: list[str]
env_vars: list[str]
config_keys: list[str]
cli_commands: list[str]
entrypoints: list[str]
ui_widgets: list[str]
tests: list[str]
strings: list[str]
licence: str | None
asset_meta: dict[str, str] | None
cyclomatic_complexity: int | None
complexity: str
risk_score: float | None
@dataclass
class APIItem:
"""Public API member for index."""
module: str
qualname: str
signature: str
kind: str
doc: str | None
@dataclass
class DeepAnalysisReport:
"""Aggregate report for an entire project."""
root: str
generated_at: str
files: list[DeepFileAnalysis]
api_index: list[APIItem]
dependency_map: dict[str, list[str]]
call_graph: dict[str, list[str]]
cli_inventory: list[dict[str, str]]
config_schema: dict[str, list[str]]
ui_catalogue: list[dict[str, str]]
test_map: dict[str, list[str]]
string_catalogue: dict[str, list[str]]
licence_findings: list[dict[str, str]]
binary_manifest: list[dict[str, str]]
llm_bundle: list[dict[str, object]]
def to_json(self) -> str:
"""Return a machine-readable JSON string."""
return json.dumps(asdict(self), ensure_ascii=False, indent=2)
class PythonAnalyzer(ast.NodeVisitor):
"""Collect per-file information for Python sources."""
def __init__(self, module_path: str) -> None:
self.module_path = module_path
self.docstring = None
self.functions: list[SignatureSummary] = []
self.classes: list[SignatureSummary] = []
self.imports: set[str] = set()
self.call_targets: set[str] = set()
self.env_vars: set[str] = set()
self.config_keys: set[str] = set()
self.cli_commands: set[str] = set()
self.entrypoints: set[str] = set()
self.ui_widgets: set[str] = set()
self.tests: set[str] = set()
self.todo_locations: int = 0
self._current_class: list[str] = []
def visit_Import(self, node: ast.Import) -> None: # noqa: D401 - part of NodeVisitor
for alias in node.names:
self.imports.add(alias.name)
self.generic_visit(node)
def visit_ImportFrom(self, node: ast.ImportFrom) -> None: # noqa: D401
module = node.module or ""
for alias in node.names:
if module:
self.imports.add(f"{module}.{alias.name}")
else:
self.imports.add(alias.name)
self.generic_visit(node)
def visit_Call(self, node: ast.Call) -> None: # noqa: D401
target = self._expr_to_name(node.func)
if target:
self.call_targets.add(target)
if target.endswith("ArgumentParser"):
self.cli_commands.add(target)
if target.endswith(("Tk", "CTk", "Frame", "Button", "Label")):
self.ui_widgets.add(target)
if target.endswith(("getenv", "environ.get")) and node.args:
key = self._extract_string(node.args[0])
if key:
self.env_vars.add(key)
self.visit_Call_keywords(node.keywords)
self.generic_visit(node)
def visit_Assign(self, node: ast.Assign) -> None: # noqa: D401
if isinstance(node.value, ast.Call):
target = self._expr_to_name(node.value.func)
if target and target.endswith("ArgumentParser"):
self.cli_commands.add(target)
self.generic_visit(node)
def _process_function(self, node: ast.FunctionDef | ast.AsyncFunctionDef) -> None:
"""Process both regular and async function definitions."""
qual = self._qualname(node.name)
signature = self._format_signature(node)
doc = ast.get_docstring(node)
summary = SignatureSummary(
name=qual,
signature=signature,
doc=_first_line(doc),
decorators=[self._expr_to_name(d) or "" for d in node.decorator_list if d],
lineno=node.lineno,
)
self.functions.append(summary)
if qual.startswith("test_") or "/tests/" in self.module_path.replace("\\", "/"):
self.tests.add(qual)
for stmt in node.body:
if isinstance(stmt, ast.If):
cond = ast.unparse(stmt.test) if hasattr(ast, "unparse") else None
if cond and "__name__" in cond and "__main__" in cond:
self.entrypoints.add(qual)
self.generic_visit(node)
def visit_FunctionDef(self, node: ast.FunctionDef) -> None: # noqa: D401
self._process_function(node)
def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> None: # noqa: D401
self._process_function(node)
def visit_ClassDef(self, node: ast.ClassDef) -> None: # noqa: D401
qual = self._qualname(node.name)
bases = [self._expr_to_name(base) or ast.unparse(base) for base in node.bases] if node.bases else []
signature = f"class {qual}({', '.join(bases)})"
doc = ast.get_docstring(node)
summary = SignatureSummary(
name=qual,
signature=signature,
doc=_first_line(doc),
decorators=[self._expr_to_name(d) or "" for d in node.decorator_list if d],
lineno=node.lineno,
)
self.classes.append(summary)
if any(base and "TestCase" in base for base in bases):
self.tests.add(qual)
self._current_class.append(node.name)
self.generic_visit(node)
self._current_class.pop()
def visit_If(self, node: ast.If) -> None: # noqa: D401
cond = ast.unparse(node.test) if hasattr(ast, "unparse") else None
if cond and "__name__" in cond and "__main__" in cond:
self.entrypoints.add(f"{self.module_path}::<module>")
self.generic_visit(node)
def visit_Subscript(self, node: ast.Subscript) -> None: # noqa: D401
target = self._expr_to_name(node.value)
if target in {"os.environ", "environ"}:
key = self._extract_string(node.slice)
if key:
self.env_vars.add(key)
self.generic_visit(node)
def visit_Call_keywords(self, keywords: Iterable[ast.keyword]) -> None:
for keyword in keywords:
if keyword.arg and "env" in keyword.arg.lower():
constant = self._extract_string(keyword.value)
if constant:
self.env_vars.add(constant)
def _qualname(self, name: str) -> str:
if self._current_class:
return ".".join(self._current_class + [name])
return name
def _expr_to_name(self, expr: ast.AST | None) -> str | None:
if expr is None:
return None
if isinstance(expr, ast.Name):
return expr.id
if isinstance(expr, ast.Attribute):
value = self._expr_to_name(expr.value)
return f"{value}.{expr.attr}" if value else expr.attr
if hasattr(ast, "unparse"):
try:
return ast.unparse(expr)
except Exception: # pragma: no cover - defensive
return None
return None
def _extract_string(self, node: ast.AST | None) -> str | None:
if node is None:
return None
if isinstance(node, ast.Constant) and isinstance(node.value, str):
return node.value
if isinstance(node, ast.Str): # py<3.8 compat
if isinstance(node.s, str):
return node.s
return None
def _format_signature(self, node: ast.AST) -> str:
if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
return getattr(node, "name", "<lambda>")
args = node.args
parts: list[str] = []
def format_arg(arg: ast.arg) -> str:
annotation = self._expr_to_name(arg.annotation) if getattr(arg, "annotation", None) else None
return f"{arg.arg}: {annotation}" if annotation else arg.arg
for arg in getattr(args, "posonlyargs", []):
parts.append(format_arg(arg))
if getattr(args, "posonlyargs", []):
parts.append("/")
for arg in args.args:
parts.append(format_arg(arg))
if args.vararg:
parts.append("*" + format_arg(args.vararg))
elif args.kwonlyargs:
parts.append("*")
for arg in args.kwonlyargs:
parts.append(format_arg(arg))
if args.kwarg:
parts.append("**" + format_arg(args.kwarg))
return f"{node.name}({', '.join(parts)})"
class RustAnalyzer:
"""Collect per-file information for Rust sources using regex-based parsing."""
def __init__(self, module_path: str) -> None:
self.module_path = module_path
self.functions: list[SignatureSummary] = []
self.classes: list[SignatureSummary] = [] # structs, enums, traits
self.imports: set[str] = set()
self.call_targets: set[str] = set()
self.env_vars: set[str] = set()
self.config_keys: set[str] = set()
self.cli_commands: set[str] = set()
self.entrypoints: set[str] = set()
self.ui_widgets: set[str] = set()
self.tests: set[str] = set()
def analyze(self, content: str) -> None:
"""Analyse Rust source content."""
self._extract_imports(content)
self._extract_structs(content)
self._extract_enums(content)
self._extract_traits(content)
self._extract_functions(content)
self._extract_env_vars(content)
self._detect_cli(content)
self._detect_entrypoints(content)
def _extract_imports(self, content: str) -> None:
"""Extract use statements and extern crate declarations."""
# Standard use statements
use_pattern = re.compile(r'^use\s+([\w:]+(?:::\{[^}]+\})?);', re.MULTILINE)
for match in use_pattern.finditer(content):
self.imports.add(match.group(1))
# extern crate declarations
extern_pattern = re.compile(r'^extern\s+crate\s+(\w+);', re.MULTILINE)
for match in extern_pattern.finditer(content):
self.imports.add(match.group(1))
def _extract_structs(self, content: str) -> None:
"""Extract struct definitions."""
struct_pattern = re.compile(
r'(?:///\s*(.+?)\n)?' # Optional doc comment
r'(?:#\[[^\]]+\]\n)*' # Optional attributes
r'(?:pub\s*(?:\([^)]+\)\s*)?)?struct\s+(\w+)(?:<[^>]+>)?',
re.MULTILINE
)
for match in struct_pattern.finditer(content):
doc = match.group(1)
name = match.group(2)
self.classes.append(SignatureSummary(
name=name,
signature=f"struct {name}",
doc=doc.strip() if doc else None,
lineno=content[:match.start()].count('\n') + 1
))
def _extract_enums(self, content: str) -> None:
"""Extract enum definitions."""
enum_pattern = re.compile(
r'(?:///\s*(.+?)\n)?'
r'(?:#\[[^\]]+\]\n)*'
r'(?:pub\s*(?:\([^)]+\)\s*)?)?enum\s+(\w+)(?:<[^>]+>)?',
re.MULTILINE
)
for match in enum_pattern.finditer(content):
doc = match.group(1)
name = match.group(2)
self.classes.append(SignatureSummary(
name=name,
signature=f"enum {name}",
doc=doc.strip() if doc else None,
lineno=content[:match.start()].count('\n') + 1
))
def _extract_traits(self, content: str) -> None:
"""Extract trait definitions."""
trait_pattern = re.compile(
r'(?:///\s*(.+?)\n)?'
r'(?:#\[[^\]]+\]\n)*'
r'(?:pub\s*(?:\([^)]+\)\s*)?)?trait\s+(\w+)(?:<[^>]+>)?',
re.MULTILINE
)
for match in trait_pattern.finditer(content):
doc = match.group(1)
name = match.group(2)
self.classes.append(SignatureSummary(
name=name,
signature=f"trait {name}",
doc=doc.strip() if doc else None,
lineno=content[:match.start()].count('\n') + 1
))
def _extract_functions(self, content: str) -> None:
"""Extract function definitions."""
fn_pattern = re.compile(
r'(?:///\s*(.+?)\n)?' # Optional doc comment
r'(?:#\[([^\]]+)\]\n)*' # Optional attributes (capture for test detection)
r'(?:pub\s*(?:\([^)]+\)\s*)?)?' # Optional visibility
r'(?:async\s+)?' # Optional async
r'(?:unsafe\s+)?' # Optional unsafe
r'(?:extern\s+"[^"]+"\s+)?' # Optional extern
r'fn\s+(\w+)\s*' # Function name
r'(?:<[^>]+>)?\s*' # Optional generics
r'\(([^)]*)\)\s*' # Parameters
r'(?:->\s*([^\{;]+))?', # Optional return type
re.MULTILINE | re.DOTALL
)
for match in fn_pattern.finditer(content):
doc = match.group(1)
attrs = match.group(2) or ""
name = match.group(3)
params = match.group(4)
returns = match.group(5)
signature = f"fn {name}({params.strip()})"
if returns:
signature += f" -> {returns.strip()}"
self.functions.append(SignatureSummary(
name=name,
signature=signature,
doc=doc.strip() if doc else None,
decorators=[f"#[{attrs}]"] if attrs else [],
lineno=content[:match.start()].count('\n') + 1
))
# Detect test functions
preceding = content[max(0, match.start() - 100):match.start()]
if '#[test]' in preceding or '#[cfg(test)]' in preceding or name.startswith('test_'):
self.tests.add(name)
# Detect main function as entrypoint
if name == 'main':
self.entrypoints.add('main')
def _extract_env_vars(self, content: str) -> None:
"""Extract environment variable usage."""
# std::env::var patterns
env_pattern = re.compile(r'env::var\s*\(\s*["\']([^"\']+)["\']\s*\)')
for match in env_pattern.finditer(content):
self.env_vars.add(match.group(1))
# std::env::var_os patterns
env_os_pattern = re.compile(r'env::var_os\s*\(\s*["\']([^"\']+)["\']\s*\)')
for match in env_os_pattern.finditer(content):
self.env_vars.add(match.group(1))
def _detect_cli(self, content: str) -> None:
"""Detect CLI-related patterns."""
# clap usage
if 'use clap' in content or 'clap::' in content:
self.cli_commands.add('clap')
if 'structopt' in content:
self.cli_commands.add('structopt')
if 'argh' in content:
self.cli_commands.add('argh')
def _detect_entrypoints(self, content: str) -> None:
"""Detect additional entrypoints beyond main."""
# tokio main
if '#[tokio::main]' in content:
self.entrypoints.add('tokio::main')
# actix main
if '#[actix_web::main]' in content or '#[actix_rt::main]' in content:
self.entrypoints.add('actix::main')
def _first_line(text: str | None) -> str | None:
if not text:
return None
for line in text.strip().splitlines():
if line.strip():
return line.strip()
return None
TODO_PATTERN = re.compile(r"\b(TODO|FIXME|XXX)\b", re.IGNORECASE)
def _language_for_path(path: Path) -> str:
from analysis.languages import LANGUAGE_MAP, detect_language
ext = path.suffix.lower()
lang = detect_language(str(path))
if lang != "unknown":
return lang.capitalize()
if ext in {".yml", ".yaml"}:
return "YAML"
if ext in {".json"}:
return "JSON"
if ext in {".md", ".markdown"}:
return "Markdown"
if ext in {".ini", ".cfg", ".conf"}:
return "Config"
if ext in {".html", ".htm"}:
return "HTML"
if ext in {".css"}:
return "CSS"
if ext in {".toml"}:
return "TOML"
if ext in {".jpg", ".jpeg", ".png", ".gif", ".svg"}:
return "Image"
if ext in {".mp3", ".wav", ".flac"}:
return "Audio"
if ext in {".mp4", ".mov", ".avi"}:
return "Video"
return ext.lstrip(".") or "file"
def _compute_sloc(contents: str) -> int:
return sum(1 for line in contents.splitlines() if line.strip())
def _count_todos(contents: str) -> int:
return len(TODO_PATTERN.findall(contents))
def _compute_complexity(node: ast.AST) -> int:
class ComplexityVisitor(ast.NodeVisitor):
score = 1
def generic_visit(self, node: ast.AST) -> None: # noqa: D401
if isinstance(node, (ast.If, ast.For, ast.While, ast.And, ast.Or, ast.Try, ast.BoolOp, ast.With)):
self.score += 1
super().generic_visit(node)
visitor = ComplexityVisitor()
visitor.visit(node)
return visitor.score
def _risk_band(complexity: int, sloc: int, todo: int) -> tuple[str, float]:
base = complexity + sloc / 200 + todo * 0.5
if base < 5:
return "low", base
if base < 15:
return "medium", base
return "high", base
def _responsibility_hint(path: Path, contents: str) -> str | None:
lower = contents.lower()
name = path.stem.lower()
ext = path.suffix.lower()
if "tkinter" in lower or "customtkinter" in lower:
return "GUI layer"
if "argparse" in lower or "click" in lower:
return "CLI or entrypoint"
if "class " in contents and "test" in path.name.lower():
return "Tests"
if ext == ".rs":
if name == "main":
return "Entry point"
if name == "lib":
return "Library root"
if name == "mod":
return "Module definition"
if "error" in name:
return "Error types"
if "#[test]" in contents or "tests" in str(path.parts):
return "Tests"
if "clap" in lower or "structopt" in lower or "argh" in lower:
return "CLI or entrypoint"
if "serde" in lower and ("struct" in contents or "enum" in contents):
return "Data models"
if "trait " in contents and "impl " not in contents:
return "Trait definitions"
if "actix" in lower or "axum" in lower or "rocket" in lower:
return "Web handlers"
if "tokio" in lower or "async_std" in lower:
return "Async runtime"
if ext in {".js", ".jsx", ".ts", ".tsx"}:
if "reactdom.render" in lower or "createroot" in lower:
return "React entry point"
if "express()" in lower or "app.listen" in lower:
return "Web server"
if "next" in lower and "getstaticprops" in lower:
return "Next.js page"
if name == "index":
return "Module entry point"
if "test" in path.name.lower() or "spec" in path.name.lower():
return "Tests"
if "component" in lower or "usestate" in lower or "useeffect" in lower:
return "React component"
if "redux" in lower or "createstore" in lower:
return "State management"
if ext == ".go":
if name == "main" and "func main()" in contents:
return "Entry point"
if "http.handlefunc" in lower or "http.listenandserve" in lower:
return "HTTP server"
if "gin" in lower or "echo" in lower or "fiber" in lower:
return "Web framework"
if "_test.go" in str(path):
return "Tests"
if "grpc" in lower:
return "gRPC service"
if ext == ".java":
if "public static void main" in contents:
return "Entry point"
if "@controller" in lower or "@restcontroller" in lower:
return "Web controller"
if "@service" in lower:
return "Service layer"
if "@repository" in lower or "@dao" in lower:
return "Data access layer"
if "@entity" in lower or "@table" in lower:
return "Entity model"
if "test" in path.name.lower() and "@test" in lower:
return "Tests"
if ext in {".kt", ".kts"}:
if "fun main(" in contents:
return "Entry point"
if "@controller" in lower or "@restcontroller" in lower:
return "Web controller"
if "@composable" in lower:
return "Jetpack Compose UI"
if "@entity" in lower:
return "Entity model"
if ext in {".c", ".h", ".cpp", ".hpp", ".cc", ".cxx"}:
if "int main(" in contents:
return "Entry point"
if ext == ".h" or ext == ".hpp":
return "Header file"
if "#include" in contents and "test" in path.name.lower():
return "Tests"
if ext == ".cs":
if "static void Main(" in contents or "static async Task Main(" in contents:
return "Entry point"
if "[testmethod]" in lower or "[test]" in lower or "[fact]" in lower:
return "Tests"
if "controller" in lower and "class " in contents:
return "Web controller"
if "async" in lower and "task" in lower:
return "Async service"
if ext == ".rb":
if "__FILE__ == $0" in contents or "__FILE__ == $PROGRAM_NAME" in contents:
return "Entry point"
if "rspec" in lower or "minitest" in lower:
return "Tests"
if "class " in contents and "controller" in lower:
return "Web controller"
if "activerecord" in lower or "applicationrecord" in lower:
return "ActiveRecord model"
if ext == ".php":
if "phpinfo()" in contents:
return "Entry point"
if "class " in contents and "controller" in lower:
return "Web controller"
if "phpunit" in lower or "testcase" in lower:
return "Tests"
if "eloquent" in lower or "model" in lower:
return "Data model"
if ext == ".swift":
if "@main" in contents or "UIApplicationMain" in contents:
return "Entry point"
if "xctestcase" in lower:
return "Tests"
if "viewcontroller" in lower:
return "View controller"
if "swiftui" in lower or "@viewbuilder" in lower:
return "SwiftUI view"
if "config" in path.parts:
return "Configuration"
if "model" in lower and ("class" in contents or "struct" in contents):
return "Domain model"
return None
def _detect_strings(node: ast.AST) -> set[str]:
strings: set[str] = set()
class StringsVisitor(ast.NodeVisitor):
def visit_Constant(self, constant: ast.Constant) -> None: # noqa: D401
if isinstance(constant.value, str):
value = constant.value.strip()
if 0 < len(value) <= 200 and "\n" not in value:
strings.add(value)
StringsVisitor().visit(node)
return strings
def build_deep_analysis(
report: ProjectReport,
root_path: Path,
options: DeepAnalysisOptions | None = None,
) -> DeepAnalysisReport:
"""Generate a deep analysis report compliant with the specification."""
options = options or DeepAnalysisOptions()
files: list[DeepFileAnalysis] = []
api_index: list[APIItem] = []
dependency_map: dict[str, list[str]] = {}
call_graph: dict[str, list[str]] = {}
cli_inventory: list[dict[str, str]] = []
config_schema: dict[str, list[str]] = defaultdict(list)
ui_catalogue: list[dict[str, str]] = []
test_map: dict[str, list[str]] = defaultdict(list)
string_catalogue: dict[str, list[str]] = defaultdict(list)
licence_findings: list[dict[str, str]] = []
binary_manifest: list[dict[str, str]] = []
llm_bundle: list[dict[str, object]] = []
internal_modules = _derive_internal_modules(report.files)
for info in report.files:
path = Path(root_path) / info.path
language = _language_for_path(path)
text: str | None = None
try:
if language.lower() not in {"image", "audio", "video"}:
text = path.read_text(encoding="utf-8", errors="ignore")
except Exception:
text = None
sloc = _compute_sloc(text) if text else 0
todo_count = _count_todos(text) if text else 0
responsibility = _responsibility_hint(path, text or "")
constructs: dict[str, list[str]] = defaultdict(list)
functions: list[SignatureSummary] = []
classes: list[SignatureSummary] = []
imports: set[str] = set()
internal_imports: set[str] = set()
external_imports: set[str] = set()
call_targets: set[str] = set()
env_vars: set[str] = set()
config_keys: set[str] = set()
cli_commands: set[str] = set()
entrypoints: set[str] = set()
ui_widgets: set[str] = set()
tests: set[str] = set()
strings: set[str] = set()
licence: str | None = None
asset_meta: dict[str, str] | None = None
complexity_score: int | None = None
if text is not None:
from analysis.languages import detect_language, get_analyzer
lang_key = detect_language(info.path)
lang_analyzer = get_analyzer(lang_key, info.path.replace(os.sep, "/"))
if lang_analyzer is not None:
try:
result = lang_analyzer.analyze(text)
functions = result.functions
classes = result.classes
imports = result.imports
call_targets = result.call_targets
env_vars = result.env_vars
cli_commands = result.cli_commands
entrypoints = result.entrypoints
ui_widgets = result.ui_widgets
tests = result.tests
strings = result.strings
if result.module_doc:
constructs["docstring"] = [result.module_doc]
if result.sections:
constructs["sections"] = result.sections
if options.include_api_index:
for summary in functions:
api_index.append(
APIItem(
module=info.path,
qualname=summary.name,
signature=summary.signature,
kind="function",
doc=summary.doc,
)
)
for summary in classes:
kind = "class"
sig_lower = summary.signature.lower()
if sig_lower.startswith("struct"):
kind = "struct"
elif sig_lower.startswith("enum"):
kind = "enum"
elif sig_lower.startswith("trait") or sig_lower.startswith("interface") or sig_lower.startswith("protocol"):
kind = "interface"
elif sig_lower.startswith("type"):
kind = "type"
elif sig_lower.startswith("object"):
kind = "object"
elif sig_lower.startswith("module"):
kind = "module"
api_index.append(
APIItem(
module=info.path,
qualname=summary.name,
signature=summary.signature,
kind=kind,
doc=summary.doc,
)
)
if options.include_complexity_panel:
complexity_score = result.complexity_score
if options.include_tests:
for test in tests:
test_map[info.path].append(test)
if options.include_ui_catalogue:
for widget in ui_widgets:
ui_catalogue.append({"file": info.path, "widget": widget})
if options.include_config_schema:
for ev in env_vars:
config_schema['environment'].append(ev)
if options.include_cli_inventory:
for command in cli_commands:
cli_inventory.append({"file": info.path, "command": command})
if options.include_string_catalogue:
strings = {s for s in strings if len(s) < 160}
for s in strings:
string_catalogue[s].append(info.path)
except Exception:
responsibility = responsibility or f"Unparseable {lang_key} file"
elif options.include_string_catalogue:
strings = {line.strip() for line in text.splitlines() if line.strip() and len(line.strip()) < 120}
for s in strings:
string_catalogue[s].append(info.path)
else:
strings = set()
if options.include_config_schema and text and path.suffix.lower() in {".json", ".yaml", ".yml", ".toml", ".ini", ".cfg"}:
key_pattern = re.compile(r"[\"']([A-Za-z0-9_.-]+)[\"']\s*[:=]")
keys = sorted(set(key_pattern.findall(text)))
if keys:
config_keys.update(keys)
config_schema[path.suffix.lower()].extend(f"{info.path}:{key}" for key in keys)
if imports:
for item in imports:
namespace = item.split(".")[0]
if namespace in internal_modules:
internal_imports.add(namespace)
else:
external_imports.add(namespace)
if options.include_dependency_map:
dependency_map[info.path] = sorted({imp.split(".")[0] for imp in imports})
if options.include_call_graph:
call_graph[info.path] = sorted(call_targets)
if text:
top_lines = "\n".join(text.splitlines()[:20]).lower()
if "license" in top_lines or "copyright" in top_lines:
licence = "Possible licence header"
mimetype, _ = mimetypes.guess_type(path.name)
if options.include_binary_manifest and mimetype and not mimetype.startswith("text"):
asset_meta = {
"path": info.path,
"mime": mimetype,
"size": f"{info.size_bytes} bytes",
}
binary_manifest.append(asset_meta)
if complexity_score is not None:
risk, risk_score = _risk_band(complexity_score, sloc, todo_count)
else:
risk, risk_score = "not-computed", None
file_card = DeepFileAnalysis(
path=info.path,
language=language,
size_bytes=info.size_bytes,
mtime_iso=info.mtime_iso,
sloc=sloc,
todo_count=todo_count,
responsibility=responsibility,
constructs={k: v for k, v in constructs.items() if v},
functions=functions if options.include_functions else [],
classes=classes if options.include_classes else [],
imports=sorted(imports),
internal_imports=sorted(internal_imports),
external_imports=sorted(external_imports),
call_targets=sorted(call_targets),
env_vars=sorted(env_vars),
config_keys=sorted(config_keys) if options.include_config_schema else [],
cli_commands=sorted(cli_commands) if options.include_cli_inventory else [],
entrypoints=sorted(entrypoints),
ui_widgets=sorted(ui_widgets) if options.include_ui_catalogue else [],
tests=sorted(tests) if options.include_tests else [],
strings=sorted(strings) if options.include_string_catalogue else [],
licence=licence,
asset_meta=asset_meta,
cyclomatic_complexity=complexity_score,
complexity=risk,
risk_score=risk_score,
)
files.append(file_card)
if options.include_llm_bundle:
llm_bundle.append(
{
"path": info.path,
"hash": hashlib.sha256(info.path.encode()).hexdigest()[:16],
"language": language,
"sloc": sloc,
"todo_count": todo_count,
"imports": sorted(imports),
"complexity_band": risk if risk_score is not None else None,
"cyclomatic_complexity": complexity_score,
"functions": [summary.signature for summary in functions] if options.include_functions else [],
"classes": [summary.signature for summary in classes] if options.include_classes else [],
"doc": file_card.constructs.get("docstring", [None])[0],
}
)
if licence:
licence_findings.append({"file": info.path, "note": licence})
normalized_config_schema = (
{key: sorted(set(values)) for key, values in config_schema.items()} if options.include_config_schema else {}
)
normalized_test_map = {key: sorted(values) for key, values in test_map.items()} if options.include_tests else {}
normalized_string_catalogue = (
{key: sorted(set(values)) for key, values in string_catalogue.items()} if options.include_string_catalogue else {}
)
return DeepAnalysisReport(
root=report.root,
generated_at=report.generated_at,
files=files,
api_index=api_index,
dependency_map=dependency_map if options.include_dependency_map else {},
call_graph=call_graph if options.include_call_graph else {},
cli_inventory=cli_inventory if options.include_cli_inventory else [],
config_schema=normalized_config_schema,
ui_catalogue=ui_catalogue if options.include_ui_catalogue else [],
test_map=normalized_test_map,
string_catalogue=normalized_string_catalogue,
licence_findings=licence_findings,
binary_manifest=binary_manifest if options.include_binary_manifest else [],
llm_bundle=llm_bundle if options.include_llm_bundle else [],
)
def _derive_internal_modules(files: list[FileInfo]) -> set[str]:
modules = set()
for fi in files:
path = Path(fi.path)
ext = path.suffix.lower()
if ext in {".py", ".rs", ".go", ".java", ".kt", ".cs", ".rb", ".php", ".swift", ".js", ".ts"}:
parts = path.parts
if len(parts) > 1:
modules.add(parts[0])
modules.add(path.stem)
return modules