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,296 @@
1
+ use std::collections::BTreeMap;
2
+
3
+ use crate::Location;
4
+
5
+ use super::coverage::CoverageMap;
6
+ use super::{
7
+ ComplexityFinding, CrapFinding, FileCoverageStatus, FileHealthScore, HealthHotspot,
8
+ HealthOptions, RefactoringTarget,
9
+ };
10
+ use crate::health::FunctionMetrics;
11
+
12
+ pub(super) fn file_health_scores(
13
+ functions: &[FunctionMetrics],
14
+ complexity: &[ComplexityFinding],
15
+ crap: &[CrapFinding],
16
+ coverage: Option<&CoverageMap>,
17
+ options: &HealthOptions,
18
+ ) -> Vec<FileHealthScore> {
19
+ let mut builders = BTreeMap::new();
20
+ for function in functions {
21
+ builders
22
+ .entry(function.path.clone())
23
+ .or_insert_with(|| FileScoreBuilder::new(function.location))
24
+ .push_function(function);
25
+ }
26
+ for finding in complexity {
27
+ if let Some(builder) = builders.get_mut(&finding.path) {
28
+ builder.complex_functions += 1;
29
+ }
30
+ }
31
+ for finding in crap {
32
+ if let Some(builder) = builders.get_mut(&finding.path) {
33
+ builder.complex_functions += 1;
34
+ builder.max_crap_score = builder.max_crap_score.max(finding.crap_score);
35
+ }
36
+ }
37
+
38
+ let mut scores = builders
39
+ .into_iter()
40
+ .map(|(path, builder)| builder.finish(path, coverage, options))
41
+ .collect::<Vec<_>>();
42
+ scores.sort_by(|left, right| (left.score, &left.path).cmp(&(right.score, &right.path)));
43
+ scores
44
+ }
45
+
46
+ pub(super) fn project_quality_score(scores: &[FileHealthScore]) -> usize {
47
+ if scores.is_empty() {
48
+ return 0;
49
+ }
50
+ let weighted_total = scores
51
+ .iter()
52
+ .map(|score| score.score.saturating_mul(score.functions.max(1)))
53
+ .sum::<usize>();
54
+ let weight = scores
55
+ .iter()
56
+ .map(|score| score.functions.max(1))
57
+ .sum::<usize>();
58
+ weighted_total.saturating_add(weight / 2) / weight
59
+ }
60
+
61
+ pub(super) fn health_hotspots(scores: &[FileHealthScore], min_score: usize) -> Vec<HealthHotspot> {
62
+ let mut hotspots = scores
63
+ .iter()
64
+ .filter(|score| score.score < min_score)
65
+ .map(|score| HealthHotspot {
66
+ path: score.path.clone(),
67
+ location: Location { line: 1, column: 0 },
68
+ score: score.score,
69
+ reasons: score.reasons.clone(),
70
+ owners: score.owners.clone(),
71
+ owner_source: score.owner_source.clone(),
72
+ owner_section: score.owner_section.clone(),
73
+ })
74
+ .collect::<Vec<_>>();
75
+ hotspots.sort_by(|left, right| (left.score, &left.path).cmp(&(right.score, &right.path)));
76
+ hotspots
77
+ }
78
+
79
+ pub(super) fn refactoring_targets(scores: &[FileHealthScore]) -> Vec<RefactoringTarget> {
80
+ let mut targets = scores
81
+ .iter()
82
+ .filter(|score| score.score < 85)
83
+ .filter(|score| score.complex_functions > 0 || score.max_crap_score > 0)
84
+ .map(|score| RefactoringTarget {
85
+ path: score.path.clone(),
86
+ location: Location { line: 1, column: 0 },
87
+ score: score.score,
88
+ priority: target_priority(score),
89
+ reasons: score.reasons.clone(),
90
+ owners: score.owners.clone(),
91
+ owner_source: score.owner_source.clone(),
92
+ owner_section: score.owner_section.clone(),
93
+ })
94
+ .collect::<Vec<_>>();
95
+ targets.sort_by(|left, right| {
96
+ (std::cmp::Reverse(left.priority), left.score, &left.path).cmp(&(
97
+ std::cmp::Reverse(right.priority),
98
+ right.score,
99
+ &right.path,
100
+ ))
101
+ });
102
+ targets
103
+ }
104
+
105
+ #[derive(Debug, Clone, PartialEq, Eq)]
106
+ struct FileScoreBuilder {
107
+ functions: usize,
108
+ complex_functions: usize,
109
+ max_cyclomatic_complexity: usize,
110
+ max_cognitive_complexity: usize,
111
+ max_crap_score: usize,
112
+ }
113
+
114
+ impl FileScoreBuilder {
115
+ fn new(_location: Location) -> Self {
116
+ Self {
117
+ functions: 0,
118
+ complex_functions: 0,
119
+ max_cyclomatic_complexity: 0,
120
+ max_cognitive_complexity: 0,
121
+ max_crap_score: 0,
122
+ }
123
+ }
124
+
125
+ fn push_function(&mut self, function: &FunctionMetrics) {
126
+ self.functions += 1;
127
+ self.max_cyclomatic_complexity = self.max_cyclomatic_complexity.max(function.cyclomatic);
128
+ self.max_cognitive_complexity = self.max_cognitive_complexity.max(function.cognitive);
129
+ }
130
+
131
+ fn finish(
132
+ self,
133
+ path: std::path::PathBuf,
134
+ coverage: Option<&CoverageMap>,
135
+ options: &HealthOptions,
136
+ ) -> FileHealthScore {
137
+ let coverage_summary = coverage_summary(coverage, &path);
138
+ let mut reasons = score_reasons(&self, &coverage_summary, options);
139
+ if reasons.is_empty() {
140
+ reasons.push("no health penalties".to_owned());
141
+ }
142
+ let score = health_score(&self, coverage_summary.status, options);
143
+ FileHealthScore {
144
+ path,
145
+ score,
146
+ functions: self.functions,
147
+ complex_functions: self.complex_functions,
148
+ max_cyclomatic_complexity: self.max_cyclomatic_complexity,
149
+ max_cognitive_complexity: self.max_cognitive_complexity,
150
+ max_crap_score: self.max_crap_score,
151
+ coverage_status: coverage_summary.status,
152
+ covered_lines: coverage_summary.covered_lines,
153
+ executable_lines: coverage_summary.executable_lines,
154
+ line_coverage_percent: coverage_summary.line_coverage_percent,
155
+ reasons,
156
+ owners: Vec::new(),
157
+ owner_source: None,
158
+ owner_section: None,
159
+ }
160
+ }
161
+ }
162
+
163
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
164
+ struct CoverageSummary {
165
+ status: FileCoverageStatus,
166
+ covered_lines: Option<usize>,
167
+ executable_lines: Option<usize>,
168
+ line_coverage_percent: Option<usize>,
169
+ }
170
+
171
+ fn coverage_summary(coverage: Option<&CoverageMap>, path: &std::path::Path) -> CoverageSummary {
172
+ let Some(coverage) = coverage else {
173
+ return CoverageSummary {
174
+ status: FileCoverageStatus::NotRequested,
175
+ covered_lines: None,
176
+ executable_lines: None,
177
+ line_coverage_percent: None,
178
+ };
179
+ };
180
+ let Some(file) = coverage.file(path) else {
181
+ return CoverageSummary {
182
+ status: FileCoverageStatus::Missing,
183
+ covered_lines: Some(0),
184
+ executable_lines: Some(0),
185
+ line_coverage_percent: None,
186
+ };
187
+ };
188
+
189
+ let covered_lines = file.covered_lines();
190
+ let executable_lines = file.executable_lines();
191
+ let status = if executable_lines == 0 {
192
+ FileCoverageStatus::NoExecutableLines
193
+ } else if covered_lines == 0 {
194
+ FileCoverageStatus::Uncovered
195
+ } else {
196
+ FileCoverageStatus::Covered
197
+ };
198
+ CoverageSummary {
199
+ status,
200
+ covered_lines: Some(covered_lines),
201
+ executable_lines: Some(executable_lines),
202
+ line_coverage_percent: (executable_lines > 0)
203
+ .then(|| coverage_percent(covered_lines, executable_lines)),
204
+ }
205
+ }
206
+
207
+ fn health_score(
208
+ builder: &FileScoreBuilder,
209
+ coverage_status: FileCoverageStatus,
210
+ options: &HealthOptions,
211
+ ) -> usize {
212
+ let penalty = complexity_penalty(builder, options) + coverage_penalty(coverage_status);
213
+ 100usize.saturating_sub(penalty.min(100))
214
+ }
215
+
216
+ fn complexity_penalty(builder: &FileScoreBuilder, options: &HealthOptions) -> usize {
217
+ builder
218
+ .max_cyclomatic_complexity
219
+ .saturating_sub(options.max_cyclomatic / 2)
220
+ .saturating_mul(2)
221
+ + builder
222
+ .max_cognitive_complexity
223
+ .saturating_sub(options.max_cognitive / 2)
224
+ .saturating_mul(2)
225
+ + builder.complex_functions.saturating_mul(8)
226
+ + builder
227
+ .max_crap_score
228
+ .saturating_sub(options.max_crap.unwrap_or(30) / 2)
229
+ .saturating_mul(2)
230
+ }
231
+
232
+ fn coverage_penalty(status: FileCoverageStatus) -> usize {
233
+ match status {
234
+ FileCoverageStatus::NotRequested | FileCoverageStatus::Covered => 0,
235
+ FileCoverageStatus::NoExecutableLines => 15,
236
+ FileCoverageStatus::Missing => 25,
237
+ FileCoverageStatus::Uncovered => 35,
238
+ }
239
+ }
240
+
241
+ fn score_reasons(
242
+ builder: &FileScoreBuilder,
243
+ coverage: &CoverageSummary,
244
+ options: &HealthOptions,
245
+ ) -> Vec<String> {
246
+ let mut reasons = Vec::new();
247
+ if builder.max_cyclomatic_complexity > options.max_cyclomatic / 2 {
248
+ reasons.push(format!(
249
+ "max cyclomatic complexity {}",
250
+ builder.max_cyclomatic_complexity
251
+ ));
252
+ }
253
+ if builder.max_cognitive_complexity > options.max_cognitive / 2 {
254
+ reasons.push(format!(
255
+ "max cognitive complexity {}",
256
+ builder.max_cognitive_complexity
257
+ ));
258
+ }
259
+ if builder.complex_functions > 0 {
260
+ reasons.push(format!("{} complex functions", builder.complex_functions));
261
+ }
262
+ if builder.max_crap_score > 0 {
263
+ reasons.push(format!("max CRAP score {}", builder.max_crap_score));
264
+ }
265
+ match coverage.status {
266
+ FileCoverageStatus::NotRequested | FileCoverageStatus::Covered => {}
267
+ FileCoverageStatus::Missing => reasons.push("missing coverage record".to_owned()),
268
+ FileCoverageStatus::NoExecutableLines => {
269
+ reasons.push("no executable LCOV lines".to_owned());
270
+ }
271
+ FileCoverageStatus::Uncovered => reasons.push("zero covered LCOV lines".to_owned()),
272
+ }
273
+ reasons
274
+ }
275
+
276
+ fn target_priority(score: &FileHealthScore) -> usize {
277
+ 100usize.saturating_sub(score.score)
278
+ + score.complex_functions.saturating_mul(10)
279
+ + score.max_crap_score / 2
280
+ + uncovered_bonus(score.coverage_status)
281
+ }
282
+
283
+ fn uncovered_bonus(status: FileCoverageStatus) -> usize {
284
+ match status {
285
+ FileCoverageStatus::Missing | FileCoverageStatus::Uncovered => 10,
286
+ FileCoverageStatus::NoExecutableLines => 5,
287
+ FileCoverageStatus::NotRequested | FileCoverageStatus::Covered => 0,
288
+ }
289
+ }
290
+
291
+ fn coverage_percent(covered_lines: usize, executable_lines: usize) -> usize {
292
+ covered_lines
293
+ .saturating_mul(100)
294
+ .saturating_add(executable_lines / 2)
295
+ / executable_lines
296
+ }
@@ -0,0 +1,240 @@
1
+ use std::fs;
2
+
3
+ use tempfile::TempDir;
4
+
5
+ use crate::{HealthOptions, analyze_health, scan_project};
6
+
7
+ #[test]
8
+ fn health_counts_branch_constructs() -> Result<(), Box<dyn std::error::Error>> {
9
+ let fixture = tempfile::tempdir()?;
10
+ write(
11
+ &fixture,
12
+ "lib/main.dart",
13
+ "void main() {
14
+ if (a && b || c) {}
15
+ for (final item in items) {}
16
+ while (ready) {}
17
+ do {} while (again);
18
+ switch (value) {
19
+ case 1:
20
+ break;
21
+ default:
22
+ break;
23
+ }
24
+ try {} catch (error) {}
25
+ final next = a ? b : c;
26
+ }
27
+ ",
28
+ )?;
29
+ let project = scan_project(fixture.path())?;
30
+
31
+ let report = analyze_health(
32
+ &project,
33
+ &HealthOptions {
34
+ max_cyclomatic: 1,
35
+ max_cognitive: 99,
36
+ top: None,
37
+ complexity_breakdown: true.into(),
38
+ ..HealthOptions::default()
39
+ },
40
+ )?;
41
+
42
+ assert_eq!(report.functions, 1);
43
+ assert_eq!(report.max_cyclomatic_complexity, 10);
44
+ assert_eq!(report.complexity[0].cyclomatic_complexity, 10);
45
+ assert_eq!(report.complexity[0].contributions.len(), 9);
46
+
47
+ Ok(())
48
+ }
49
+
50
+ #[test]
51
+ fn cognitive_complexity_penalizes_nesting() -> Result<(), Box<dyn std::error::Error>> {
52
+ let fixture = tempfile::tempdir()?;
53
+ write(
54
+ &fixture,
55
+ "lib/main.dart",
56
+ "void flat() {
57
+ if (a) {}
58
+ if (b) {}
59
+ }
60
+
61
+ void nested() {
62
+ if (a) {
63
+ if (b) {}
64
+ }
65
+ }
66
+ ",
67
+ )?;
68
+ let project = scan_project(fixture.path())?;
69
+
70
+ let report = analyze_health(
71
+ &project,
72
+ &HealthOptions {
73
+ max_cyclomatic: 1,
74
+ max_cognitive: 1,
75
+ top: None,
76
+ complexity_breakdown: false.into(),
77
+ ..HealthOptions::default()
78
+ },
79
+ )?;
80
+
81
+ let Some(flat) = report
82
+ .complexity
83
+ .iter()
84
+ .find(|finding| finding.symbol == "flat")
85
+ else {
86
+ panic!("flat finding");
87
+ };
88
+ let Some(nested) = report
89
+ .complexity
90
+ .iter()
91
+ .find(|finding| finding.symbol == "nested")
92
+ else {
93
+ panic!("nested finding");
94
+ };
95
+ assert_eq!(flat.cyclomatic_complexity, nested.cyclomatic_complexity);
96
+ assert!(nested.cognitive_complexity > flat.cognitive_complexity);
97
+
98
+ Ok(())
99
+ }
100
+
101
+ #[test]
102
+ fn nested_closures_are_scored_separately() -> Result<(), Box<dyn std::error::Error>> {
103
+ let fixture = tempfile::tempdir()?;
104
+ write(
105
+ &fixture,
106
+ "lib/main.dart",
107
+ "void outer() {
108
+ final inner = () {
109
+ if (ready) {}
110
+ };
111
+ inner();
112
+ }
113
+ ",
114
+ )?;
115
+ let project = scan_project(fixture.path())?;
116
+
117
+ let report = analyze_health(
118
+ &project,
119
+ &HealthOptions {
120
+ max_cyclomatic: 0,
121
+ max_cognitive: 99,
122
+ top: None,
123
+ complexity_breakdown: false.into(),
124
+ ..HealthOptions::default()
125
+ },
126
+ )?;
127
+
128
+ let outer = report
129
+ .complexity
130
+ .iter()
131
+ .find(|finding| finding.symbol == "outer");
132
+ let closure = report
133
+ .complexity
134
+ .iter()
135
+ .find(|finding| finding.symbol == "<closure>");
136
+ let (Some(outer), Some(closure)) = (outer, closure) else {
137
+ panic!("outer function and closure findings");
138
+ };
139
+ assert_eq!(outer.cyclomatic_complexity, 1);
140
+ assert_eq!(closure.cyclomatic_complexity, 2);
141
+
142
+ Ok(())
143
+ }
144
+
145
+ #[test]
146
+ fn lcov_drives_coverage_gaps_and_crap_findings() -> Result<(), Box<dyn std::error::Error>> {
147
+ let fixture = tempfile::tempdir()?;
148
+ write_coverage_source(&fixture)?;
149
+ write(
150
+ &fixture,
151
+ "coverage/lcov.info",
152
+ "SF:lib/main.dart
153
+ DA:2,0
154
+ DA:3,0
155
+ DA:4,0
156
+ DA:5,0
157
+ end_of_record
158
+ ",
159
+ )?;
160
+ let project = scan_project(fixture.path())?;
161
+
162
+ let report = analyze_health(
163
+ &project,
164
+ &HealthOptions {
165
+ coverage_path: Some("coverage/lcov.info".into()),
166
+ coverage_gaps: true.into(),
167
+ max_crap: Some(10),
168
+ ..HealthOptions::default()
169
+ },
170
+ )?;
171
+
172
+ assert_eq!(report.coverage_files, 1);
173
+ assert_eq!(report.coverage_gaps.len(), 1);
174
+ assert_eq!(report.coverage_gaps[0].covered_lines, 0);
175
+ assert_eq!(report.coverage_gaps[0].executable_lines, 4);
176
+ assert_eq!(report.crap.len(), 1);
177
+ assert_eq!(report.crap[0].symbol, "uncovered");
178
+ assert_eq!(report.crap[0].cyclomatic_complexity, 4);
179
+ assert_eq!(report.crap[0].line_coverage_percent, 0);
180
+ assert_eq!(report.crap[0].crap_score, 20);
181
+ assert_eq!(report.max_crap_score, 20);
182
+
183
+ Ok(())
184
+ }
185
+
186
+ #[test]
187
+ fn covered_lcov_lines_do_not_emit_coverage_findings() -> Result<(), Box<dyn std::error::Error>> {
188
+ let fixture = tempfile::tempdir()?;
189
+ write_coverage_source(&fixture)?;
190
+ write(
191
+ &fixture,
192
+ "coverage/lcov.info",
193
+ "SF:lib/main.dart
194
+ DA:2,1
195
+ DA:3,1
196
+ DA:4,1
197
+ DA:5,1
198
+ end_of_record
199
+ ",
200
+ )?;
201
+ let project = scan_project(fixture.path())?;
202
+
203
+ let report = analyze_health(
204
+ &project,
205
+ &HealthOptions {
206
+ coverage_path: Some("coverage/lcov.info".into()),
207
+ coverage_gaps: true.into(),
208
+ max_crap: Some(10),
209
+ ..HealthOptions::default()
210
+ },
211
+ )?;
212
+
213
+ assert!(report.coverage_gaps.is_empty());
214
+ assert!(report.crap.is_empty());
215
+ assert_eq!(report.max_crap_score, 0);
216
+
217
+ Ok(())
218
+ }
219
+
220
+ fn write_coverage_source(fixture: &TempDir) -> Result<(), std::io::Error> {
221
+ write(
222
+ fixture,
223
+ "lib/main.dart",
224
+ "void uncovered(List<int> items) {
225
+ if (items.isEmpty) return;
226
+ for (final item in items) {
227
+ if (item.isEven) return;
228
+ }
229
+ }
230
+ ",
231
+ )
232
+ }
233
+
234
+ fn write(fixture: &TempDir, path: &str, source: &str) -> Result<(), std::io::Error> {
235
+ let path = fixture.path().join(path);
236
+ if let Some(parent) = path.parent() {
237
+ fs::create_dir_all(parent)?;
238
+ }
239
+ fs::write(path, source)
240
+ }
@@ -0,0 +1,163 @@
1
+ use serde::{Deserialize, Serialize};
2
+
3
+ /// Per-file/function complexity threshold override.
4
+ #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
5
+ #[serde(deny_unknown_fields)]
6
+ pub struct HealthThresholdOverride {
7
+ /// File globs matched against root-relative Dart paths.
8
+ pub files: Vec<String>,
9
+ /// Exact function names. Empty means every function in matching files.
10
+ #[serde(default)]
11
+ pub functions: Vec<String>,
12
+ /// Local cyclomatic ceiling.
13
+ #[serde(default, alias = "maxCyclomatic")]
14
+ pub max_cyclomatic: Option<usize>,
15
+ /// Local cognitive ceiling.
16
+ #[serde(default, alias = "maxCognitive")]
17
+ pub max_cognitive: Option<usize>,
18
+ /// Local CRAP ceiling.
19
+ #[serde(default, alias = "maxCrap")]
20
+ pub max_crap: Option<usize>,
21
+ /// Reason shown to agents when this override is active.
22
+ #[serde(default)]
23
+ pub reason: Option<String>,
24
+ }
25
+
26
+ impl HealthThresholdOverride {
27
+ /// Whether this override contains at least one local ceiling.
28
+ #[must_use]
29
+ pub const fn has_threshold(&self) -> bool {
30
+ self.max_cyclomatic.is_some() || self.max_cognitive.is_some() || self.max_crap.is_some()
31
+ }
32
+
33
+ pub(super) const fn has_static_threshold(&self) -> bool {
34
+ self.max_cyclomatic.is_some() || self.max_cognitive.is_some()
35
+ }
36
+
37
+ pub(super) const fn has_crap_threshold(&self) -> bool {
38
+ self.max_crap.is_some()
39
+ }
40
+ }
41
+
42
+ /// Status for one configured threshold override.
43
+ #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
44
+ #[serde(rename_all = "snake_case")]
45
+ pub enum HealthThresholdOverrideStatus {
46
+ /// Override matched a function and changed or explained threshold output.
47
+ Active,
48
+ /// Override matched code, but no current function needs its local ceiling.
49
+ Stale,
50
+ /// Override did not match any analyzed function.
51
+ NoMatch,
52
+ }
53
+
54
+ /// Runtime report state for one threshold override.
55
+ #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
56
+ pub struct HealthThresholdOverrideReport {
57
+ /// Zero-based index in `health.thresholdOverrides`.
58
+ pub index: usize,
59
+ /// File globs from config.
60
+ pub files: Vec<String>,
61
+ /// Exact function names from config.
62
+ pub functions: Vec<String>,
63
+ /// Local cyclomatic ceiling.
64
+ pub max_cyclomatic: Option<usize>,
65
+ /// Local cognitive ceiling.
66
+ pub max_cognitive: Option<usize>,
67
+ /// Local CRAP ceiling.
68
+ pub max_crap: Option<usize>,
69
+ /// Configured reason.
70
+ pub reason: Option<String>,
71
+ /// Override status.
72
+ pub status: HealthThresholdOverrideStatus,
73
+ /// Matched root-relative `file:symbol` entries.
74
+ pub matched_functions: Vec<String>,
75
+ }
76
+
77
+ /// Effective thresholds used for a finding.
78
+ #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
79
+ pub struct EffectiveThresholds {
80
+ /// Cyclomatic ceiling used for this function.
81
+ pub max_cyclomatic: Option<usize>,
82
+ /// Cognitive ceiling used for this function.
83
+ pub max_cognitive: Option<usize>,
84
+ /// CRAP ceiling used for this function.
85
+ pub max_crap: Option<usize>,
86
+ }
87
+
88
+ /// Source of the effective thresholds.
89
+ #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
90
+ #[serde(rename_all = "kebab-case")]
91
+ pub enum ThresholdSource {
92
+ /// Threshold came from `health.thresholdOverrides`.
93
+ Override,
94
+ }
95
+
96
+ /// Thresholds applied to a function while evaluating findings.
97
+ #[derive(Debug, Clone, PartialEq, Eq)]
98
+ pub(super) struct AppliedThresholds {
99
+ pub(super) source: Option<ThresholdSource>,
100
+ pub(super) reason: Option<String>,
101
+ pub(super) effective: EffectiveThresholds,
102
+ }
103
+
104
+ impl AppliedThresholds {
105
+ pub(super) fn default_static(max_cyclomatic: usize, max_cognitive: usize) -> Self {
106
+ Self {
107
+ source: None,
108
+ reason: None,
109
+ effective: EffectiveThresholds {
110
+ max_cyclomatic: Some(max_cyclomatic),
111
+ max_cognitive: Some(max_cognitive),
112
+ max_crap: None,
113
+ },
114
+ }
115
+ }
116
+
117
+ pub(super) fn default_crap(max_crap: usize) -> Self {
118
+ Self {
119
+ source: None,
120
+ reason: None,
121
+ effective: EffectiveThresholds {
122
+ max_cyclomatic: None,
123
+ max_cognitive: None,
124
+ max_crap: Some(max_crap),
125
+ },
126
+ }
127
+ }
128
+ }
129
+
130
+ pub(super) fn override_report(
131
+ index: usize,
132
+ rule: &HealthThresholdOverride,
133
+ status: HealthThresholdOverrideStatus,
134
+ matched_functions: Vec<String>,
135
+ ) -> HealthThresholdOverrideReport {
136
+ HealthThresholdOverrideReport {
137
+ index,
138
+ files: rule.files.clone(),
139
+ functions: rule.functions.clone(),
140
+ max_cyclomatic: rule.max_cyclomatic,
141
+ max_cognitive: rule.max_cognitive,
142
+ max_crap: rule.max_crap,
143
+ reason: rule.reason.clone(),
144
+ status,
145
+ matched_functions,
146
+ }
147
+ }
148
+
149
+ pub(super) fn function_label(
150
+ root: &std::path::Path,
151
+ path: &std::path::Path,
152
+ symbol: &str,
153
+ ) -> String {
154
+ let relative = path.strip_prefix(root).unwrap_or(path);
155
+ format!("{}:{symbol}", path_to_slash_string(relative))
156
+ }
157
+
158
+ fn path_to_slash_string(path: &std::path::Path) -> String {
159
+ path.components()
160
+ .filter_map(|component| component.as_os_str().to_str())
161
+ .collect::<Vec<_>>()
162
+ .join("/")
163
+ }