1use rustc_hash::FxHashMap;
10use std::path::Path;
11
12use fallow_output::BaselineMode;
13use fallow_types::identity::IdentityPaths;
14
15use super::{
16 BASELINE_KEY_SCHEME, BaselineData, BaselineFileKind, BaselineKind, DuplicationBaselineData,
17 HEALTH_FINDING_DIMENSIONS, HealthBaselineCount, HealthBaselineData, HealthBaselineMode,
18 HealthFindingCategory, HealthFindingCountMap, canonical_keys, classify_baseline_value,
19 clone_group_fingerprint_key, consume_baseline_key, health_finding_counts,
20 moved_identity_bucket_remaps, severity_counts_for_dimension, severity_index,
21};
22use crate::duplicates::{CloneFingerprintSet, DuplicationReport};
23
24#[derive(Debug, Clone, PartialEq, Eq)]
26pub struct PrunedEntry {
27 pub category: String,
31 pub key: String,
33 pub count: usize,
35}
36
37#[derive(Debug, Clone, PartialEq, Eq)]
39pub struct BaselinePrune {
40 pub entries_before: usize,
43 pub entries_after: usize,
45 pub removed: Vec<PrunedEntry>,
47 pub content: Option<String>,
50}
51
52#[derive(Debug, Clone, PartialEq, Eq)]
54pub enum BaselinePruneRefusal {
55 Parse(String),
57 NotThisKind {
59 saved_by: Option<BaselineKind>,
61 },
62 LegacyKeys,
65 UnknownKeyScheme(String),
67 IncompatibleIdentity(Vec<&'static str>),
70 SharedCloneKeys,
73 UnknownFields(Vec<String>),
76 ScopeMismatch {
79 saved_only: BaselineMode,
81 run_only: BaselineMode,
85 },
86}
87
88impl BaselinePruneRefusal {
89 #[must_use]
91 pub const fn code(&self) -> &'static str {
92 match self {
93 Self::Parse(_) => "parse-error",
94 Self::NotThisKind { .. } => "not-this-kind",
95 Self::LegacyKeys => "legacy-keys",
96 Self::UnknownKeyScheme(_) => "unknown-key-scheme",
97 Self::IncompatibleIdentity(_) => "incompatible-identity",
98 Self::SharedCloneKeys => "shared-clone-keys",
99 Self::UnknownFields(_) => "unknown-fields",
100 Self::ScopeMismatch { .. } => "scope-mismatch",
101 }
102 }
103
104 #[must_use]
106 pub fn reason(&self) -> String {
107 match self {
108 Self::Parse(error) => format!("the file is not a valid baseline: {error}"),
109 Self::NotThisKind {
110 saved_by: Some(kind),
111 } => format!("`fallow {}` saved this file", kind.as_str()),
112 Self::NotThisKind { saved_by: None } => {
113 "nothing in the file names this baseline kind".to_owned()
114 }
115 Self::LegacyKeys => {
116 "the file uses an older key form that prune cannot match".to_owned()
117 }
118 Self::UnknownKeyScheme(scheme) => {
119 format!("the file uses the key scheme `{scheme}`, which this version does not know")
120 }
121 Self::IncompatibleIdentity(fields) => format!(
122 "the file was saved with another analysis mode ({})",
123 fields.join(", ")
124 ),
125 Self::SharedCloneKeys => {
126 "the file has clone keys that older versions shared between unrelated groups"
127 .to_owned()
128 }
129 Self::UnknownFields(fields) => format!(
130 "the file has fields that this version does not know ({}); a newer fallow version probably saved it",
131 fields.join(", ")
132 ),
133 Self::ScopeMismatch {
134 saved_only,
135 run_only,
136 } => {
137 let mut facts = Vec::new();
138 if !saved_only.is_empty() {
139 facts.push(format!(
140 "the file was saved with {} and this run does not use it",
141 saved_only.flags_prose()
142 ));
143 }
144 if !run_only.is_empty() {
145 facts.push(format!(
146 "the file does not record {} and this run uses it",
147 run_only.unrecorded_prose()
148 ));
149 }
150 format!(
151 "{}, so a prune would remove valid entries",
152 facts.join(", and ")
153 )
154 }
155 }
156 }
157}
158
159fn check_saved_mode(
162 content: &str,
163 entries: usize,
164 run: BaselineMode,
165) -> Result<(), BaselinePruneRefusal> {
166 if entries == 0 {
167 return Ok(());
168 }
169 let saved = BaselineMode::from_saved_names(&super::saved_scope_reasons(content));
170 if saved == run {
171 return Ok(());
172 }
173 Err(BaselinePruneRefusal::ScopeMismatch {
174 saved_only: saved.minus(run),
175 run_only: run.minus(saved),
176 })
177}
178
179fn parse_own_kind(
180 content: &str,
181 kind: BaselineKind,
182) -> Result<serde_json::Value, BaselinePruneRefusal> {
183 let parsed = serde_json::from_str::<serde_json::Value>(content)
184 .map_err(|error| BaselinePruneRefusal::Parse(error.to_string()))?;
185 match classify_baseline_value(&parsed, kind) {
186 BaselineFileKind::Own | BaselineFileKind::NotAnObject => Ok(parsed),
187 other @ (BaselineFileKind::Foreign(_) | BaselineFileKind::Unrecognised) => {
188 Err(BaselinePruneRefusal::NotThisKind {
189 saved_by: other.saved_by(),
190 })
191 }
192 }
193}
194
195fn parse_value<T: serde::de::DeserializeOwned + serde::Serialize>(
200 value: &serde_json::Value,
201) -> Result<T, BaselinePruneRefusal> {
202 let parsed =
203 T::deserialize(value).map_err(|error| BaselinePruneRefusal::Parse(error.to_string()))?;
204 let round_trip = serde_json::to_value(&parsed)
205 .map_err(|error| BaselinePruneRefusal::Parse(error.to_string()))?;
206 if let (Some(original), Some(known)) = (value.as_object(), round_trip.as_object()) {
207 let unknown: Vec<String> = original
208 .iter()
209 .filter(|(key, field)| {
210 key.as_str() != "kind" && !known.contains_key(key.as_str()) && !is_empty_json(field)
211 })
212 .map(|(key, _)| key.clone())
213 .collect();
214 if !unknown.is_empty() {
215 return Err(BaselinePruneRefusal::UnknownFields(unknown));
216 }
217 }
218 Ok(parsed)
219}
220
221fn is_empty_json(value: &serde_json::Value) -> bool {
222 match value {
223 serde_json::Value::Null => true,
224 serde_json::Value::Array(items) => items.is_empty(),
225 serde_json::Value::Object(fields) => fields.is_empty(),
226 serde_json::Value::String(text) => text.is_empty(),
227 serde_json::Value::Bool(_) | serde_json::Value::Number(_) => false,
228 }
229}
230
231fn serialize<T: serde::Serialize>(
232 baseline: &T,
233 trailing_newline: bool,
234) -> Result<String, BaselinePruneRefusal> {
235 let mut json = serde_json::to_string_pretty(baseline)
236 .map_err(|error| BaselinePruneRefusal::Parse(error.to_string()))?;
237 if trailing_newline {
238 json.push('\n');
239 }
240 Ok(json)
241}
242
243fn retain_matched(
246 saved: &mut Vec<String>,
247 current: &[String],
248 category: &str,
249 removed: &mut Vec<PrunedEntry>,
250) {
251 let mut remaining: FxHashMap<&str, usize> = FxHashMap::default();
252 for key in current {
253 *remaining.entry(key.as_str()).or_default() += 1;
254 }
255 saved.retain(|key| {
256 if consume_baseline_key(&mut remaining, key) {
257 return true;
258 }
259 removed.push(PrunedEntry {
260 category: category.to_owned(),
261 key: key.clone(),
262 count: 1,
263 });
264 false
265 });
266}
267
268pub fn prune_dead_code_baseline(
277 content: &str,
278 results: &crate::results::AnalysisResults,
279 root: &Path,
280 identity: &fallow_types::semantic::SemanticAnalysisIdentity,
281 mode: BaselineMode,
282) -> Result<BaselinePrune, BaselinePruneRefusal> {
283 let mut baseline: BaselineData =
284 parse_value(&parse_own_kind(content, BaselineKind::DeadCode)?)?;
285 match baseline.identity.as_deref() {
286 None => return Err(BaselinePruneRefusal::LegacyKeys),
287 Some(scheme) if scheme != BASELINE_KEY_SCHEME => {
288 return Err(BaselinePruneRefusal::UnknownKeyScheme(scheme.to_owned()));
289 }
290 Some(_) => {}
291 }
292 let incompatible = baseline.analysis_identity().incompatible_fields(identity);
293 if !incompatible.is_empty() {
294 return Err(BaselinePruneRefusal::IncompatibleIdentity(incompatible));
295 }
296
297 let entries_before = baseline.total_entries();
298 check_saved_mode(content, entries_before, mode)?;
299 let paths = IdentityPaths::new(root);
300 let hidden = results.cascade.hidden.to_results();
302 let mut removed = Vec::new();
303 macro_rules! prune {
304 ($($field:ident),* $(,)?) => {
305 $({
306 let mut current = canonical_keys(&results.$field, &paths);
307 current.extend(canonical_keys(&hidden.$field, &paths));
308 retain_matched(
309 &mut baseline.$field,
310 ¤t,
311 stringify!($field),
312 &mut removed,
313 );
314 })*
315 };
316 }
317 with_baseline_fields!(prune);
318
319 let content = if removed.is_empty() {
320 None
321 } else {
322 baseline.kind = Some(BaselineKind::DeadCode);
323 Some(serialize(&baseline, true)?)
324 };
325 Ok(BaselinePrune {
326 entries_before,
327 entries_after: baseline.total_entries(),
328 removed,
329 content,
330 })
331}
332
333pub fn prune_dupes_baseline(
345 content: &str,
346 report: &DuplicationReport,
347 production: bool,
348) -> Result<BaselinePrune, BaselinePruneRefusal> {
349 let mut baseline: DuplicationBaselineData =
350 parse_value(&parse_own_kind(content, BaselineKind::Dupes)?)?;
351 if baseline.has_unparsed_collision_keys() {
352 return Err(BaselinePruneRefusal::SharedCloneKeys);
353 }
354 let entries_before = baseline.entry_count();
355 if baseline.normalized_clone_fingerprints.is_empty() {
356 if entries_before == 0 {
357 return Ok(BaselinePrune {
358 entries_before,
359 entries_after: 0,
360 removed: Vec::new(),
361 content: None,
362 });
363 }
364 return Err(BaselinePruneRefusal::LegacyKeys);
365 }
366 check_saved_mode(
367 content,
368 entries_before,
369 BaselineMode {
370 production,
371 include_entry_exports: false,
372 },
373 )?;
374
375 let fingerprints = CloneFingerprintSet::from_groups(&report.clone_groups);
376 let current: Vec<String> = report
377 .clone_groups
378 .iter()
379 .map(|group| clone_group_fingerprint_key(group, &fingerprints))
380 .collect();
381 let mut remaining: FxHashMap<&str, usize> = FxHashMap::default();
382 for key in ¤t {
383 *remaining.entry(key.as_str()).or_default() += 1;
384 }
385 let keep: Vec<bool> = baseline
386 .normalized_clone_fingerprints
387 .iter()
388 .map(|key| consume_baseline_key(&mut remaining, key))
389 .collect();
390 let removed: Vec<PrunedEntry> = baseline
391 .normalized_clone_fingerprints
392 .iter()
393 .zip(&keep)
394 .filter(|(_, kept)| !**kept)
395 .map(|(key, _)| PrunedEntry {
396 category: "normalized_clone_fingerprints".to_owned(),
397 key: key.clone(),
398 count: 1,
399 })
400 .collect();
401 if removed.is_empty() {
402 return Ok(BaselinePrune {
403 entries_before,
404 entries_after: entries_before,
405 removed,
406 content: None,
407 });
408 }
409
410 let rows = keep.len();
411 retain_rows(&mut baseline.normalized_clone_fingerprints, &keep);
412 if baseline.clone_groups.len() == rows {
415 retain_rows(&mut baseline.clone_groups, &keep);
416 }
417 if baseline.clone_fingerprints.len() == rows {
418 retain_rows(&mut baseline.clone_fingerprints, &keep);
419 }
420 baseline.kind = Some(BaselineKind::Dupes);
421 Ok(BaselinePrune {
422 entries_before,
423 entries_after: baseline.entry_count(),
424 removed,
425 content: Some(serialize(&baseline, false)?),
426 })
427}
428
429fn retain_rows(rows: &mut Vec<String>, keep: &[bool]) {
430 let mut index = 0;
431 rows.retain(|_| {
432 let kept = keep[index];
433 index += 1;
434 kept
435 });
436}
437
438pub fn prune_health_baseline(
451 content: &str,
452 findings: &[fallow_output::ComplexityViolation],
453 root: &Path,
454 production: bool,
455) -> Result<BaselinePrune, BaselinePruneRefusal> {
456 let mut baseline: HealthBaselineData =
457 parse_value(&parse_own_kind(content, BaselineKind::Health)?)?;
458 if baseline.finding_counts.is_empty() && !baseline.findings.is_empty() {
459 return Err(BaselinePruneRefusal::LegacyKeys);
460 }
461 let entries_before = baseline.finding_entry_count();
462 check_saved_mode(
463 content,
464 entries_before,
465 BaselineMode {
466 production,
467 include_entry_exports: false,
468 },
469 )?;
470
471 let mut removed = Vec::new();
472 let current_counts = health_finding_counts(findings, root, HealthBaselineMode::Count);
473 prune_count_buckets(
474 &mut baseline.finding_counts,
475 ¤t_counts,
476 &FxHashMap::default(),
477 "finding_counts",
478 &mut removed,
479 );
480 baseline
481 .finding_counts
482 .retain(|_, counts| !counts.is_empty());
483 if !baseline.identity_finding_counts.is_empty() {
484 let current_identity = health_finding_counts(findings, root, HealthBaselineMode::Identity);
485 let remaps: FxHashMap<String, String> = moved_identity_bucket_remaps(
486 &baseline.identity_finding_counts,
487 ¤t_identity,
488 root,
489 )
490 .into_iter()
491 .collect();
492 prune_count_buckets(
493 &mut baseline.identity_finding_counts,
494 ¤t_identity,
495 &remaps,
496 "identity_finding_counts",
497 &mut removed,
498 );
499 baseline
504 .identity_finding_counts
505 .retain(|key, counts| !counts.is_empty() || current_identity.contains_key(key));
506 }
507
508 let content = if removed.is_empty() {
509 None
510 } else {
511 baseline.kind = Some(BaselineKind::Health);
512 Some(serialize(&baseline, false)?)
513 };
514 Ok(BaselinePrune {
515 entries_before,
516 entries_after: baseline.finding_entry_count(),
517 removed,
518 content,
519 })
520}
521
522fn prune_count_buckets(
524 saved: &mut HealthFindingCountMap,
525 current: &HealthFindingCountMap,
526 remaps: &FxHashMap<String, String>,
527 field: &str,
528 removed: &mut Vec<PrunedEntry>,
529) {
530 for (bucket, saved_counts) in saved.iter_mut() {
531 let current_key = remaps.get(bucket).unwrap_or(bucket);
532 let current_counts = current.get(current_key);
533 for dimension in HEALTH_FINDING_DIMENSIONS {
534 let baseline = severity_counts_for_dimension(Some(saved_counts), dimension);
535 let used = consumed_severity_slots(
536 severity_counts_for_dimension(current_counts, dimension),
537 baseline,
538 );
539 for severity in [
540 fallow_output::FindingSeverity::Moderate,
541 fallow_output::FindingSeverity::High,
542 fallow_output::FindingSeverity::Critical,
543 ] {
544 let index = severity_index(severity);
545 if used[index] == baseline[index] {
546 continue;
547 }
548 let category = HealthFindingCategory {
549 dimension,
550 severity,
551 }
552 .key();
553 removed.push(PrunedEntry {
554 category: format!("{field}.{category}"),
555 key: bucket.clone(),
556 count: baseline[index] - used[index],
557 });
558 if used[index] == 0 {
559 saved_counts.remove(category);
560 } else {
561 saved_counts.insert(
562 category.to_owned(),
563 HealthBaselineCount { count: used[index] },
564 );
565 }
566 }
567 }
568 }
569}
570
571fn consumed_severity_slots(current: [usize; 3], baseline: [usize; 3]) -> [usize; 3] {
578 let mut available = baseline;
579 for severity_idx in 0..3 {
580 let compatible = available[severity_idx..].iter().sum::<usize>();
581 let mut matched = current[severity_idx].min(compatible);
582 for slot in available.iter_mut().skip(severity_idx) {
583 let taken = matched.min(*slot);
584 *slot -= taken;
585 matched -= taken;
586 if matched == 0 {
587 break;
588 }
589 }
590 }
591 [
592 baseline[0] - available[0],
593 baseline[1] - available[1],
594 baseline[2] - available[2],
595 ]
596}
597
598#[cfg(test)]
599mod tests;