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,555 @@
1
+ use std::collections::{BTreeMap, BTreeSet};
2
+ use std::fs;
3
+ use std::path::{Path, PathBuf};
4
+ use std::process::Command;
5
+
6
+ use petgraph::visit::EdgeRef;
7
+ use thiserror::Error;
8
+
9
+ use crate::graph::normalize_against;
10
+ use crate::output::{FindingKind, JsonReport, JsonSecurityOccurrence, Severity, Verdict};
11
+ use crate::{ModuleGraph, find_dead_code};
12
+
13
+ /// Fallow-style security review gate mode.
14
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
15
+ pub(crate) enum SecurityGateMode {
16
+ /// Fail only on candidates introduced by added diff lines.
17
+ New,
18
+ /// Fail when changed code makes a candidate newly reachable.
19
+ NewlyReachable,
20
+ }
21
+
22
+ /// Source for line-level security gate scope.
23
+ #[derive(Debug, Clone, PartialEq, Eq)]
24
+ pub(crate) enum SecurityDiffSource {
25
+ /// Read a unified diff from a file.
26
+ File(PathBuf),
27
+ /// Read a unified diff from standard input.
28
+ Stdin,
29
+ }
30
+
31
+ /// Errors returned while applying a security gate.
32
+ #[derive(Debug, Error)]
33
+ pub enum SecurityGateError {
34
+ /// Security gates need an explicit diff.
35
+ #[error(
36
+ "security --gate new or newly-reachable requires --diff-file PATH, --diff-stdin, or --changed-since REF"
37
+ )]
38
+ MissingDiffFile,
39
+ /// Diff file could not be read.
40
+ #[error("failed to read diff file {path}: {source}")]
41
+ ReadDiff {
42
+ /// Diff path.
43
+ path: PathBuf,
44
+ /// Underlying IO error.
45
+ source: std::io::Error,
46
+ },
47
+ /// Git could not be executed.
48
+ #[error("failed to run git diff for security gate: {source}")]
49
+ Git {
50
+ /// Underlying IO error.
51
+ source: std::io::Error,
52
+ },
53
+ /// Git returned a non-zero status.
54
+ #[error("git diff failed for security gate base {base:?}: {stderr}")]
55
+ GitDiff {
56
+ /// Base revision passed by the caller.
57
+ base: String,
58
+ /// Stderr from git.
59
+ stderr: String,
60
+ },
61
+ /// Untracked file scope could not be read.
62
+ #[error("failed to read untracked file {path}: {source}")]
63
+ ReadUntracked {
64
+ /// File path.
65
+ path: PathBuf,
66
+ /// Underlying IO error.
67
+ source: std::io::Error,
68
+ },
69
+ }
70
+
71
+ #[derive(Debug, Clone, Default, PartialEq, Eq)]
72
+ pub(crate) struct ChangedLineScope {
73
+ lines: BTreeMap<String, BTreeSet<usize>>,
74
+ }
75
+
76
+ impl ChangedLineScope {
77
+ fn insert(&mut self, path: &str, line: usize) {
78
+ self.lines.entry(path.to_owned()).or_default().insert(line);
79
+ }
80
+
81
+ fn contains(&self, path: &str, line: usize) -> bool {
82
+ self.lines
83
+ .get(path)
84
+ .is_some_and(|lines| lines.contains(&line))
85
+ }
86
+
87
+ fn paths(&self) -> impl Iterator<Item = &str> {
88
+ self.lines.keys().map(String::as_str)
89
+ }
90
+ }
91
+
92
+ /// Load changed-line scope from a unified diff file.
93
+ ///
94
+ /// # Errors
95
+ ///
96
+ /// Returns [`SecurityGateError`] if the diff cannot be read.
97
+ pub(crate) fn changed_lines_from_diff_file(
98
+ root: &Path,
99
+ path: &Path,
100
+ ) -> Result<ChangedLineScope, SecurityGateError> {
101
+ let source = fs::read_to_string(path).map_err(|source| SecurityGateError::ReadDiff {
102
+ path: path.to_path_buf(),
103
+ source,
104
+ })?;
105
+ Ok(changed_lines_from_unified_diff(root, &source))
106
+ }
107
+
108
+ /// Load changed-line scope from a unified diff string.
109
+ pub(crate) fn changed_lines_from_diff(root: &Path, source: &str) -> ChangedLineScope {
110
+ changed_lines_from_unified_diff(root, source)
111
+ }
112
+
113
+ /// Load changed-line scope from Git changes since `base`.
114
+ ///
115
+ /// # Errors
116
+ ///
117
+ /// Returns [`SecurityGateError`] if Git fails or an untracked file cannot be read.
118
+ pub(crate) fn changed_lines_from_git(
119
+ root: &Path,
120
+ base: &str,
121
+ ) -> Result<ChangedLineScope, SecurityGateError> {
122
+ let output = Command::new("git")
123
+ .args(["diff", "--unified=0", "--diff-filter=ACMRTUXB", base, "--"])
124
+ .current_dir(root)
125
+ .output()
126
+ .map_err(|source| SecurityGateError::Git { source })?;
127
+
128
+ if !output.status.success() {
129
+ return Err(SecurityGateError::GitDiff {
130
+ base: base.to_owned(),
131
+ stderr: String::from_utf8_lossy(&output.stderr).trim().to_owned(),
132
+ });
133
+ }
134
+
135
+ let mut scope =
136
+ changed_lines_from_unified_diff(root, String::from_utf8_lossy(&output.stdout).as_ref());
137
+ add_untracked_lines(root, base, &mut scope)?;
138
+ Ok(scope)
139
+ }
140
+
141
+ /// Restrict a security report to candidates introduced by changed lines.
142
+ pub(crate) fn apply_changed_line_gate(report: &mut JsonReport, scope: &ChangedLineScope) {
143
+ apply_security_occurrence_filter(report, |path, line| scope.contains(path, line));
144
+ }
145
+
146
+ /// Restrict a security report to reachable candidates affected by changed files.
147
+ pub(crate) fn apply_changed_reachability_gate<P>(
148
+ root: &Path,
149
+ graph: &ModuleGraph,
150
+ report: &mut JsonReport,
151
+ entry_points: impl IntoIterator<Item = P>,
152
+ scope: &ChangedLineScope,
153
+ ) where
154
+ P: AsRef<Path>,
155
+ {
156
+ let reachable = find_dead_code(graph, entry_points)
157
+ .reachable_files
158
+ .into_iter()
159
+ .collect::<BTreeSet<_>>();
160
+ let affected = downstream_changed_files(root, graph, scope);
161
+ let visible = affected
162
+ .into_iter()
163
+ .filter(|path| reachable.contains(path))
164
+ .map(|path| display_path(root, &path))
165
+ .collect::<BTreeSet<_>>();
166
+ apply_security_occurrence_filter(report, |path, _line| visible.contains(path));
167
+ }
168
+
169
+ fn apply_security_occurrence_filter<F>(report: &mut JsonReport, mut keep: F)
170
+ where
171
+ F: FnMut(&str, usize) -> bool,
172
+ {
173
+ let mut changed = BTreeMap::<String, ChangedCandidate>::new();
174
+ report.security_candidates.retain_mut(|candidate| {
175
+ candidate
176
+ .occurrences
177
+ .retain(|occurrence| keep(&occurrence.path, occurrence.line));
178
+ if candidate.occurrences.is_empty() {
179
+ return false;
180
+ }
181
+ changed.insert(
182
+ candidate.fingerprint.clone(),
183
+ ChangedCandidate::from_occurrences(&candidate.occurrences),
184
+ );
185
+ true
186
+ });
187
+ report
188
+ .attack_surface
189
+ .retain(|entry| keep(&entry.path, entry.line));
190
+ report.findings.retain_mut(|finding| {
191
+ if finding.kind != FindingKind::SecurityCandidate {
192
+ return false;
193
+ }
194
+ let Some(fingerprint) = finding.fingerprint.as_ref() else {
195
+ return keep(&finding.path, finding.line);
196
+ };
197
+ let Some(candidate) = changed.get(fingerprint) else {
198
+ return false;
199
+ };
200
+ finding.path.clone_from(&candidate.primary.path);
201
+ finding.line = candidate.primary.line;
202
+ finding.column = candidate.primary.column;
203
+ finding.files.clone_from(&candidate.files);
204
+ for action in &mut finding.actions {
205
+ if action.target_path.is_some() {
206
+ action.target_path = Some(candidate.primary.path.clone());
207
+ }
208
+ if action.command.is_some() || !action.argv.is_empty() {
209
+ action.argv = vec![
210
+ "dart-decimate".to_owned(),
211
+ "inspect".to_owned(),
212
+ "--format".to_owned(),
213
+ "json".to_owned(),
214
+ "--file".to_owned(),
215
+ candidate.primary.path.clone(),
216
+ ];
217
+ action.command = Some(shell_command(&action.argv));
218
+ }
219
+ }
220
+ true
221
+ });
222
+ report.next_steps.clear();
223
+ recompute_summary(report);
224
+ }
225
+
226
+ fn downstream_changed_files(
227
+ root: &Path,
228
+ graph: &ModuleGraph,
229
+ scope: &ChangedLineScope,
230
+ ) -> BTreeSet<PathBuf> {
231
+ let mut pending = scope
232
+ .paths()
233
+ .filter_map(|path| graph.node_index(normalize_against(root, Path::new(path))))
234
+ .collect::<Vec<_>>();
235
+ let mut affected = BTreeSet::new();
236
+
237
+ while let Some(node) = pending.pop() {
238
+ if !affected.insert(graph.graph()[node].path.clone()) {
239
+ continue;
240
+ }
241
+ pending.extend(graph.graph().edges(node).map(|edge| edge.target()));
242
+ }
243
+
244
+ affected
245
+ }
246
+
247
+ fn display_path(root: &Path, path: &Path) -> String {
248
+ let normalized = normalize_against(root, path);
249
+ normalized
250
+ .strip_prefix(root)
251
+ .unwrap_or(&normalized)
252
+ .to_string_lossy()
253
+ .replace('\\', "/")
254
+ }
255
+
256
+ fn add_untracked_lines(
257
+ root: &Path,
258
+ base: &str,
259
+ scope: &mut ChangedLineScope,
260
+ ) -> Result<(), SecurityGateError> {
261
+ let output = Command::new("git")
262
+ .args(["ls-files", "--others", "--exclude-standard"])
263
+ .current_dir(root)
264
+ .output()
265
+ .map_err(|source| SecurityGateError::Git { source })?;
266
+
267
+ if !output.status.success() {
268
+ return Err(SecurityGateError::GitDiff {
269
+ base: base.to_owned(),
270
+ stderr: String::from_utf8_lossy(&output.stderr).trim().to_owned(),
271
+ });
272
+ }
273
+
274
+ for line in output.stdout.split(|byte| *byte == b'\n') {
275
+ let Some(path) = std::str::from_utf8(line)
276
+ .ok()
277
+ .map(str::trim)
278
+ .filter(|path| !path.is_empty())
279
+ .and_then(|path| normalize_untracked_path(root, path))
280
+ else {
281
+ continue;
282
+ };
283
+ add_file_lines(root, &path, scope)?;
284
+ }
285
+
286
+ Ok(())
287
+ }
288
+
289
+ fn add_file_lines(
290
+ root: &Path,
291
+ display_path: &str,
292
+ scope: &mut ChangedLineScope,
293
+ ) -> Result<(), SecurityGateError> {
294
+ let path = root.join(display_path);
295
+ let source = fs::read_to_string(&path).map_err(|source| SecurityGateError::ReadUntracked {
296
+ path: path.clone(),
297
+ source,
298
+ })?;
299
+ for line in 1..=source.lines().count() {
300
+ scope.insert(display_path, line);
301
+ }
302
+ Ok(())
303
+ }
304
+
305
+ fn changed_lines_from_unified_diff(root: &Path, diff: &str) -> ChangedLineScope {
306
+ let mut scope = ChangedLineScope::default();
307
+ let mut current_path = None::<String>;
308
+ let mut new_line = 0usize;
309
+ let mut in_hunk = false;
310
+
311
+ for line in diff.lines() {
312
+ if let Some(raw_path) = line.strip_prefix("+++ ") {
313
+ current_path = normalize_diff_path(root, raw_path);
314
+ in_hunk = false;
315
+ continue;
316
+ }
317
+ if let Some(start) = parse_new_hunk_start(line) {
318
+ new_line = start;
319
+ in_hunk = current_path.is_some();
320
+ continue;
321
+ }
322
+ if !in_hunk {
323
+ continue;
324
+ }
325
+ if line.starts_with('+') {
326
+ if let Some(path) = current_path.as_deref() {
327
+ scope.insert(path, new_line);
328
+ }
329
+ new_line += 1;
330
+ } else if !line.starts_with('-') && !line.starts_with('\\') {
331
+ new_line += 1;
332
+ }
333
+ }
334
+
335
+ scope
336
+ }
337
+
338
+ fn parse_new_hunk_start(line: &str) -> Option<usize> {
339
+ let hunk = line.strip_prefix("@@ ")?;
340
+ let plus = hunk.find('+')?;
341
+ let after_plus = &hunk[plus + 1..];
342
+ let digits = after_plus
343
+ .chars()
344
+ .take_while(char::is_ascii_digit)
345
+ .collect::<String>();
346
+ digits.parse().ok()
347
+ }
348
+
349
+ fn normalize_diff_path(root: &Path, raw: &str) -> Option<String> {
350
+ let token = raw.trim().split('\t').next()?.trim();
351
+ if token == "/dev/null" || token.is_empty() {
352
+ return None;
353
+ }
354
+ let token = token
355
+ .strip_prefix("a/")
356
+ .or_else(|| token.strip_prefix("b/"))
357
+ .unwrap_or(token)
358
+ .strip_prefix("./")
359
+ .unwrap_or_else(|| {
360
+ token
361
+ .strip_prefix("a/")
362
+ .or_else(|| token.strip_prefix("b/"))
363
+ .unwrap_or(token)
364
+ });
365
+ let path = Path::new(token);
366
+ let relative = if path.is_absolute() {
367
+ path.strip_prefix(root).ok()?
368
+ } else {
369
+ path
370
+ };
371
+ Some(relative.to_string_lossy().replace('\\', "/"))
372
+ }
373
+
374
+ fn normalize_untracked_path(root: &Path, raw: &str) -> Option<String> {
375
+ let path = normalize_against(root, Path::new(raw));
376
+ let relative = path.strip_prefix(root).ok()?;
377
+ Some(relative.to_string_lossy().replace('\\', "/"))
378
+ }
379
+
380
+ #[derive(Debug, Clone, PartialEq, Eq)]
381
+ struct ChangedCandidate {
382
+ primary: JsonSecurityOccurrence,
383
+ files: Vec<String>,
384
+ }
385
+
386
+ impl ChangedCandidate {
387
+ fn from_occurrences(occurrences: &[JsonSecurityOccurrence]) -> Self {
388
+ let primary = occurrences[0].clone();
389
+ let files = occurrences
390
+ .iter()
391
+ .map(|occurrence| occurrence.path.clone())
392
+ .collect::<BTreeSet<_>>()
393
+ .into_iter()
394
+ .collect();
395
+ Self { primary, files }
396
+ }
397
+ }
398
+
399
+ fn recompute_summary(report: &mut JsonReport) {
400
+ report.summary.unresolved_dependencies = kind_count(report, FindingKind::UnresolvedDependency);
401
+ report.summary.part_of_violations = kind_count(report, FindingKind::PartOfViolation);
402
+ report.summary.unused_dependencies = dependency_count(report);
403
+ report.summary.unused_dev_dependencies = kind_count(report, FindingKind::UnusedDevDependency);
404
+ report.summary.test_only_dependencies = kind_count(report, FindingKind::TestOnlyDependency);
405
+ report.summary.dependency_overrides = kind_count(report, FindingKind::UnusedDependencyOverride)
406
+ + kind_count(report, FindingKind::MisconfiguredDependencyOverride);
407
+ report.summary.unused_dependency_overrides =
408
+ kind_count(report, FindingKind::UnusedDependencyOverride);
409
+ report.summary.misconfigured_dependency_overrides =
410
+ kind_count(report, FindingKind::MisconfiguredDependencyOverride);
411
+ report.summary.unlisted_dependencies = kind_count(report, FindingKind::UnlistedDependency);
412
+ report.summary.private_src_imports = kind_count(report, FindingKind::PrivateSrcImport);
413
+ report.summary.dead_files = kind_count(report, FindingKind::DeadFile);
414
+ report.summary.unused_exports = kind_count(report, FindingKind::UnusedExport);
415
+ report.summary.unused_types = kind_count(report, FindingKind::UnusedType);
416
+ report.summary.private_type_leaks = kind_count(report, FindingKind::PrivateTypeLeak);
417
+ report.summary.unused_enum_members = kind_count(report, FindingKind::UnusedEnumMember);
418
+ report.summary.unused_class_members = kind_count(report, FindingKind::UnusedClassMember);
419
+ report.summary.duplicate_exports = kind_count(report, FindingKind::DuplicateExport);
420
+ report.summary.route_collisions = kind_count(report, FindingKind::RouteCollision);
421
+ report.summary.private_widget_classes = kind_count(report, FindingKind::PrivateWidgetClass);
422
+ report.summary.widget_top_level_functions =
423
+ kind_count(report, FindingKind::WidgetTopLevelFunctionBoundary);
424
+ report.summary.unused_widget_params = kind_count(report, FindingKind::UnusedWidgetParam);
425
+ report.summary.unrendered_widgets = kind_count(report, FindingKind::UnrenderedWidget);
426
+ report.summary.missing_context_mounted_after_await =
427
+ kind_count(report, FindingKind::MissingContextMountedAfterAwait);
428
+ report.summary.code_duplications = report.clone_groups.len();
429
+ report.summary.complex_functions = complexity_count(report);
430
+ report.summary.coverage_gaps = kind_count(report, FindingKind::CoverageGap);
431
+ report.summary.crap_functions = kind_count(report, FindingKind::HighCrapScore);
432
+ report.summary.file_scores = report.file_scores.len();
433
+ report.summary.hotspots = report.hotspots.len();
434
+ report.summary.refactoring_targets = report.refactoring_targets.len();
435
+ report.summary.feature_flags = report.feature_flags.len();
436
+ report.summary.feature_flag_occurrences = report
437
+ .feature_flags
438
+ .iter()
439
+ .map(|flag| flag.occurrences.len())
440
+ .sum();
441
+ report.summary.security_candidates = report.security_candidates.len();
442
+ report.summary.security_candidate_occurrences = report
443
+ .security_candidates
444
+ .iter()
445
+ .map(|candidate| candidate.occurrences.len())
446
+ .sum();
447
+ report.summary.attack_surface = report.attack_surface.len();
448
+ report.summary.missing_entry_points = kind_count(report, FindingKind::MissingEntryPoint);
449
+ report.summary.cycles = kind_count(report, FindingKind::CircularDependency);
450
+ report.summary.re_export_cycles = kind_count(report, FindingKind::ReExportCycle);
451
+ report.summary.boundary_violations = kind_count(report, FindingKind::BoundaryViolation);
452
+ report.summary.boundary_coverage = kind_count(report, FindingKind::BoundaryCoverage);
453
+ report.summary.boundary_call_violations =
454
+ kind_count(report, FindingKind::BoundaryCallViolation);
455
+ report.summary.policy_violations = kind_count(report, FindingKind::PolicyViolation);
456
+ report.summary.missing_suppression_reasons =
457
+ kind_count(report, FindingKind::MissingSuppressionReason);
458
+ report.summary.findings = report.findings.len();
459
+ report.verdict = if report
460
+ .findings
461
+ .iter()
462
+ .any(|finding| finding.severity == Severity::Error)
463
+ {
464
+ Verdict::Fail
465
+ } else {
466
+ Verdict::Pass
467
+ };
468
+ }
469
+
470
+ fn kind_count(report: &JsonReport, kind: FindingKind) -> usize {
471
+ report
472
+ .findings
473
+ .iter()
474
+ .filter(|finding| finding.kind == kind)
475
+ .count()
476
+ }
477
+
478
+ fn dependency_count(report: &JsonReport) -> usize {
479
+ report
480
+ .findings
481
+ .iter()
482
+ .filter(|finding| {
483
+ matches!(
484
+ finding.kind,
485
+ FindingKind::UnusedDependency
486
+ | FindingKind::UnusedDevDependency
487
+ | FindingKind::TestOnlyDependency
488
+ | FindingKind::UnusedDependencyOverride
489
+ )
490
+ })
491
+ .count()
492
+ }
493
+
494
+ fn complexity_count(report: &JsonReport) -> usize {
495
+ report
496
+ .findings
497
+ .iter()
498
+ .filter(|finding| {
499
+ matches!(
500
+ finding.kind,
501
+ FindingKind::HighCyclomaticComplexity
502
+ | FindingKind::HighCognitiveComplexity
503
+ | FindingKind::HighComplexity
504
+ | FindingKind::HighCrapScore
505
+ )
506
+ })
507
+ .count()
508
+ }
509
+
510
+ fn shell_command(argv: &[String]) -> String {
511
+ argv.iter()
512
+ .map(|arg| shell_escape(arg))
513
+ .collect::<Vec<_>>()
514
+ .join(" ")
515
+ }
516
+
517
+ fn shell_escape(arg: &str) -> String {
518
+ if arg.chars().all(is_shell_safe) {
519
+ return arg.to_owned();
520
+ }
521
+ format!("'{}'", arg.replace('\'', "'\"'\"'"))
522
+ }
523
+
524
+ fn is_shell_safe(character: char) -> bool {
525
+ character.is_ascii_alphanumeric()
526
+ || matches!(
527
+ character,
528
+ '/' | '.' | ':' | '_' | '-' | '=' | '+' | ',' | '@'
529
+ )
530
+ }
531
+
532
+ #[cfg(test)]
533
+ mod tests {
534
+ use super::*;
535
+
536
+ #[test]
537
+ fn parses_added_lines_from_git_diff() {
538
+ let scope = changed_lines_from_unified_diff(
539
+ Path::new("/repo"),
540
+ "diff --git a/lib/main.dart b/lib/main.dart
541
+ --- a/lib/main.dart
542
+ +++ b/lib/main.dart
543
+ @@ -1,2 +1,3 @@
544
+ context
545
+ +added
546
+ -removed
547
+ +second
548
+ ",
549
+ );
550
+
551
+ assert!(scope.contains("lib/main.dart", 2));
552
+ assert!(scope.contains("lib/main.dart", 3));
553
+ assert!(!scope.contains("lib/main.dart", 1));
554
+ }
555
+ }
@@ -0,0 +1,27 @@
1
+ use std::path::Path;
2
+
3
+ pub(super) fn is_private(name: &str) -> bool {
4
+ name.starts_with('_')
5
+ }
6
+
7
+ pub(super) fn is_library_source(root: &Path, path: &Path) -> bool {
8
+ path.strip_prefix(root).is_ok_and(|relative| {
9
+ relative
10
+ .components()
11
+ .next()
12
+ .is_some_and(|component| component.as_os_str() == "lib")
13
+ })
14
+ }
15
+
16
+ pub(super) fn is_public_library_entry(root: &Path, path: &Path) -> bool {
17
+ path.strip_prefix(root).is_ok_and(|relative| {
18
+ let mut components = relative.components();
19
+ components
20
+ .next()
21
+ .is_some_and(|component| component.as_os_str() == "lib")
22
+ && components
23
+ .next()
24
+ .is_none_or(|component| component.as_os_str() != "src")
25
+ && relative.extension().is_some_and(|ext| ext == "dart")
26
+ })
27
+ }
@@ -0,0 +1,125 @@
1
+ use std::collections::{BTreeMap, BTreeSet};
2
+ use std::path::PathBuf;
3
+
4
+ use serde::{Deserialize, Serialize};
5
+
6
+ use super::SymbolIndex;
7
+ use super::path_filters::{is_library_source, is_private};
8
+ use crate::generated::is_generated_dart_path;
9
+ use crate::graph::normalize_against;
10
+ use crate::{DeclarationKind, Location, ScannedProject};
11
+
12
+ /// A public API signature that exposes a Dart library-private type.
13
+ #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
14
+ pub struct PrivateTypeLeak {
15
+ /// File containing the public declaration.
16
+ pub path: PathBuf,
17
+ /// Public declaration whose signature leaks the private type.
18
+ pub declaration: String,
19
+ /// Kind of the public declaration.
20
+ pub declaration_kind: DeclarationKind,
21
+ /// Private type referenced by the public signature.
22
+ pub private_type: String,
23
+ /// Location of the private type token in the signature.
24
+ pub location: Location,
25
+ /// Whether Dart Decimate can safely delete code from graph evidence alone.
26
+ pub safe_to_delete: bool,
27
+ }
28
+
29
+ pub(super) fn private_type_leaks(
30
+ project: &ScannedProject,
31
+ index: &SymbolIndex,
32
+ ) -> Vec<PrivateTypeLeak> {
33
+ let private_types_by_library = private_types_by_library(index);
34
+ let mut leaks = Vec::new();
35
+
36
+ for file in &project.files {
37
+ let path = normalize_against(&project.root, &file.path);
38
+ if !path.starts_with(&project.root)
39
+ || is_generated_dart_path(&path)
40
+ || !is_library_source(&project.root, &path)
41
+ {
42
+ continue;
43
+ }
44
+
45
+ let library = index.library_path(&path);
46
+ let Some(private_types) = private_types_by_library.get(library) else {
47
+ continue;
48
+ };
49
+
50
+ leaks.extend(file.signature_references.iter().filter_map(|reference| {
51
+ if !public_signature_leaks_private_type(index, &path, private_types, reference) {
52
+ return None;
53
+ }
54
+
55
+ Some(PrivateTypeLeak {
56
+ path: path.clone(),
57
+ declaration: reference.declaration.clone(),
58
+ declaration_kind: reference.declaration_kind,
59
+ private_type: reference.name.clone(),
60
+ location: reference.location,
61
+ safe_to_delete: false,
62
+ })
63
+ }));
64
+ }
65
+
66
+ leaks.sort_by(|left, right| {
67
+ (
68
+ &left.path,
69
+ left.location.line,
70
+ left.location.column,
71
+ &left.declaration,
72
+ &left.private_type,
73
+ )
74
+ .cmp(&(
75
+ &right.path,
76
+ right.location.line,
77
+ right.location.column,
78
+ &right.declaration,
79
+ &right.private_type,
80
+ ))
81
+ });
82
+ leaks.dedup_by(|left, right| {
83
+ left.path == right.path
84
+ && left.declaration == right.declaration
85
+ && left.private_type == right.private_type
86
+ && left.location == right.location
87
+ });
88
+ leaks
89
+ }
90
+
91
+ fn private_types_by_library(index: &SymbolIndex) -> BTreeMap<PathBuf, BTreeSet<String>> {
92
+ let mut private_types = BTreeMap::<PathBuf, BTreeSet<String>>::new();
93
+ for indexed in &index.declarations {
94
+ if is_private(&indexed.declaration.name) && is_type_declaration(indexed.declaration.kind) {
95
+ private_types
96
+ .entry(index.library_path(&indexed.path).to_path_buf())
97
+ .or_default()
98
+ .insert(indexed.declaration.name.clone());
99
+ }
100
+ }
101
+ private_types
102
+ }
103
+
104
+ fn public_signature_leaks_private_type(
105
+ index: &SymbolIndex,
106
+ path: &std::path::Path,
107
+ private_types: &BTreeSet<String>,
108
+ reference: &crate::SignatureReference,
109
+ ) -> bool {
110
+ !is_private(&reference.declaration)
111
+ && is_private(&reference.name)
112
+ && private_types.contains(&reference.name)
113
+ && index.is_public_export(path, &reference.declaration)
114
+ }
115
+
116
+ const fn is_type_declaration(kind: DeclarationKind) -> bool {
117
+ matches!(
118
+ kind,
119
+ DeclarationKind::Class
120
+ | DeclarationKind::Mixin
121
+ | DeclarationKind::ExtensionType
122
+ | DeclarationKind::Enum
123
+ | DeclarationKind::TypeAlias
124
+ )
125
+ }