-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdependency_analyzer.py
More file actions
166 lines (126 loc) Β· 4.68 KB
/
dependency_analyzer.py
File metadata and controls
166 lines (126 loc) Β· 4.68 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
#!/usr/bin/env python3
"""Analyze module dependency hierarchy and detect circular imports.
This script scans Python modules to:
- Build a dependency graph
- Detect circular imports
- Identify architecture layer violations
"""
import argparse
import ast
import sys
from collections import defaultdict
from pathlib import Path
def extract_imports(file_path: Path) -> set[str]:
"""Extract import statements from a Python file."""
imports = set()
try:
with open(file_path, encoding="utf-8") as f:
tree = ast.parse(f.read(), filename=str(file_path))
except (SyntaxError, UnicodeDecodeError):
return imports
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for alias in node.names:
imports.add(alias.name.split(".")[0])
elif isinstance(node, ast.ImportFrom) and node.module:
imports.add(node.module.split(".")[0])
return imports
def build_dependency_graph(src_dir: Path) -> dict[str, set[str]]:
"""Build a dependency graph from source files."""
graph = defaultdict(set)
for py_file in src_dir.rglob("*.py"):
if "__pycache__" in str(py_file):
continue
# Get module name relative to src
try:
rel_path = py_file.relative_to(src_dir)
module_parts = list(rel_path.parts[:-1]) # Directory parts
if py_file.name != "__init__.py":
module_parts.append(py_file.stem)
module_name = ".".join(module_parts) if module_parts else py_file.stem
except ValueError:
continue
imports = extract_imports(py_file)
graph[module_name] = imports
return dict(graph)
def find_cycles(
graph: dict[str, set[str]], start: str, visited: set[str], path: list
) -> list:
"""Find cycles in the dependency graph using DFS."""
cycles = []
if start in visited:
if start in path:
cycle_start = path.index(start)
cycles.append([*path[cycle_start:], start])
return cycles
visited.add(start)
path.append(start)
for dep in graph.get(start, set()):
if dep in graph: # Only follow internal dependencies
cycles.extend(find_cycles(graph, dep, visited.copy(), path.copy()))
return cycles
def analyze_dependencies(repo_root: Path) -> int:
"""Analyze dependencies and report findings."""
print("π Analyzing module dependency hierarchy...\n")
src_dir = repo_root / "src" / "codomyrmex"
if not src_dir.exists():
src_dir = repo_root / "src"
if not src_dir.exists():
print("β No src directory found")
return 1
graph = build_dependency_graph(src_dir)
print(f"π Found {len(graph)} modules")
# Find potential circular dependencies
all_cycles = []
for module in graph:
cycles = find_cycles(graph, module, set(), [])
all_cycles.extend(cycles)
# Deduplicate cycles
unique_cycles = []
for cycle in all_cycles:
normalized = tuple(sorted(cycle))
if normalized not in [tuple(sorted(c)) for c in unique_cycles]:
unique_cycles.append(cycle)
if unique_cycles:
print(f"\nβ οΈ Found {len(unique_cycles)} potential circular dependencies:")
for i, cycle in enumerate(unique_cycles[:5], 1): # Show first 5
print(f" {i}. {' -> '.join(cycle)}")
if len(unique_cycles) > 5:
print(f" ... and {len(unique_cycles) - 5} more")
else:
print("\nβ
No circular dependencies detected")
# Report top-level modules
top_level = set()
for module in graph:
if "." not in module:
top_level.add(module)
print(f"\nπ¦ Top-level modules: {len(top_level)}")
for mod in sorted(list(top_level)[:10]):
print(f" - {mod}")
print("\nβ
Dependency analysis complete")
return 0
def main():
# Auto-injected: Load configuration
from pathlib import Path
import yaml
config_path = (
Path(__file__).resolve().parent.parent.parent
/ "config"
/ "validation"
/ "config.yaml"
)
if config_path.exists():
with open(config_path) as f:
yaml.safe_load(f) or {}
print("Loaded config from config/validation/config.yaml")
parser = argparse.ArgumentParser(description="Analyze module dependency hierarchy")
parser.add_argument(
"--repo-root", type=Path, default=Path.cwd(), help="Repository root directory"
)
parser.add_argument(
"--output", type=Path, help="Output file for dependency graph (JSON)"
)
args = parser.parse_args()
return analyze_dependencies(args.repo_root)
if __name__ == "__main__":
sys.exit(main())