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,60 @@
1
+ use std::fs;
2
+ use std::path::PathBuf;
3
+
4
+ use tempfile::TempDir;
5
+
6
+ use super::*;
7
+ use crate::scan_project;
8
+
9
+ #[test]
10
+ fn reports_library_files_not_covered_by_boundary_zones() -> Result<(), Box<dyn std::error::Error>> {
11
+ let fixture = tempfile::tempdir()?;
12
+ write(&fixture, "pubspec.yaml", "name: app\n")?;
13
+ write(&fixture, "lib/domain/model.dart", "class Model {}\n")?;
14
+ write(&fixture, "lib/ui/page.dart", "class Page {}\n")?;
15
+ write(
16
+ &fixture,
17
+ "lib/data/repository.dart",
18
+ "class Repository {}\n",
19
+ )?;
20
+ let project = scan_project(fixture.path())?;
21
+
22
+ let gaps =
23
+ detect_boundary_coverage(&project, &[BoundaryRule::new("lib/domain", "lib/ui")], &[]);
24
+
25
+ assert_eq!(
26
+ gaps.iter()
27
+ .filter_map(|gap| gap.path.strip_prefix(fixture.path()).ok())
28
+ .map(PathBuf::from)
29
+ .collect::<Vec<_>>(),
30
+ vec![PathBuf::from("lib/data/repository.dart")]
31
+ );
32
+
33
+ Ok(())
34
+ }
35
+
36
+ #[test]
37
+ fn skips_generated_and_non_library_files() -> Result<(), Box<dyn std::error::Error>> {
38
+ let fixture = tempfile::tempdir()?;
39
+ write(&fixture, "pubspec.yaml", "name: app\n")?;
40
+ write(&fixture, "lib/domain/model.dart", "class Model {}\n")?;
41
+ write(&fixture, "lib/ui/page.dart", "class Page {}\n")?;
42
+ write(&fixture, "lib/orphan.g.dart", "class Generated {}\n")?;
43
+ write(&fixture, "test/orphan_test.dart", "void main() {}\n")?;
44
+ let project = scan_project(fixture.path())?;
45
+
46
+ let gaps =
47
+ detect_boundary_coverage(&project, &[BoundaryRule::new("lib/domain", "lib/ui")], &[]);
48
+
49
+ assert!(gaps.is_empty());
50
+
51
+ Ok(())
52
+ }
53
+
54
+ fn write(fixture: &TempDir, path: &str, source: &str) -> Result<(), std::io::Error> {
55
+ let path = fixture.path().join(path);
56
+ if let Some(parent) = path.parent() {
57
+ fs::create_dir_all(parent)?;
58
+ }
59
+ fs::write(path, source)
60
+ }
@@ -0,0 +1,317 @@
1
+ use std::collections::BTreeSet;
2
+ use std::path::{Path, PathBuf};
3
+
4
+ use serde::{Deserialize, Serialize};
5
+
6
+ use crate::generated::is_generated_dart_path;
7
+ use crate::graph::normalize_against;
8
+ use crate::{BoundaryRule, Location, ScannedProject};
9
+
10
+ /// Built-in architecture boundary presets.
11
+ #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
12
+ #[serde(rename_all = "kebab-case")]
13
+ pub enum BoundaryPreset {
14
+ /// Classic inward-only layers: domain/data/application cannot depend outward.
15
+ Layered,
16
+ /// Hexagonal architecture: domain/application stay independent of adapters.
17
+ Hexagonal,
18
+ /// Feature-sliced layer order: shared -> entities -> features -> widgets -> pages -> app.
19
+ FeatureSliced,
20
+ /// Feature-first app layout with shared/core kept independent of feature code.
21
+ Bulletproof,
22
+ }
23
+
24
+ impl BoundaryPreset {
25
+ /// Preset identifier used in config and JSON output.
26
+ #[must_use]
27
+ pub const fn as_str(self) -> &'static str {
28
+ match self {
29
+ Self::Layered => "layered",
30
+ Self::Hexagonal => "hexagonal",
31
+ Self::FeatureSliced => "feature-sliced",
32
+ Self::Bulletproof => "bulletproof",
33
+ }
34
+ }
35
+ }
36
+
37
+ /// A Dart library file not covered by any configured architecture boundary.
38
+ #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
39
+ pub struct BoundaryCoverageGap {
40
+ /// File outside every configured boundary path.
41
+ pub path: PathBuf,
42
+ /// Boundary paths Dart Decimate considered as architecture zones.
43
+ pub configured_boundaries: Vec<PathBuf>,
44
+ /// Location used for report anchoring.
45
+ pub location: Location,
46
+ }
47
+
48
+ /// Architecture boundary inventory for `dart-decimate list --boundaries`.
49
+ #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
50
+ pub struct BoundaryInventory {
51
+ /// Whether any boundary rules are configured.
52
+ pub configured: bool,
53
+ /// Built-in presets contributing boundary rules.
54
+ pub presets: Vec<BoundaryPreset>,
55
+ /// Root-relative globs exempt from boundary coverage gaps.
56
+ pub allow_unmatched: Vec<String>,
57
+ /// Directory zones inferred from configured rules.
58
+ pub zones: Vec<BoundaryZone>,
59
+ /// Configured access rules.
60
+ pub rules: Vec<BoundaryAccessRule>,
61
+ /// Dart library files outside every configured zone.
62
+ pub uncovered_files: Vec<PathBuf>,
63
+ }
64
+
65
+ /// One configured boundary zone.
66
+ #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
67
+ pub struct BoundaryZone {
68
+ /// Boundary path.
69
+ pub path: PathBuf,
70
+ /// Dart library files under this boundary path.
71
+ pub file_count: usize,
72
+ }
73
+
74
+ /// One configured boundary access rule.
75
+ #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
76
+ pub struct BoundaryAccessRule {
77
+ /// Source zone.
78
+ pub from: PathBuf,
79
+ /// Disallowed target zone.
80
+ pub disallow: PathBuf,
81
+ /// Files covered by the source zone.
82
+ pub covered_files: usize,
83
+ }
84
+
85
+ /// Build a boundary inventory from configured directory rules.
86
+ #[must_use]
87
+ pub fn boundary_inventory(
88
+ project: &ScannedProject,
89
+ rules: &[BoundaryRule],
90
+ presets: &[BoundaryPreset],
91
+ allow_unmatched: &[String],
92
+ ) -> BoundaryInventory {
93
+ let zones = configured_boundary_paths(&project.root, rules);
94
+ let library_files = library_files(project);
95
+ let listed_zones = zones
96
+ .iter()
97
+ .map(|zone| BoundaryZone {
98
+ path: zone.clone(),
99
+ file_count: library_files
100
+ .iter()
101
+ .filter(|path| path.starts_with(zone))
102
+ .count(),
103
+ })
104
+ .collect::<Vec<_>>();
105
+ let rules = rules
106
+ .iter()
107
+ .map(|rule| {
108
+ let from = normalize_against(&project.root, &rule.from);
109
+ let disallow = normalize_against(&project.root, &rule.disallow);
110
+ BoundaryAccessRule {
111
+ covered_files: library_files
112
+ .iter()
113
+ .filter(|path| path.starts_with(&from))
114
+ .count(),
115
+ from,
116
+ disallow,
117
+ }
118
+ })
119
+ .collect::<Vec<_>>();
120
+ let uncovered_files = library_files
121
+ .into_iter()
122
+ .filter(|path| {
123
+ !zones.iter().any(|zone| path.starts_with(zone))
124
+ && !matches_allow_unmatched(&project.root, path, allow_unmatched)
125
+ })
126
+ .collect::<Vec<_>>();
127
+
128
+ BoundaryInventory {
129
+ configured: !listed_zones.is_empty(),
130
+ presets: presets.to_vec(),
131
+ allow_unmatched: allow_unmatched.to_vec(),
132
+ zones: listed_zones,
133
+ rules,
134
+ uncovered_files,
135
+ }
136
+ }
137
+
138
+ /// Report Dart library files that do not belong to any configured boundary zone.
139
+ #[must_use]
140
+ pub fn detect_boundary_coverage(
141
+ project: &ScannedProject,
142
+ rules: &[BoundaryRule],
143
+ allow_unmatched: &[String],
144
+ ) -> Vec<BoundaryCoverageGap> {
145
+ let configured_boundaries = configured_boundary_paths(&project.root, rules);
146
+ if configured_boundaries.is_empty() {
147
+ return Vec::new();
148
+ }
149
+
150
+ let mut gaps = project
151
+ .files
152
+ .iter()
153
+ .filter_map(|file| {
154
+ let path = normalize_against(&project.root, &file.path);
155
+ if !is_library_source(&project.root, &path)
156
+ || is_generated_dart_path(&path)
157
+ || configured_boundaries
158
+ .iter()
159
+ .any(|boundary| path.starts_with(boundary))
160
+ || matches_allow_unmatched(&project.root, &path, allow_unmatched)
161
+ {
162
+ return None;
163
+ }
164
+
165
+ Some(BoundaryCoverageGap {
166
+ path,
167
+ configured_boundaries: configured_boundaries.clone(),
168
+ location: file
169
+ .declarations
170
+ .first()
171
+ .map_or(Location { line: 1, column: 0 }, |declaration| {
172
+ declaration.location
173
+ }),
174
+ })
175
+ })
176
+ .collect::<Vec<_>>();
177
+
178
+ gaps.sort_by(|left, right| left.path.cmp(&right.path));
179
+ gaps
180
+ }
181
+
182
+ /// Expand built-in architecture presets into concrete path rules.
183
+ #[must_use]
184
+ pub fn boundary_preset_rules(presets: &[BoundaryPreset]) -> Vec<BoundaryRule> {
185
+ presets
186
+ .iter()
187
+ .copied()
188
+ .flat_map(preset_boundary_rules)
189
+ .collect()
190
+ }
191
+
192
+ fn preset_boundary_rules(preset: BoundaryPreset) -> Vec<BoundaryRule> {
193
+ match preset {
194
+ BoundaryPreset::Layered => rules(&[
195
+ ("lib/domain", "lib/data"),
196
+ ("lib/domain", "lib/application"),
197
+ ("lib/domain", "lib/infrastructure"),
198
+ ("lib/domain", "lib/presentation"),
199
+ ("lib/domain", "lib/ui"),
200
+ ("lib/data", "lib/presentation"),
201
+ ("lib/data", "lib/ui"),
202
+ ("lib/application", "lib/infrastructure"),
203
+ ("lib/application", "lib/presentation"),
204
+ ("lib/application", "lib/ui"),
205
+ ]),
206
+ BoundaryPreset::Hexagonal => rules(&[
207
+ ("lib/domain", "lib/application"),
208
+ ("lib/domain", "lib/infrastructure"),
209
+ ("lib/domain", "lib/adapters"),
210
+ ("lib/domain", "lib/presentation"),
211
+ ("lib/domain", "lib/ui"),
212
+ ("lib/application", "lib/infrastructure"),
213
+ ("lib/application", "lib/adapters"),
214
+ ("lib/application", "lib/presentation"),
215
+ ("lib/application", "lib/ui"),
216
+ ]),
217
+ BoundaryPreset::FeatureSliced => rules(&[
218
+ ("lib/shared", "lib/entities"),
219
+ ("lib/shared", "lib/features"),
220
+ ("lib/shared", "lib/widgets"),
221
+ ("lib/shared", "lib/pages"),
222
+ ("lib/shared", "lib/app"),
223
+ ("lib/entities", "lib/features"),
224
+ ("lib/entities", "lib/widgets"),
225
+ ("lib/entities", "lib/pages"),
226
+ ("lib/entities", "lib/app"),
227
+ ("lib/features", "lib/widgets"),
228
+ ("lib/features", "lib/pages"),
229
+ ("lib/features", "lib/app"),
230
+ ("lib/widgets", "lib/pages"),
231
+ ("lib/widgets", "lib/app"),
232
+ ("lib/pages", "lib/app"),
233
+ ]),
234
+ BoundaryPreset::Bulletproof => rules(&[
235
+ ("lib/core", "lib/features"),
236
+ ("lib/core", "lib/app"),
237
+ ("lib/core", "lib/pages"),
238
+ ("lib/shared", "lib/features"),
239
+ ("lib/shared", "lib/app"),
240
+ ("lib/shared", "lib/pages"),
241
+ ("lib/features", "lib/app"),
242
+ ("lib/features", "lib/pages"),
243
+ ]),
244
+ }
245
+ }
246
+
247
+ fn rules(pairs: &[(&str, &str)]) -> Vec<BoundaryRule> {
248
+ pairs
249
+ .iter()
250
+ .map(|(from, disallow)| BoundaryRule::new(*from, *disallow))
251
+ .collect()
252
+ }
253
+
254
+ fn library_files(project: &ScannedProject) -> Vec<PathBuf> {
255
+ project
256
+ .files
257
+ .iter()
258
+ .filter_map(|file| {
259
+ let path = normalize_against(&project.root, &file.path);
260
+ (is_library_source(&project.root, &path) && !is_generated_dart_path(&path))
261
+ .then_some(path)
262
+ })
263
+ .collect()
264
+ }
265
+
266
+ fn configured_boundary_paths(root: &Path, rules: &[BoundaryRule]) -> Vec<PathBuf> {
267
+ let mut paths = rules
268
+ .iter()
269
+ .flat_map(|rule| [&rule.from, &rule.disallow])
270
+ .map(|path| normalize_against(root, path))
271
+ .collect::<BTreeSet<_>>()
272
+ .into_iter()
273
+ .collect::<Vec<_>>();
274
+ paths.sort();
275
+ paths
276
+ }
277
+
278
+ fn matches_allow_unmatched(root: &Path, path: &Path, allow_unmatched: &[String]) -> bool {
279
+ let relative = path
280
+ .strip_prefix(root)
281
+ .unwrap_or(path)
282
+ .components()
283
+ .filter_map(|component| match component {
284
+ std::path::Component::Normal(value) => value.to_str(),
285
+ _ => None,
286
+ })
287
+ .collect::<Vec<_>>()
288
+ .join("/");
289
+ allow_unmatched
290
+ .iter()
291
+ .any(|pattern| matches_pattern(pattern, &relative))
292
+ }
293
+
294
+ fn matches_pattern(pattern: &str, relative: &str) -> bool {
295
+ let normalized = pattern.trim().trim_start_matches("./");
296
+ if normalized.is_empty() {
297
+ return false;
298
+ }
299
+ if relative == normalized
300
+ || relative.starts_with(&format!("{}/", normalized.trim_end_matches('/')))
301
+ {
302
+ return true;
303
+ }
304
+ glob::Pattern::new(normalized).is_ok_and(|pattern| pattern.matches(relative))
305
+ }
306
+
307
+ fn is_library_source(root: &Path, path: &Path) -> bool {
308
+ path.strip_prefix(root).is_ok_and(|relative| {
309
+ relative
310
+ .components()
311
+ .next()
312
+ .is_some_and(|component| component.as_os_str() == "lib")
313
+ })
314
+ }
315
+
316
+ #[cfg(test)]
317
+ mod tests;
@@ -0,0 +1,117 @@
1
+ use std::collections::BTreeSet;
2
+ use std::path::{Path, PathBuf};
3
+ use std::process::Command;
4
+
5
+ use thiserror::Error;
6
+
7
+ use crate::graph::normalize_against;
8
+ use crate::scan::ScannedProject;
9
+
10
+ /// Errors returned while computing changed file scope.
11
+ #[derive(Debug, Error)]
12
+ pub enum ChangedScopeError {
13
+ /// Git could not be executed.
14
+ #[error("failed to run git diff for changed scope: {source}")]
15
+ Git {
16
+ /// Underlying IO error.
17
+ source: std::io::Error,
18
+ },
19
+ /// Git returned a non-zero status.
20
+ #[error("git diff failed for base {base:?}: {stderr}")]
21
+ GitDiff {
22
+ /// Base revision passed by the caller.
23
+ base: String,
24
+ /// Stderr from git.
25
+ stderr: String,
26
+ },
27
+ }
28
+
29
+ /// Return root-normalized files changed since `base`.
30
+ ///
31
+ /// # Errors
32
+ ///
33
+ /// Returns [`ChangedScopeError`] if `git diff` cannot be executed or the base
34
+ /// revision is invalid for this repository.
35
+ pub fn changed_files(root: &Path, base: &str) -> Result<Vec<PathBuf>, ChangedScopeError> {
36
+ let output = Command::new("git")
37
+ .args(["diff", "--name-only", "--diff-filter=ACMRTUXB", base, "--"])
38
+ .current_dir(root)
39
+ .output()
40
+ .map_err(|source| ChangedScopeError::Git { source })?;
41
+
42
+ if !output.status.success() {
43
+ return Err(ChangedScopeError::GitDiff {
44
+ base: base.to_owned(),
45
+ stderr: String::from_utf8_lossy(&output.stderr).trim().to_owned(),
46
+ });
47
+ }
48
+
49
+ let untracked = Command::new("git")
50
+ .args(["ls-files", "--others", "--exclude-standard"])
51
+ .current_dir(root)
52
+ .output()
53
+ .map_err(|source| ChangedScopeError::Git { source })?;
54
+
55
+ if !untracked.status.success() {
56
+ return Err(ChangedScopeError::GitDiff {
57
+ base: base.to_owned(),
58
+ stderr: String::from_utf8_lossy(&untracked.stderr).trim().to_owned(),
59
+ });
60
+ }
61
+
62
+ let mut paths = changed_paths(root, &output.stdout);
63
+ paths.extend(changed_paths(root, &untracked.stdout));
64
+ Ok(paths.into_iter().collect())
65
+ }
66
+
67
+ /// Return changed files plus one resolved graph hop in either direction.
68
+ ///
69
+ /// # Errors
70
+ ///
71
+ /// Returns [`ChangedScopeError`] if changed-file discovery fails.
72
+ pub fn changed_file_scope(
73
+ project: &ScannedProject,
74
+ base: &str,
75
+ ) -> Result<Vec<PathBuf>, ChangedScopeError> {
76
+ let changed = changed_files(&project.root, base)?;
77
+ Ok(changed_file_scope_from_changed(project, &changed))
78
+ }
79
+
80
+ /// Expand an already discovered changed-file list with one graph hop.
81
+ #[must_use]
82
+ pub fn changed_file_scope_from_changed(
83
+ project: &ScannedProject,
84
+ changed: &[PathBuf],
85
+ ) -> Vec<PathBuf> {
86
+ expand_related_files(project, changed.to_vec())
87
+ }
88
+
89
+ fn expand_related_files(project: &ScannedProject, changed: Vec<PathBuf>) -> Vec<PathBuf> {
90
+ let changed_set = changed.into_iter().collect::<BTreeSet<_>>();
91
+ let mut scope = changed_set.clone();
92
+
93
+ for dependency in project.graph.dependencies() {
94
+ if changed_set.contains(&dependency.from_path) {
95
+ scope.insert(dependency.to_path);
96
+ } else if changed_set.contains(&dependency.to_path) {
97
+ scope.insert(dependency.from_path);
98
+ }
99
+ }
100
+
101
+ scope.into_iter().collect()
102
+ }
103
+
104
+ fn changed_paths(root: &Path, stdout: &[u8]) -> BTreeSet<PathBuf> {
105
+ stdout
106
+ .split(|byte| *byte == b'\n')
107
+ .filter_map(|line| std::str::from_utf8(line).ok())
108
+ .map(str::trim)
109
+ .filter(|line| !line.is_empty())
110
+ .filter_map(|line| normalize_changed_path(root, line))
111
+ .collect()
112
+ }
113
+
114
+ fn normalize_changed_path(root: &Path, line: &str) -> Option<PathBuf> {
115
+ let path = normalize_against(root, Path::new(line));
116
+ path.starts_with(root).then_some(path)
117
+ }