dart-decimate 0.0.1

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.
Files changed (188) hide show
  1. package/Cargo.lock +572 -0
  2. package/Cargo.toml +41 -0
  3. package/LICENSE +21 -0
  4. package/README.md +617 -0
  5. package/assets/dart-decimate-banner.png +0 -0
  6. package/npm/bin/dart-decimate-mcp.js +48 -0
  7. package/npm/bin/dart-decimate.js +48 -0
  8. package/npm/scripts/postinstall.js +46 -0
  9. package/npm/scripts/test-npx-local.js +54 -0
  10. package/npm/scripts/test-npx-mcp-local.js +56 -0
  11. package/package.json +45 -0
  12. package/src/baseline.rs +643 -0
  13. package/src/bin/dart-decimate-mcp.rs +11 -0
  14. package/src/boundaries/tests.rs +60 -0
  15. package/src/boundaries.rs +317 -0
  16. package/src/changed_scope.rs +117 -0
  17. package/src/ci_template.rs +399 -0
  18. package/src/cli/analyze.rs +462 -0
  19. package/src/cli/analyzer_options.rs +82 -0
  20. package/src/cli/audit_run.rs +327 -0
  21. package/src/cli/boundary_args.rs +44 -0
  22. package/src/cli/ci_template_run.rs +196 -0
  23. package/src/cli/command_name.rs +20 -0
  24. package/src/cli/common_args.rs +167 -0
  25. package/src/cli/config_run.rs +78 -0
  26. package/src/cli/coverage_run.rs +393 -0
  27. package/src/cli/decision_surface_run.rs +99 -0
  28. package/src/cli/default_command.rs +69 -0
  29. package/src/cli/dupes_args.rs +150 -0
  30. package/src/cli/entry_points.rs +121 -0
  31. package/src/cli/error.rs +149 -0
  32. package/src/cli/error_output.rs +68 -0
  33. package/src/cli/explain_run.rs +72 -0
  34. package/src/cli/fix_run.rs +162 -0
  35. package/src/cli/flags_args.rs +23 -0
  36. package/src/cli/health_args.rs +200 -0
  37. package/src/cli/hooks_run.rs +191 -0
  38. package/src/cli/impact_run.rs +95 -0
  39. package/src/cli/init_run.rs +49 -0
  40. package/src/cli/inspect_args.rs +20 -0
  41. package/src/cli/inspect_run.rs +66 -0
  42. package/src/cli/issue_filter_args.rs +240 -0
  43. package/src/cli/list_run.rs +311 -0
  44. package/src/cli/mode_args.rs +72 -0
  45. package/src/cli/output_format.rs +62 -0
  46. package/src/cli/regression_args.rs +156 -0
  47. package/src/cli/request_args.rs +175 -0
  48. package/src/cli/schema_commands.rs +72 -0
  49. package/src/cli/scope_args.rs +174 -0
  50. package/src/cli/security_args.rs +175 -0
  51. package/src/cli/security_gate_run.rs +66 -0
  52. package/src/cli/security_summary_run.rs +43 -0
  53. package/src/cli/summary_args.rs +12 -0
  54. package/src/cli/tests.rs +516 -0
  55. package/src/cli/trace_args.rs +67 -0
  56. package/src/cli/trace_run.rs +131 -0
  57. package/src/cli/trace_tests.rs +235 -0
  58. package/src/cli/unsupported_run.rs +116 -0
  59. package/src/cli/watch_run.rs +153 -0
  60. package/src/cli.rs +603 -0
  61. package/src/config/boundary_config.rs +235 -0
  62. package/src/config/cache.rs +25 -0
  63. package/src/config/dependencies.rs +114 -0
  64. package/src/config/health.rs +237 -0
  65. package/src/config/jsonc.rs +66 -0
  66. package/src/config/policy.rs +91 -0
  67. package/src/config/rule_aliases.rs +487 -0
  68. package/src/config/rules.rs +339 -0
  69. package/src/config.rs +635 -0
  70. package/src/coverage.rs +469 -0
  71. package/src/dart_parser.rs +673 -0
  72. package/src/decision_surface.rs +405 -0
  73. package/src/dependencies/analyze.rs +218 -0
  74. package/src/dependencies/codegen.rs +118 -0
  75. package/src/dependencies/discovery.rs +60 -0
  76. package/src/dependencies/overrides.rs +76 -0
  77. package/src/dependencies/private_src_imports.rs +32 -0
  78. package/src/dependencies/pubspec_document.rs +86 -0
  79. package/src/dependencies/pubspec_entry.rs +96 -0
  80. package/src/dependencies/tests.rs +544 -0
  81. package/src/dependencies/usage.rs +33 -0
  82. package/src/dependencies.rs +553 -0
  83. package/src/dependency_scripts.rs +91 -0
  84. package/src/dupes/lex.rs +236 -0
  85. package/src/dupes/tests.rs +119 -0
  86. package/src/dupes.rs +625 -0
  87. package/src/explain.rs +692 -0
  88. package/src/extract/directives.rs +252 -0
  89. package/src/extract/error_tests.rs +25 -0
  90. package/src/extract/members.rs +210 -0
  91. package/src/extract/primary_constructors.rs +421 -0
  92. package/src/extract/references.rs +151 -0
  93. package/src/extract/routes.rs +691 -0
  94. package/src/extract/signatures.rs +266 -0
  95. package/src/extract/string_tests.rs +18 -0
  96. package/src/extract/strings.rs +107 -0
  97. package/src/extract/tests.rs +697 -0
  98. package/src/extract.rs +680 -0
  99. package/src/feature_flags/tests.rs +76 -0
  100. package/src/feature_flags.rs +453 -0
  101. package/src/finding_identity.rs +60 -0
  102. package/src/fix.rs +551 -0
  103. package/src/generated.rs +53 -0
  104. package/src/graph/augment_tests.rs +212 -0
  105. package/src/graph/conditionals.rs +74 -0
  106. package/src/graph/package_config_tests.rs +100 -0
  107. package/src/graph/parts.rs +248 -0
  108. package/src/graph/pubspec_tests.rs +119 -0
  109. package/src/graph/tests.rs +837 -0
  110. package/src/graph/uri_tests.rs +102 -0
  111. package/src/graph.rs +644 -0
  112. package/src/health/coverage.rs +309 -0
  113. package/src/health/ownership.rs +175 -0
  114. package/src/health/runtime_coverage.rs +616 -0
  115. package/src/health/runtime_intelligence.rs +511 -0
  116. package/src/health/scores.rs +296 -0
  117. package/src/health/tests.rs +240 -0
  118. package/src/health/threshold_types.rs +163 -0
  119. package/src/health/thresholds.rs +229 -0
  120. package/src/health/types.rs +636 -0
  121. package/src/health.rs +597 -0
  122. package/src/hooks/agent_settings.rs +175 -0
  123. package/src/hooks/templates.rs +51 -0
  124. package/src/hooks.rs +569 -0
  125. package/src/impact.rs +287 -0
  126. package/src/init.rs +237 -0
  127. package/src/inspect.rs +142 -0
  128. package/src/intelligence/tests.rs +232 -0
  129. package/src/intelligence.rs +305 -0
  130. package/src/lib.rs +198 -0
  131. package/src/main.rs +5 -0
  132. package/src/manifest/mcp.rs +565 -0
  133. package/src/manifest.rs +552 -0
  134. package/src/mcp/cli_args/value_args.rs +175 -0
  135. package/src/mcp/cli_args.rs +658 -0
  136. package/src/mcp/cli_args_tests.rs +522 -0
  137. package/src/mcp/code_execute.rs +671 -0
  138. package/src/mcp/tools.rs +660 -0
  139. package/src/mcp.rs +325 -0
  140. package/src/output/audit_risk.rs +135 -0
  141. package/src/output/dependency_findings.rs +327 -0
  142. package/src/output/duplication_findings.rs +114 -0
  143. package/src/output/feature_flag_findings.rs +122 -0
  144. package/src/output/format.rs +31 -0
  145. package/src/output/graph_findings.rs +461 -0
  146. package/src/output/health_findings.rs +612 -0
  147. package/src/output/human.rs +27 -0
  148. package/src/output/next_steps.rs +92 -0
  149. package/src/output/route_findings.rs +76 -0
  150. package/src/output/runtime_coverage.rs +515 -0
  151. package/src/output/scope.rs +183 -0
  152. package/src/output/security_findings.rs +390 -0
  153. package/src/output/security_sarif.rs +150 -0
  154. package/src/output/suppressions.rs +323 -0
  155. package/src/output/symbol_findings.rs +257 -0
  156. package/src/output/tests.rs +114 -0
  157. package/src/output/types.rs +604 -0
  158. package/src/output/widget_findings.rs +213 -0
  159. package/src/output.rs +682 -0
  160. package/src/package_map.rs +495 -0
  161. package/src/policy/packs.rs +232 -0
  162. package/src/policy/tests.rs +134 -0
  163. package/src/policy.rs +640 -0
  164. package/src/project_list.rs +376 -0
  165. package/src/report_schema/inventory.rs +418 -0
  166. package/src/report_schema.rs +488 -0
  167. package/src/routes.rs +354 -0
  168. package/src/scan/tests.rs +250 -0
  169. package/src/scan.rs +275 -0
  170. package/src/security/detect.rs +639 -0
  171. package/src/security/tests.rs +178 -0
  172. package/src/security.rs +373 -0
  173. package/src/security_gate.rs +555 -0
  174. package/src/symbols/path_filters.rs +27 -0
  175. package/src/symbols/private_type_leaks.rs +125 -0
  176. package/src/symbols/riverpod.rs +113 -0
  177. package/src/symbols/tests.rs +692 -0
  178. package/src/symbols.rs +693 -0
  179. package/src/trace/tests.rs +225 -0
  180. package/src/trace.rs +690 -0
  181. package/src/unsupported.rs +47 -0
  182. package/src/widgets/lifecycle.rs +484 -0
  183. package/src/widgets/params.rs +236 -0
  184. package/src/widgets/tests.rs +430 -0
  185. package/src/widgets/top_level.rs +110 -0
  186. package/src/widgets/unrendered.rs +374 -0
  187. package/src/widgets.rs +590 -0
  188. package/src/workspace_scope.rs +358 -0
@@ -0,0 +1,232 @@
1
+ use std::fs;
2
+ use std::path::{Path, PathBuf};
3
+
4
+ use tempfile::TempDir;
5
+
6
+ use super::*;
7
+ use crate::{DartExport, DartFile, DartImport, GraphError, build_module_graph};
8
+
9
+ #[test]
10
+ fn flags_files_unreachable_from_entry_points() -> Result<(), Box<dyn std::error::Error>> {
11
+ let fixture = Fixture::new()?;
12
+ fixture.write("pubspec.yaml", "name: app\n")?;
13
+ let graph = fixture.graph(&[
14
+ fixture.file("lib/main.dart", &["src/a.dart"]),
15
+ fixture.file("lib/src/a.dart", &["b.dart"]),
16
+ fixture.file("lib/src/b.dart", &[]),
17
+ fixture.file("lib/src/dead.dart", &[]),
18
+ ])?;
19
+
20
+ let report = find_dead_code(&graph, ["lib/main.dart", "lib/missing.dart"]);
21
+
22
+ assert_eq!(
23
+ paths(fixture.root(), report.reachable_files),
24
+ vec!["lib/main.dart", "lib/src/a.dart", "lib/src/b.dart",]
25
+ );
26
+ assert_eq!(
27
+ paths(fixture.root(), report.missing_entry_points),
28
+ vec!["lib/missing.dart",]
29
+ );
30
+ assert_eq!(
31
+ report
32
+ .dead_files
33
+ .into_iter()
34
+ .map(|dead| (strip_root(fixture.root(), &dead.path), dead.safe_to_delete))
35
+ .collect::<Vec<_>>(),
36
+ vec![("lib/src/dead.dart".to_owned(), true)]
37
+ );
38
+
39
+ Ok(())
40
+ }
41
+
42
+ #[test]
43
+ fn detects_tarjan_cycles_with_deterministic_file_order() -> Result<(), Box<dyn std::error::Error>> {
44
+ let fixture = Fixture::new()?;
45
+ fixture.write("pubspec.yaml", "name: app\n")?;
46
+ let graph = fixture.graph(&[
47
+ fixture.file("lib/a.dart", &["b.dart"]),
48
+ fixture.file("lib/b.dart", &["c.dart"]),
49
+ fixture.file("lib/c.dart", &["a.dart"]),
50
+ fixture.file("lib/acyclic.dart", &[]),
51
+ ])?;
52
+
53
+ let cycles = detect_cycles(&graph);
54
+
55
+ assert_eq!(cycles.len(), 1);
56
+ assert_eq!(
57
+ paths(fixture.root(), cycles[0].files.clone()),
58
+ vec!["lib/a.dart", "lib/b.dart", "lib/c.dart",]
59
+ );
60
+
61
+ Ok(())
62
+ }
63
+
64
+ #[test]
65
+ fn detects_self_loop_cycles() -> Result<(), Box<dyn std::error::Error>> {
66
+ let fixture = Fixture::new()?;
67
+ fixture.write("pubspec.yaml", "name: app\n")?;
68
+ let graph = fixture.graph(&[fixture.file("lib/self.dart", &["self.dart"])])?;
69
+
70
+ let cycles = detect_cycles(&graph);
71
+
72
+ assert_eq!(cycles.len(), 1);
73
+ assert_eq!(
74
+ paths(fixture.root(), cycles[0].files.clone()),
75
+ vec!["lib/self.dart",]
76
+ );
77
+
78
+ Ok(())
79
+ }
80
+
81
+ #[test]
82
+ fn detects_re_export_cycles_without_import_cycles() -> Result<(), Box<dyn std::error::Error>> {
83
+ let fixture = Fixture::new()?;
84
+ fixture.write("pubspec.yaml", "name: app\n")?;
85
+ let graph = fixture.graph(&[
86
+ fixture.file_with_exports("lib/a.dart", &["b.dart"]),
87
+ fixture.file_with_exports("lib/b.dart", &["a.dart"]),
88
+ fixture.file("lib/c.dart", &["d.dart"]),
89
+ fixture.file("lib/d.dart", &[]),
90
+ ])?;
91
+
92
+ let cycles = detect_re_export_cycles(&graph);
93
+
94
+ assert_eq!(cycles.len(), 1);
95
+ assert_eq!(
96
+ cycles[0]
97
+ .files
98
+ .iter()
99
+ .map(|path| strip_root(fixture.root(), path))
100
+ .collect::<Vec<_>>(),
101
+ vec!["lib/a.dart", "lib/b.dart"]
102
+ );
103
+
104
+ Ok(())
105
+ }
106
+
107
+ #[test]
108
+ fn flags_architecture_boundary_violations() -> Result<(), Box<dyn std::error::Error>> {
109
+ let fixture = Fixture::new()?;
110
+ fixture.write("pubspec.yaml", "name: app\n")?;
111
+ let graph = fixture.graph(&[
112
+ fixture.file("lib/domain/service.dart", &["../ui/widget.dart"]),
113
+ fixture.file("lib/domain/model.dart", &[]),
114
+ fixture.file("lib/ui/widget.dart", &[]),
115
+ fixture.file("lib/data/repository.dart", &["../domain/model.dart"]),
116
+ ])?;
117
+
118
+ let violations =
119
+ check_architecture_boundaries(&graph, &[BoundaryRule::new("lib/domain", "lib/ui")]);
120
+
121
+ assert_eq!(violations.len(), 1);
122
+ assert_eq!(
123
+ (
124
+ strip_root(fixture.root(), &violations[0].from_path),
125
+ strip_root(fixture.root(), &violations[0].to_path),
126
+ violations[0].specifier.as_str(),
127
+ ),
128
+ (
129
+ "lib/domain/service.dart".to_owned(),
130
+ "lib/ui/widget.dart".to_owned(),
131
+ "../ui/widget.dart",
132
+ )
133
+ );
134
+
135
+ Ok(())
136
+ }
137
+
138
+ fn paths(root: &Path, paths: Vec<PathBuf>) -> Vec<String> {
139
+ paths
140
+ .into_iter()
141
+ .map(|path| strip_root(root, &path))
142
+ .collect()
143
+ }
144
+
145
+ fn strip_root(root: &Path, path: &Path) -> String {
146
+ path.strip_prefix(root)
147
+ .unwrap_or(path)
148
+ .to_string_lossy()
149
+ .replace('\\', "/")
150
+ }
151
+
152
+ struct Fixture {
153
+ temp: TempDir,
154
+ }
155
+
156
+ impl Fixture {
157
+ fn new() -> Result<Self, std::io::Error> {
158
+ tempfile::tempdir().map(|temp| Self { temp })
159
+ }
160
+
161
+ fn root(&self) -> &Path {
162
+ self.temp.path()
163
+ }
164
+
165
+ fn path(&self, path: &str) -> PathBuf {
166
+ crate::graph::normalize_path(&self.root().join(path))
167
+ }
168
+
169
+ fn write(&self, path: &str, source: &str) -> Result<(), std::io::Error> {
170
+ let path = self.path(path);
171
+ if let Some(parent) = path.parent() {
172
+ fs::create_dir_all(parent)?;
173
+ }
174
+ fs::write(path, source)
175
+ }
176
+
177
+ fn file(&self, path: &str, imports: &[&str]) -> DartFile {
178
+ DartFile {
179
+ path: self.path(path),
180
+ library: None,
181
+ part_of: None,
182
+ imports: imports.iter().map(|uri| import(uri)).collect(),
183
+ exports: vec![],
184
+ parts: vec![],
185
+ declarations: vec![],
186
+ members: vec![],
187
+ references: vec![],
188
+ signature_references: vec![],
189
+ routes: vec![],
190
+ }
191
+ }
192
+
193
+ fn file_with_exports(&self, path: &str, exports: &[&str]) -> DartFile {
194
+ DartFile {
195
+ path: self.path(path),
196
+ library: None,
197
+ part_of: None,
198
+ imports: vec![],
199
+ exports: exports.iter().map(|uri| export(uri)).collect(),
200
+ parts: vec![],
201
+ declarations: vec![],
202
+ members: vec![],
203
+ references: vec![],
204
+ signature_references: vec![],
205
+ routes: vec![],
206
+ }
207
+ }
208
+
209
+ fn graph(&self, files: &[DartFile]) -> Result<ModuleGraph, GraphError> {
210
+ build_module_graph(self.root(), files)
211
+ }
212
+ }
213
+
214
+ fn import(uri: &str) -> DartImport {
215
+ DartImport {
216
+ uri: uri.to_owned(),
217
+ condition: None,
218
+ prefix: None,
219
+ deferred: false,
220
+ combinators: Vec::new(),
221
+ location: Location { line: 1, column: 0 },
222
+ }
223
+ }
224
+
225
+ fn export(uri: &str) -> DartExport {
226
+ DartExport {
227
+ uri: uri.to_owned(),
228
+ condition: None,
229
+ combinators: Vec::new(),
230
+ location: Location { line: 1, column: 0 },
231
+ }
232
+ }
@@ -0,0 +1,305 @@
1
+ use std::collections::{BTreeSet, VecDeque};
2
+ use std::path::{Path, PathBuf};
3
+
4
+ use petgraph::Direction;
5
+ use petgraph::algo::tarjan_scc;
6
+ use petgraph::graph::{DiGraph, NodeIndex};
7
+ use petgraph::visit::EdgeRef;
8
+ use serde::{Deserialize, Serialize};
9
+
10
+ use crate::graph::normalize_against;
11
+ use crate::{DependencyKind, Location, ModuleGraph};
12
+
13
+ /// Dead-code reachability result for a module graph.
14
+ #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
15
+ pub struct DeadCodeReport {
16
+ /// Entry point files found in the graph.
17
+ pub entry_points: Vec<PathBuf>,
18
+ /// Entry point files requested by the caller but absent from the graph.
19
+ pub missing_entry_points: Vec<PathBuf>,
20
+ /// Files reachable from at least one entry point.
21
+ pub reachable_files: Vec<PathBuf>,
22
+ /// Files not reachable from any entry point.
23
+ pub dead_files: Vec<DeadFile>,
24
+ }
25
+
26
+ /// An unreachable Dart file.
27
+ #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
28
+ pub struct DeadFile {
29
+ /// Unreachable file path.
30
+ pub path: PathBuf,
31
+ /// Whether Dart Decimate can suggest deletion from graph evidence alone.
32
+ pub safe_to_delete: bool,
33
+ }
34
+
35
+ /// A circular dependency reported as one strongly connected component.
36
+ #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
37
+ pub struct DependencyCycle {
38
+ /// Files participating in the cycle, sorted for deterministic output.
39
+ pub files: Vec<PathBuf>,
40
+ }
41
+
42
+ /// A cycle composed only of Dart `export` edges.
43
+ #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
44
+ pub struct ReExportCycle {
45
+ /// Files participating in the re-export cycle, sorted for deterministic output.
46
+ pub files: Vec<PathBuf>,
47
+ }
48
+
49
+ /// A directory-based architecture boundary rule.
50
+ #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
51
+ pub struct BoundaryRule {
52
+ /// Source directory covered by the rule, relative to the project root unless absolute.
53
+ pub from: PathBuf,
54
+ /// Directory that matching source files must not depend on.
55
+ pub disallow: PathBuf,
56
+ }
57
+
58
+ impl BoundaryRule {
59
+ /// Create a boundary rule.
60
+ pub fn new(from: impl Into<PathBuf>, disallow: impl Into<PathBuf>) -> Self {
61
+ Self {
62
+ from: from.into(),
63
+ disallow: disallow.into(),
64
+ }
65
+ }
66
+ }
67
+
68
+ /// A graph edge that violates a boundary rule.
69
+ #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
70
+ pub struct BoundaryViolation {
71
+ /// File containing the violating directive.
72
+ pub from_path: PathBuf,
73
+ /// File resolved from the violating directive.
74
+ pub to_path: PathBuf,
75
+ /// Rule source directory.
76
+ pub from_boundary: PathBuf,
77
+ /// Rule disallowed target directory.
78
+ pub disallowed_boundary: PathBuf,
79
+ /// Raw import/export URI from the source file.
80
+ pub specifier: String,
81
+ /// Whether the dependency came from an import or export directive.
82
+ pub kind: DependencyKind,
83
+ /// Location of the directive in the source file.
84
+ pub location: Location,
85
+ }
86
+
87
+ /// Traverse the graph from entry points and flag unreachable files.
88
+ #[must_use]
89
+ pub fn find_dead_code<P>(
90
+ graph: &ModuleGraph,
91
+ entry_points: impl IntoIterator<Item = P>,
92
+ ) -> DeadCodeReport
93
+ where
94
+ P: AsRef<Path>,
95
+ {
96
+ let mut reachable_nodes = BTreeSet::new();
97
+ let mut found_entry_points = BTreeSet::new();
98
+ let mut missing_entry_points = BTreeSet::new();
99
+
100
+ for entry_point in entry_points {
101
+ let entry_path = normalize_against(graph.root(), entry_point.as_ref());
102
+ let Some(start) = graph.node_index(&entry_path) else {
103
+ missing_entry_points.insert(entry_path);
104
+ continue;
105
+ };
106
+
107
+ found_entry_points.insert(entry_path);
108
+ traverse_reachable(graph, start, &mut reachable_nodes);
109
+ }
110
+
111
+ let reachable_files = reachable_nodes
112
+ .iter()
113
+ .map(|node| graph.graph()[*node].path.clone())
114
+ .collect::<BTreeSet<_>>();
115
+
116
+ let mut dead_files = graph
117
+ .graph()
118
+ .node_indices()
119
+ .filter_map(|node| {
120
+ if reachable_nodes.contains(&node) {
121
+ return None;
122
+ }
123
+ Some(DeadFile {
124
+ path: graph.graph()[node].path.clone(),
125
+ safe_to_delete: true,
126
+ })
127
+ })
128
+ .collect::<Vec<_>>();
129
+ dead_files.sort_by(|left, right| left.path.cmp(&right.path));
130
+
131
+ DeadCodeReport {
132
+ entry_points: found_entry_points.into_iter().collect(),
133
+ missing_entry_points: missing_entry_points.into_iter().collect(),
134
+ reachable_files: reachable_files.into_iter().collect(),
135
+ dead_files,
136
+ }
137
+ }
138
+
139
+ /// Detect circular dependencies using petgraph's Tarjan SCC implementation.
140
+ #[must_use]
141
+ pub fn detect_cycles(graph: &ModuleGraph) -> Vec<DependencyCycle> {
142
+ let mut cycles = tarjan_scc(graph.graph())
143
+ .into_iter()
144
+ .filter_map(|component| cycle_from_component(graph, component))
145
+ .collect::<Vec<_>>();
146
+
147
+ cycles.sort_by(|left, right| left.files.cmp(&right.files));
148
+ cycles
149
+ }
150
+
151
+ /// Detect structural cycles made only of `export` edges.
152
+ #[must_use]
153
+ pub fn detect_re_export_cycles(graph: &ModuleGraph) -> Vec<ReExportCycle> {
154
+ let mut export_graph = DiGraph::<NodeIndex, ()>::new();
155
+ let mut original_to_export = std::collections::BTreeMap::new();
156
+
157
+ for node in graph.graph().node_indices() {
158
+ let mapped = export_graph.add_node(node);
159
+ original_to_export.insert(node, mapped);
160
+ }
161
+
162
+ for edge in graph
163
+ .graph()
164
+ .edge_references()
165
+ .filter(|edge| edge.weight().kind == DependencyKind::Export)
166
+ {
167
+ let Some(from) = original_to_export.get(&edge.source()).copied() else {
168
+ continue;
169
+ };
170
+ let Some(to) = original_to_export.get(&edge.target()).copied() else {
171
+ continue;
172
+ };
173
+ export_graph.add_edge(from, to, ());
174
+ }
175
+
176
+ let mut cycles = tarjan_scc(&export_graph)
177
+ .into_iter()
178
+ .filter_map(|component| re_export_cycle_from_component(graph, &export_graph, component))
179
+ .collect::<Vec<_>>();
180
+ cycles.sort_by(|left, right| left.files.cmp(&right.files));
181
+ cycles
182
+ }
183
+
184
+ /// Check directory boundary rules against all resolved graph edges.
185
+ #[must_use]
186
+ pub fn check_architecture_boundaries(
187
+ graph: &ModuleGraph,
188
+ rules: &[BoundaryRule],
189
+ ) -> Vec<BoundaryViolation> {
190
+ let normalized_rules = rules
191
+ .iter()
192
+ .map(|rule| {
193
+ (
194
+ normalize_against(graph.root(), &rule.from),
195
+ normalize_against(graph.root(), &rule.disallow),
196
+ )
197
+ })
198
+ .collect::<Vec<_>>();
199
+
200
+ let mut violations = graph
201
+ .dependencies()
202
+ .into_iter()
203
+ .flat_map(|dependency| {
204
+ normalized_rules
205
+ .iter()
206
+ .filter_map(move |(from_boundary, disallowed_boundary)| {
207
+ if dependency.from_path.starts_with(from_boundary)
208
+ && dependency.to_path.starts_with(disallowed_boundary)
209
+ {
210
+ return Some(BoundaryViolation {
211
+ from_path: dependency.from_path.clone(),
212
+ to_path: dependency.to_path.clone(),
213
+ from_boundary: from_boundary.clone(),
214
+ disallowed_boundary: disallowed_boundary.clone(),
215
+ specifier: dependency.specifier.clone(),
216
+ kind: dependency.kind,
217
+ location: dependency.location,
218
+ });
219
+ }
220
+
221
+ None
222
+ })
223
+ })
224
+ .collect::<Vec<_>>();
225
+
226
+ violations.sort_by(|left, right| {
227
+ (
228
+ &left.from_path,
229
+ &left.to_path,
230
+ &left.from_boundary,
231
+ &left.disallowed_boundary,
232
+ )
233
+ .cmp(&(
234
+ &right.from_path,
235
+ &right.to_path,
236
+ &right.from_boundary,
237
+ &right.disallowed_boundary,
238
+ ))
239
+ });
240
+ violations
241
+ }
242
+
243
+ fn traverse_reachable(graph: &ModuleGraph, start: NodeIndex, reachable: &mut BTreeSet<NodeIndex>) {
244
+ let mut queue = VecDeque::from([start]);
245
+ while let Some(node) = queue.pop_front() {
246
+ if !reachable.insert(node) {
247
+ continue;
248
+ }
249
+ for edge in graph.graph().edges(node) {
250
+ queue.push_back(edge.target());
251
+ }
252
+ for edge in graph.graph().edges_directed(node, Direction::Incoming) {
253
+ if edge.weight().kind == DependencyKind::Augment {
254
+ queue.push_back(edge.source());
255
+ }
256
+ }
257
+ }
258
+ }
259
+
260
+ fn cycle_from_component(graph: &ModuleGraph, component: Vec<NodeIndex>) -> Option<DependencyCycle> {
261
+ let first = component.first().copied()?;
262
+ let is_cycle = component.len() > 1 || component_has_self_loop(graph, first);
263
+ if !is_cycle {
264
+ return None;
265
+ }
266
+
267
+ let mut files = component
268
+ .into_iter()
269
+ .map(|node| graph.graph()[node].path.clone())
270
+ .collect::<Vec<_>>();
271
+ files.sort();
272
+
273
+ Some(DependencyCycle { files })
274
+ }
275
+
276
+ fn component_has_self_loop(graph: &ModuleGraph, node: NodeIndex) -> bool {
277
+ graph.graph().edges(node).any(|edge| edge.target() == node)
278
+ }
279
+
280
+ fn re_export_cycle_from_component(
281
+ graph: &ModuleGraph,
282
+ export_graph: &DiGraph<NodeIndex, ()>,
283
+ component: Vec<NodeIndex>,
284
+ ) -> Option<ReExportCycle> {
285
+ let first = component.first().copied()?;
286
+ let is_cycle = component.len() > 1 || export_component_has_self_loop(export_graph, first);
287
+ if !is_cycle {
288
+ return None;
289
+ }
290
+
291
+ let mut files = component
292
+ .into_iter()
293
+ .map(|node| graph.graph()[export_graph[node]].path.clone())
294
+ .collect::<Vec<_>>();
295
+ files.sort();
296
+
297
+ Some(ReExportCycle { files })
298
+ }
299
+
300
+ fn export_component_has_self_loop(graph: &DiGraph<NodeIndex, ()>, node: NodeIndex) -> bool {
301
+ graph.edges(node).any(|edge| edge.target() == node)
302
+ }
303
+
304
+ #[cfg(test)]
305
+ mod tests;