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
package/src/fix.rs ADDED
@@ -0,0 +1,551 @@
1
+ use std::collections::BTreeSet;
2
+ use std::fmt::Write as _;
3
+ use std::fs;
4
+ use std::path::{Path, PathBuf};
5
+
6
+ use serde::{Deserialize, Serialize};
7
+
8
+ use crate::graph::normalize_path;
9
+ use crate::output::{Finding, FindingKind};
10
+
11
+ /// Stable JSON schema version for fix reports.
12
+ pub const FIX_SCHEMA_VERSION: &str = "dart-decimate.fix.v1";
13
+
14
+ /// Safe-fix execution mode.
15
+ #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
16
+ #[serde(rename_all = "kebab-case")]
17
+ pub enum FixMode {
18
+ /// Report planned fixes without writing files.
19
+ DryRun,
20
+ /// Apply planned fixes.
21
+ Apply,
22
+ }
23
+
24
+ /// Report emitted by `dart-decimate fix`.
25
+ #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
26
+ pub struct FixReport {
27
+ /// Schema identifier.
28
+ pub schema_version: String,
29
+ /// Tool name.
30
+ pub tool: String,
31
+ /// Typed JSON envelope kind.
32
+ pub kind: String,
33
+ /// Whether this was a dry-run or apply run.
34
+ pub mode: FixMode,
35
+ /// Numeric rollup.
36
+ pub summary: FixSummary,
37
+ /// Planned or applied fixes.
38
+ pub fixes: Vec<FixChange>,
39
+ /// Auto-fixable findings that were not safe to execute.
40
+ pub skipped: Vec<FixSkip>,
41
+ }
42
+
43
+ /// Numeric fix summary.
44
+ #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
45
+ pub struct FixSummary {
46
+ /// Planned fix count.
47
+ pub planned: usize,
48
+ /// Applied fix count.
49
+ pub applied: usize,
50
+ /// Skipped fix count.
51
+ pub skipped: usize,
52
+ }
53
+
54
+ /// One planned or applied fix.
55
+ #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
56
+ pub struct FixChange {
57
+ /// Stable action id.
58
+ pub action: String,
59
+ /// Root-relative file path.
60
+ pub path: String,
61
+ /// 1-based source line for the finding.
62
+ pub line: usize,
63
+ /// Human-readable fix description.
64
+ pub description: String,
65
+ /// Whether the fix was applied to disk.
66
+ pub applied: bool,
67
+ }
68
+
69
+ /// One skipped fix candidate.
70
+ #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
71
+ pub struct FixSkip {
72
+ /// Stable action id.
73
+ pub action: String,
74
+ /// Root-relative file path.
75
+ pub path: String,
76
+ /// 1-based source line for the finding.
77
+ pub line: usize,
78
+ /// Why the fix was skipped.
79
+ pub reason: String,
80
+ }
81
+
82
+ /// Plan or apply safe fixes from already-filtered findings.
83
+ #[must_use]
84
+ pub fn fix_findings(
85
+ root: &Path,
86
+ findings: &[Finding],
87
+ selected_actions: &BTreeSet<String>,
88
+ mode: FixMode,
89
+ ) -> FixReport {
90
+ let mut candidates = candidates(root, findings, selected_actions);
91
+ candidates.sort_by_key(candidate_order);
92
+
93
+ let mut fixes = Vec::new();
94
+ let mut skipped = Vec::new();
95
+ for candidate in candidates {
96
+ match validate_candidate(root, &candidate) {
97
+ Ok(()) => {
98
+ let applied = mode == FixMode::Apply
99
+ && apply_candidate(&candidate)
100
+ .map_err(|reason| {
101
+ skipped.push(FixSkip {
102
+ action: candidate.action.clone(),
103
+ path: candidate.path.clone(),
104
+ line: candidate.line,
105
+ reason,
106
+ });
107
+ })
108
+ .is_ok();
109
+ if mode == FixMode::DryRun || applied {
110
+ fixes.push(FixChange {
111
+ action: candidate.action,
112
+ path: candidate.path,
113
+ line: candidate.line,
114
+ description: candidate.description,
115
+ applied,
116
+ });
117
+ }
118
+ }
119
+ Err(reason) => skipped.push(FixSkip {
120
+ action: candidate.action,
121
+ path: candidate.path,
122
+ line: candidate.line,
123
+ reason,
124
+ }),
125
+ }
126
+ }
127
+
128
+ FixReport {
129
+ schema_version: FIX_SCHEMA_VERSION.to_owned(),
130
+ tool: "dart-decimate".to_owned(),
131
+ kind: "fix".to_owned(),
132
+ mode,
133
+ summary: FixSummary {
134
+ planned: fixes.len(),
135
+ applied: fixes.iter().filter(|fix| fix.applied).count(),
136
+ skipped: skipped.len(),
137
+ },
138
+ fixes,
139
+ skipped,
140
+ }
141
+ }
142
+
143
+ /// Render a human-readable fix report.
144
+ #[must_use]
145
+ pub fn render_fix_report(report: &FixReport) -> String {
146
+ let mode = match report.mode {
147
+ FixMode::DryRun => "dry-run",
148
+ FixMode::Apply => "apply",
149
+ };
150
+ let mut output = format!(
151
+ "Fix {mode}\nplanned: {}\napplied: {}\nskipped: {}\n",
152
+ report.summary.planned, report.summary.applied, report.summary.skipped
153
+ );
154
+ for fix in &report.fixes {
155
+ let status = if fix.applied { "applied" } else { "planned" };
156
+ let _ = write!(
157
+ output,
158
+ "\n{status} {} {}:{}\n{}",
159
+ fix.action, fix.path, fix.line, fix.description
160
+ );
161
+ }
162
+ for skip in &report.skipped {
163
+ let _ = write!(
164
+ output,
165
+ "\nskipped {} {}:{}\n{}",
166
+ skip.action, skip.path, skip.line, skip.reason
167
+ );
168
+ }
169
+ output.push('\n');
170
+ output
171
+ }
172
+
173
+ #[derive(Debug, Clone, PartialEq, Eq)]
174
+ struct FixCandidate {
175
+ action: String,
176
+ path: String,
177
+ absolute_path: PathBuf,
178
+ line: usize,
179
+ description: String,
180
+ kind: FindingKind,
181
+ safe_to_delete: bool,
182
+ target_path: Option<String>,
183
+ target_dependency: Option<String>,
184
+ target_end_line: Option<usize>,
185
+ config_key: Option<String>,
186
+ }
187
+
188
+ fn candidates(
189
+ root: &Path,
190
+ findings: &[Finding],
191
+ selected_actions: &BTreeSet<String>,
192
+ ) -> Vec<FixCandidate> {
193
+ findings
194
+ .iter()
195
+ .flat_map(|finding| {
196
+ finding
197
+ .actions
198
+ .iter()
199
+ .filter(|action| action.auto_fixable)
200
+ .filter(|action| {
201
+ selected_actions.is_empty() || selected_actions.contains(&action.action)
202
+ })
203
+ .map(|action| FixCandidate {
204
+ path: action
205
+ .target_path
206
+ .clone()
207
+ .unwrap_or_else(|| finding.path.clone()),
208
+ action: action.action.clone(),
209
+ absolute_path: resolve_finding_path(
210
+ root,
211
+ action.target_path.as_deref().unwrap_or(&finding.path),
212
+ ),
213
+ line: finding.line,
214
+ description: action.description.clone(),
215
+ kind: finding.kind,
216
+ safe_to_delete: finding.safe_to_delete,
217
+ target_path: action.target_path.clone(),
218
+ target_dependency: action.target_dependency.clone(),
219
+ target_end_line: action.target_end_line,
220
+ config_key: action.config_key.clone(),
221
+ })
222
+ })
223
+ .collect()
224
+ }
225
+
226
+ fn validate_candidate(root: &Path, candidate: &FixCandidate) -> Result<(), String> {
227
+ let normalized_root = normalize_path(root);
228
+ if !candidate.absolute_path.starts_with(&normalized_root) {
229
+ return Err("candidate path is outside the project root".to_owned());
230
+ }
231
+ match candidate.action.as_str() {
232
+ "delete-file" => validate_delete_file(candidate),
233
+ "remove-declaration" => validate_remove_declaration(candidate),
234
+ "remove-suppression" => validate_remove_suppression(candidate),
235
+ action if is_pubspec_dependency_action(action) => {
236
+ validate_remove_pubspec_dependency(candidate)
237
+ }
238
+ _ => Err(format!("unsupported safe fix action {}", candidate.action)),
239
+ }
240
+ }
241
+
242
+ fn validate_delete_file(candidate: &FixCandidate) -> Result<(), String> {
243
+ if candidate.kind != FindingKind::DeadFile {
244
+ return Err("delete-file only applies to dead-file findings".to_owned());
245
+ }
246
+ if candidate
247
+ .absolute_path
248
+ .extension()
249
+ .is_none_or(|ext| ext != "dart")
250
+ {
251
+ return Err("delete-file only removes Dart files".to_owned());
252
+ }
253
+ let metadata =
254
+ fs::symlink_metadata(&candidate.absolute_path).map_err(|error| error.to_string())?;
255
+ if metadata.file_type().is_symlink() {
256
+ return Err("refusing to delete a symlink".to_owned());
257
+ }
258
+ if !metadata.is_file() {
259
+ return Err("delete-file target is not a regular file".to_owned());
260
+ }
261
+ Ok(())
262
+ }
263
+
264
+ fn validate_remove_declaration(candidate: &FixCandidate) -> Result<(), String> {
265
+ if !matches!(
266
+ candidate.kind,
267
+ FindingKind::UnusedExport | FindingKind::UnusedType
268
+ ) {
269
+ return Err("remove-declaration only applies to unused top-level symbols".to_owned());
270
+ }
271
+ if !candidate.safe_to_delete {
272
+ return Err("unused symbol finding is not marked safe_to_delete".to_owned());
273
+ }
274
+ if candidate.target_path.is_none() {
275
+ return Err("remove-declaration requires action.target_path".to_owned());
276
+ }
277
+ if candidate.target_end_line.unwrap_or(candidate.line) != candidate.line {
278
+ return Err("multi-line declarations are not auto-fixable".to_owned());
279
+ }
280
+ validate_dart_source_target(candidate)?;
281
+ let source = fs::read_to_string(&candidate.absolute_path).map_err(|error| error.to_string())?;
282
+ validate_declaration_line(&source, candidate.line)
283
+ }
284
+
285
+ fn validate_remove_suppression(candidate: &FixCandidate) -> Result<(), String> {
286
+ if candidate.kind != FindingKind::StaleSuppression {
287
+ return Err("remove-suppression only applies to stale-suppression findings".to_owned());
288
+ }
289
+ if candidate.line == 0 {
290
+ return Err("suppression line must be 1-based".to_owned());
291
+ }
292
+ if !candidate.absolute_path.is_file() {
293
+ return Err("suppression file does not exist".to_owned());
294
+ }
295
+ Ok(())
296
+ }
297
+
298
+ fn validate_remove_pubspec_dependency(candidate: &FixCandidate) -> Result<(), String> {
299
+ let section = dependency_section_for_kind(candidate.kind)?;
300
+ if !candidate.safe_to_delete {
301
+ return Err("unused dependency finding is not marked safe_to_delete".to_owned());
302
+ }
303
+ if candidate.target_path.is_none() {
304
+ return Err("remove-pubspec-dependency requires action.target_path".to_owned());
305
+ }
306
+ if candidate.config_key.as_deref() != Some(section) {
307
+ return Err(format!(
308
+ "remove-pubspec-dependency requires action.config_key {section}"
309
+ ));
310
+ }
311
+ let metadata =
312
+ fs::symlink_metadata(&candidate.absolute_path).map_err(|error| error.to_string())?;
313
+ if metadata.file_type().is_symlink() {
314
+ return Err("refusing to edit a symlinked pubspec.yaml".to_owned());
315
+ }
316
+ if !metadata.is_file() {
317
+ return Err("pubspec dependency target is not a regular file".to_owned());
318
+ }
319
+ if candidate
320
+ .absolute_path
321
+ .file_name()
322
+ .and_then(|name| name.to_str())
323
+ != Some("pubspec.yaml")
324
+ {
325
+ return Err("remove-pubspec-dependency target must be pubspec.yaml".to_owned());
326
+ }
327
+ let source = fs::read_to_string(&candidate.absolute_path).map_err(|error| error.to_string())?;
328
+ validate_pubspec_dependency_source(&source, candidate, section)
329
+ }
330
+
331
+ fn apply_candidate(candidate: &FixCandidate) -> Result<(), String> {
332
+ match candidate.action.as_str() {
333
+ "delete-file" => {
334
+ fs::remove_file(&candidate.absolute_path).map_err(|error| error.to_string())
335
+ }
336
+ "remove-declaration" => remove_declaration(candidate),
337
+ "remove-suppression" => remove_line(&candidate.absolute_path, candidate.line),
338
+ action if is_pubspec_dependency_action(action) => remove_pubspec_dependency(candidate),
339
+ _ => Err(format!("unsupported safe fix action {}", candidate.action)),
340
+ }
341
+ }
342
+
343
+ fn remove_declaration(candidate: &FixCandidate) -> Result<(), String> {
344
+ validate_remove_declaration(candidate)?;
345
+ remove_line(&candidate.absolute_path, candidate.line)
346
+ }
347
+
348
+ fn remove_pubspec_dependency(candidate: &FixCandidate) -> Result<(), String> {
349
+ let section = dependency_section_for_kind(candidate.kind)?;
350
+ let source = fs::read_to_string(&candidate.absolute_path).map_err(|error| error.to_string())?;
351
+ validate_pubspec_dependency_source(&source, candidate, section)?;
352
+ remove_line(&candidate.absolute_path, candidate.line)
353
+ }
354
+
355
+ fn remove_line(path: &Path, line: usize) -> Result<(), String> {
356
+ let source = fs::read_to_string(path).map_err(|error| error.to_string())?;
357
+ let mut lines = source
358
+ .split_inclusive('\n')
359
+ .map(str::to_owned)
360
+ .collect::<Vec<_>>();
361
+ if line == 0 || line > lines.len() {
362
+ return Err("suppression line is outside the file".to_owned());
363
+ }
364
+ lines.remove(line - 1);
365
+ fs::write(path, lines.concat()).map_err(|error| error.to_string())
366
+ }
367
+
368
+ fn validate_pubspec_dependency_source(
369
+ source: &str,
370
+ candidate: &FixCandidate,
371
+ section: &str,
372
+ ) -> Result<(), String> {
373
+ let dependency = candidate
374
+ .target_dependency
375
+ .as_deref()
376
+ .ok_or_else(|| "remove-pubspec-dependency requires action.target_dependency".to_owned())?;
377
+ let lines = source.split_inclusive('\n').collect::<Vec<_>>();
378
+ if candidate.line == 0 || candidate.line > lines.len() {
379
+ return Err("dependency line is outside pubspec.yaml".to_owned());
380
+ }
381
+ validate_simple_pubspec_dependency_line(&lines, candidate.line - 1, dependency, section)
382
+ }
383
+
384
+ fn validate_simple_pubspec_dependency_line(
385
+ lines: &[&str],
386
+ index: usize,
387
+ dependency: &str,
388
+ section: &str,
389
+ ) -> Result<(), String> {
390
+ let line = lines[index];
391
+ if line.contains('#') {
392
+ return Err("dependency entries with comments are not auto-fixable".to_owned());
393
+ }
394
+ let indent = indentation(line)?;
395
+ if indent == 0 {
396
+ return Err(
397
+ "dependency entry must be nested under dependencies or dev_dependencies".to_owned(),
398
+ );
399
+ }
400
+ let actual_section = enclosing_pubspec_section(lines, index, indent)?;
401
+ if actual_section != section {
402
+ return Err(format!(
403
+ "dependency entry is under {actual_section}, expected {section}"
404
+ ));
405
+ }
406
+ let trimmed = line.trim();
407
+ let (key, value) = trimmed
408
+ .split_once(':')
409
+ .ok_or_else(|| "dependency entry is not a YAML key-value line".to_owned())?;
410
+ if key.trim() != dependency {
411
+ return Err(format!(
412
+ "dependency entry key {} does not match target_dependency {dependency}",
413
+ key.trim()
414
+ ));
415
+ }
416
+ let value = value.trim();
417
+ if value.is_empty() {
418
+ return Err("nested dependency entries are not auto-fixable".to_owned());
419
+ }
420
+ if value.contains('{')
421
+ || value.contains('}')
422
+ || value.contains('[')
423
+ || value.contains(']')
424
+ || value.contains("path:")
425
+ || value.contains("git:")
426
+ || value.contains("sdk:")
427
+ {
428
+ return Err("path/git/sdk/map dependency entries are not auto-fixable".to_owned());
429
+ }
430
+ Ok(())
431
+ }
432
+
433
+ fn validate_dart_source_target(candidate: &FixCandidate) -> Result<(), String> {
434
+ let metadata =
435
+ fs::symlink_metadata(&candidate.absolute_path).map_err(|error| error.to_string())?;
436
+ if metadata.file_type().is_symlink() {
437
+ return Err("refusing to edit a symlinked Dart file".to_owned());
438
+ }
439
+ if !metadata.is_file() {
440
+ return Err("Dart declaration target is not a regular file".to_owned());
441
+ }
442
+ if candidate
443
+ .absolute_path
444
+ .extension()
445
+ .is_none_or(|extension| extension != "dart")
446
+ {
447
+ return Err("remove-declaration target must be a Dart file".to_owned());
448
+ }
449
+ Ok(())
450
+ }
451
+
452
+ fn validate_declaration_line(source: &str, line: usize) -> Result<(), String> {
453
+ let lines = source.split_inclusive('\n').collect::<Vec<_>>();
454
+ if line == 0 || line > lines.len() {
455
+ return Err("declaration line is outside the file".to_owned());
456
+ }
457
+ let trimmed = lines[line - 1].trim();
458
+ if trimmed.is_empty() || trimmed.starts_with("//") {
459
+ return Err("declaration line is not executable Dart source".to_owned());
460
+ }
461
+ if trimmed.starts_with("import ")
462
+ || trimmed.starts_with("export ")
463
+ || trimmed.starts_with("part ")
464
+ || trimmed.starts_with("library ")
465
+ {
466
+ return Err("remove-declaration refuses to edit Dart directives".to_owned());
467
+ }
468
+ if !(trimmed.ends_with(';') || trimmed.ends_with('}')) {
469
+ return Err("declaration line is not a complete one-line declaration".to_owned());
470
+ }
471
+ Ok(())
472
+ }
473
+
474
+ fn enclosing_pubspec_section(
475
+ lines: &[&str],
476
+ index: usize,
477
+ target_indent: usize,
478
+ ) -> Result<String, String> {
479
+ for line in lines[..index].iter().rev() {
480
+ let trimmed = line.trim();
481
+ if trimmed.is_empty() || trimmed.starts_with('#') {
482
+ continue;
483
+ }
484
+ let indent = indentation(line)?;
485
+ if indent >= target_indent {
486
+ continue;
487
+ }
488
+ if indent != 0 {
489
+ return Err("dependency entry is nested below another map".to_owned());
490
+ }
491
+ let (key, value) = trimmed
492
+ .split_once(':')
493
+ .ok_or_else(|| "dependency entry is not under a pubspec section".to_owned())?;
494
+ if !value.trim().is_empty() {
495
+ return Err(
496
+ "dependency entry is not under dependencies or dev_dependencies".to_owned(),
497
+ );
498
+ }
499
+ return Ok(key.trim().to_owned());
500
+ }
501
+ Err("dependency entry is not under dependencies or dev_dependencies".to_owned())
502
+ }
503
+
504
+ fn indentation(line: &str) -> Result<usize, String> {
505
+ let mut spaces = 0;
506
+ for character in line.chars() {
507
+ match character {
508
+ ' ' => spaces += 1,
509
+ '\t' => return Err("tab-indented pubspec entries are not auto-fixable".to_owned()),
510
+ _ => return Ok(spaces),
511
+ }
512
+ }
513
+ Ok(spaces)
514
+ }
515
+
516
+ fn dependency_section_for_kind(kind: FindingKind) -> Result<&'static str, String> {
517
+ match kind {
518
+ FindingKind::UnusedDependency => Ok("dependencies"),
519
+ FindingKind::UnusedDevDependency => Ok("dev_dependencies"),
520
+ _ => Err(
521
+ "remove-pubspec-dependency only applies to unused pub dependency findings".to_owned(),
522
+ ),
523
+ }
524
+ }
525
+
526
+ fn is_pubspec_dependency_action(action: &str) -> bool {
527
+ action == "remove-pubspec-dependency"
528
+ }
529
+
530
+ fn resolve_finding_path(root: &Path, path: &str) -> PathBuf {
531
+ let path = Path::new(path);
532
+ if path.is_absolute() {
533
+ normalize_path(path)
534
+ } else {
535
+ normalize_path(&root.join(path))
536
+ }
537
+ }
538
+
539
+ fn candidate_order(candidate: &FixCandidate) -> (u8, String, std::cmp::Reverse<usize>, String) {
540
+ let group = match candidate.action.as_str() {
541
+ "remove-suppression" => 0,
542
+ action if action == "remove-declaration" || is_pubspec_dependency_action(action) => 1,
543
+ _ => 2,
544
+ };
545
+ (
546
+ group,
547
+ candidate.path.clone(),
548
+ std::cmp::Reverse(candidate.line),
549
+ candidate.action.clone(),
550
+ )
551
+ }
@@ -0,0 +1,53 @@
1
+ use std::path::Path;
2
+
3
+ pub(crate) const GENERATED_DART_SUFFIXES: &[&str] = &[
4
+ ".g.dart",
5
+ ".freezed.dart",
6
+ ".gen.dart",
7
+ ".gr.dart",
8
+ ".mocks.dart",
9
+ ];
10
+
11
+ #[must_use]
12
+ pub(crate) fn is_generated_dart_path(path: &Path) -> bool {
13
+ path.file_name()
14
+ .and_then(|name| name.to_str())
15
+ .is_some_and(is_generated_dart_file_name)
16
+ }
17
+
18
+ #[must_use]
19
+ pub(crate) fn is_generated_dart_file_name(name: &str) -> bool {
20
+ GENERATED_DART_SUFFIXES
21
+ .iter()
22
+ .any(|suffix| name.ends_with(suffix))
23
+ }
24
+
25
+ #[cfg(test)]
26
+ mod tests {
27
+ use std::path::Path;
28
+
29
+ use super::*;
30
+
31
+ #[test]
32
+ fn recognizes_common_dart_generated_companions() {
33
+ for file_name in [
34
+ "model.g.dart",
35
+ "model.freezed.dart",
36
+ "l10n.gen.dart",
37
+ "routes.gr.dart",
38
+ "service.mocks.dart",
39
+ ] {
40
+ assert!(is_generated_dart_file_name(file_name), "{file_name}");
41
+ assert!(is_generated_dart_path(
42
+ Path::new("lib").join(file_name).as_path()
43
+ ));
44
+ }
45
+ }
46
+
47
+ #[test]
48
+ fn rejects_regular_dart_sources() {
49
+ for file_name in ["main.dart", "mock_service.dart", "generated.dart"] {
50
+ assert!(!is_generated_dart_file_name(file_name), "{file_name}");
51
+ }
52
+ }
53
+ }