-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcli_analysis.py
More file actions
359 lines (284 loc) · 12.5 KB
/
Copy pathcli_analysis.py
File metadata and controls
359 lines (284 loc) · 12.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
"""Analysis execution — chunked, streaming, and standard analysis flows.
Extracted from cli.py to isolate analysis orchestration from CLI parsing.
"""
import sys
from pathlib import Path
def _run_analysis(args, source_path: Path, output_dir: Path):
"""Run code analysis with configured strategy.
Returns AnalysisResult or exits on error.
For large repos, may analyze in chunks and merge results.
"""
from .core.large_repo import should_use_chunking
# --no-chunk explicitly disables chunking
use_chunking = not args.no_chunk and (
args.chunk or should_use_chunking(source_path, args.chunk_size)
)
if use_chunking:
if args.verbose:
print("Large repository detected - using chunked analysis")
args.chunk = True
return _run_chunked_analysis(args, source_path, output_dir)
return _run_standard_analysis(args, source_path, output_dir)
def _run_standard_analysis(args, source_path: Path, output_dir: Path):
"""Standard single-project analysis flow."""
from .core.analyzer import ProjectAnalyzer
config = _build_config(args, output_dir)
try:
if args.streaming or args.strategy in ["quick", "deep"]:
result = _run_streaming_analysis(args, config, source_path)
else:
analyzer = ProjectAnalyzer(config, source_path)
result = analyzer.analyze_project(str(source_path))
if args.verbose:
_print_analysis_summary(result)
return result
except Exception as e:
print(f"Error during analysis: {e}", file=sys.stderr)
sys.exit(1)
def _apply_exclude_patterns(filter_config, args) -> None:
"""Merge CLI --exclude globs into filter_config.exclude_patterns."""
if not (hasattr(args, "exclude") and args.exclude):
return
custom = [
f"*{p}*" if not p.startswith("*") and not p.endswith("*") else p
for p in args.exclude
]
filter_config.exclude_patterns = list(set(filter_config.exclude_patterns + custom))
def _apply_strategy_config(config, args) -> None:
"""Apply --fast flag and --strategy overrides to config.performance."""
if getattr(args, "fast", False):
config.performance.fast_mode = True
config.performance.apply_fast_mode()
if getattr(args, "strategy", "standard") == "quick":
config.performance.skip_data_flow = True
config.performance.skip_dead_code_detection = True
config.performance.skip_centrality = True
config.performance.skip_community_detection = True
def _build_config(args, output_dir: Path):
"""Build analysis Config from CLI args."""
from .core.config import Config, FilterConfig
filter_config = FilterConfig()
_apply_exclude_patterns(filter_config, args)
if hasattr(args, "no_gitignore") and args.no_gitignore:
filter_config.gitignore_enabled = False
config = Config(
mode=args.mode,
max_depth_enumeration=args.max_depth,
detect_state_machines=not args.no_patterns,
detect_recursion=not args.no_patterns,
output_dir=str(output_dir),
filters=filter_config,
)
config.no_cache = getattr(args, "no_cache", False) or getattr(args, "force", False)
config.watch = getattr(args, "watch", False)
config.dry_run = getattr(args, "dry_run", False)
_apply_strategy_config(config, args)
return config
def _print_analysis_summary(result) -> None:
"""Print analysis completion summary."""
print("\nAnalysis complete:")
print(f" - Functions: {len(result.functions)}")
print(f" - Classes: {len(result.classes)}")
print(f" - CFG nodes: {len(result.nodes)}")
print(f" - CFG edges: {len(result.edges)}")
# ------------------------------------------------------------------
# Chunked analysis
# ------------------------------------------------------------------
def _run_chunked_analysis(args, source_path: Path, output_dir: Path):
"""Analyze large repository using hierarchical chunking.
Strategy:
1. Level 1 folders first
2. If >256KB, split to level 2 subfolders
3. If still too big, use file chunking
"""
from .core.large_repo import HierarchicalRepoSplitter
splitter = HierarchicalRepoSplitter(
size_limit_kb=args.chunk_size, max_files_per_chunk=args.max_files_per_chunk
)
subprojects = splitter.get_analysis_plan(source_path)
if args.verbose:
_print_chunked_plan(subprojects)
subprojects = _filter_subprojects(args, subprojects)
all_results = _analyze_all_subprojects(args, subprojects, output_dir)
merged_result = _merge_chunked_results(all_results, source_path)
if args.verbose:
print("\nChunked analysis complete:")
print(f" - Chunks analyzed: {len(all_results)}")
print(f" - Total functions: {len(merged_result.functions)}")
print(f" - Total classes: {len(merged_result.classes)}")
return merged_result
def _print_chunked_plan(subprojects) -> None:
"""Print hierarchical analysis plan summary."""
print(f"Hierarchical analysis plan ({len(subprojects)} chunks):")
level_counts = {}
for sp in subprojects:
level_counts[sp.level] = level_counts.get(sp.level, 0) + 1
for level in sorted(level_counts.keys()):
level_name = {0: "root", 1: "level-1", 2: "level-2", 3: "file-chunks"}.get(
level, f"level-{level}"
)
print(f" {level_name}: {level_counts[level]} chunks")
print("\nChunks:")
for sp in subprojects:
level_indicator = " " * sp.level
size_info = f"~{sp.estimated_size_kb}KB"
print(f"{level_indicator}{sp.name}: {sp.file_count} files ({size_info})")
def _filter_subprojects(args, subprojects) -> list:
"""Apply --only-subproject and --skip-subprojects filters."""
if args.only_subproject:
subprojects = [
sp
for sp in subprojects
if sp.name == args.only_subproject
or sp.name.startswith(args.only_subproject + ".")
]
if not subprojects:
print(
f"Error: Subproject '{args.only_subproject}' not found", file=sys.stderr
)
sys.exit(1)
if args.skip_subprojects:
subprojects = [
sp
for sp in subprojects
if not any(sp.name.startswith(skip) for skip in args.skip_subprojects)
]
return subprojects
def _analyze_all_subprojects(args, subprojects, output_dir: Path) -> list:
"""Analyze each subproject and collect results."""
all_results = []
for i, subproject in enumerate(subprojects, 1):
if args.verbose:
level_name = {0: "root", 1: "L1", 2: "L2", 3: "chunk"}.get(
subproject.level, f"L{subproject.level}"
)
print(
f"\n[{i}/{len(subprojects)}] Analyzing [{level_name}]: {subproject.name}"
)
sp_output_dir = output_dir / subproject.name.replace(".", "_")
sp_output_dir.mkdir(parents=True, exist_ok=True)
result = _analyze_subproject(args, subproject, sp_output_dir)
if result:
all_results.append((subproject.name, result, sp_output_dir))
return all_results
def _build_filter_config(args):
"""Build a FilterConfig from CLI args (exclude patterns, gitignore flag)."""
from .core.config import FilterConfig
fc = FilterConfig()
if getattr(args, "exclude", None):
custom = [
f"*{p}*" if not p.startswith("*") and not p.endswith("*") else p
for p in args.exclude
]
fc.exclude_patterns = list(set(fc.exclude_patterns + custom))
if getattr(args, "no_gitignore", False):
fc.gitignore_enabled = False
return fc
def _analyze_subproject(args, subproject, output_dir: Path):
"""Analyze and export a single subproject."""
from .core.analyzer import ProjectAnalyzer
from .core.config import Config
from .cli_exports import _export_simple_formats, _export_evolution
filter_config = _build_filter_config(args)
config = Config(
mode=args.mode,
max_depth_enumeration=args.max_depth,
detect_state_machines=not args.no_patterns,
detect_recursion=not args.no_patterns,
output_dir=str(output_dir),
verbose=args.verbose,
filters=filter_config,
)
analyzer = ProjectAnalyzer(config, subproject.path)
try:
result = analyzer.analyze_project(str(subproject.path))
formats = [f.strip() for f in args.format.split(",")]
if "all" in formats:
formats = ["toon", "context", "evolution"]
_export_simple_formats(args, result, output_dir, formats)
if "evolution" in formats or "all" in formats:
_export_evolution(args, result, output_dir)
if args.verbose:
print(
f" ✓ Exported {subproject.name}: {len(result.functions)} functions"
)
return result
except Exception as e:
print(f"Warning: Failed to analyze {subproject.name}: {e}", file=sys.stderr)
return None
def _merge_item_dict(src: dict, seen: set, prefix: str, dst: dict) -> None:
"""Copy items from src into dst, deduplicating by (file, name) key."""
for item_name, info in src.items():
key = (info.file, info.name)
if key in seen:
continue
seen.add(key)
dst[f"{prefix}{item_name}" if "." not in item_name else item_name] = info
def _merge_chunked_results(all_results, source_path: Path):
"""Merge results from multiple subproject analyses."""
from .core.models import AnalysisResult
merged = AnalysisResult(project_path=str(source_path))
# Track seen (file, simple_name) pairs to deduplicate overlapping chunk scopes.
# When the splitter assigns the same directory to multiple chunks (e.g. root and
# batch_1 both point at the project root), the same class/function would otherwise
# appear multiple times in the merged result and trigger false-positive duplicate
# detection in the TOON exporter.
seen_funcs: set = set()
seen_classes: set = set()
seen_modules: set = set()
for name, result, output_dir in all_results:
if not result:
continue
prefix = f"{name}."
_merge_item_dict(result.functions, seen_funcs, prefix, merged.functions)
_merge_item_dict(result.classes, seen_classes, prefix, merged.classes)
_merge_item_dict(result.modules, seen_modules, prefix, merged.modules)
merged.nodes.update(result.nodes)
merged.edges.extend(result.edges)
return merged
# ------------------------------------------------------------------
# Streaming analysis
# ------------------------------------------------------------------
def _run_streaming_analysis(args, config, source_path: Path):
"""Run streaming analysis with progress reporting and return accumulated results."""
from .core.analyzer import ProjectAnalyzer
from .core.streaming_analyzer import (
StreamingAnalyzer,
STRATEGY_QUICK,
STRATEGY_STANDARD,
STRATEGY_DEEP,
)
strategy_map = {
"quick": STRATEGY_QUICK,
"standard": STRATEGY_STANDARD,
"deep": STRATEGY_DEEP,
}
strategy = strategy_map.get(args.strategy, STRATEGY_STANDARD)
strategy.max_files_in_memory = min(
strategy.max_files_in_memory, args.max_memory // 10
)
analyzer = StreamingAnalyzer(config, strategy)
if args.verbose:
def on_progress(update):
"""Print a progress percentage line in-place."""
pct = update.get("percentage", 0)
print(f"\r[{pct:.0f}%] {update.get('message', '')}", end="", flush=True)
analyzer.set_progress_callback(on_progress)
print(f"Analyzing with {args.strategy} strategy...")
# Accumulate results from streaming analysis
accumulated_results = []
for update in analyzer.analyze_streaming(str(source_path)):
if update["type"] == "complete":
if args.verbose:
print()
print(f"Completed in {update.get('elapsed_seconds', 0):.1f}s")
# Store accumulated results for return
accumulated_results = update
# Use accumulated results if available, otherwise fallback to standard analyzer
if accumulated_results and accumulated_results.get("processed_files", 0) > 0:
# Convert accumulated results to AnalysisResult format
standard_analyzer = ProjectAnalyzer(config)
return standard_analyzer.analyze_project(str(source_path))
# Fallback: use standard analyzer
standard_analyzer = ProjectAnalyzer(config)
return standard_analyzer.analyze_project(str(source_path))