Skip to main content

fallow_engine/
baseline_growth.rs

1//! The shrink-only rule for a committed baseline.
2//!
3//! A baseline records debt that a repository still must pay. A change that adds
4//! a finding can also re-save the baseline, and then the new finding is
5//! suppressed and no stale entry exists. This module compares the baseline file
6//! with the same file at a base ref and names each key that the base file does
7//! not have. The comparison reads two file versions only. It needs no analysis
8//! run, so it gives the same answer on a whole-project run and on a narrowed run.
9//!
10//! A key is compared as the file writes it. A renamed file gives a new key, so
11//! the rule counts it as growth. The rule is strict on purpose: a reviewer
12//! approves each new key, or the change removes it. A dead-code baseline with
13//! an `identity` stores line-free keys once for each occurrence, so a moved
14//! line is not growth and one more occurrence of a key is.
15
16use std::collections::{BTreeMap, BTreeSet};
17use std::path::Path;
18
19use serde_json::{Map, Value};
20
21use fallow_types::identity::{IdentityPaths, dead_code_canonical_key};
22
23use crate::baseline::{BaselineData, BaselineKind};
24
25#[path = "baseline_growth_legacy_health.rs"]
26mod legacy_health;
27
28/// The keys that a baseline has and its version at the base ref does not have.
29#[derive(Debug, Clone, Default, PartialEq, Eq)]
30pub struct BaselineGrowth {
31    /// One item per category that grew, sorted by category name.
32    pub categories: Vec<GrownCategory>,
33}
34
35/// The new keys of one baseline category.
36#[derive(Debug, Clone, PartialEq, Eq)]
37pub struct GrownCategory {
38    /// The category as the baseline file names it, for example `unused_files`.
39    pub category: String,
40    /// The new keys, sorted.
41    pub keys: Vec<String>,
42}
43
44impl BaselineGrowth {
45    /// The number of new keys in all categories.
46    #[must_use]
47    pub fn added_entries(&self) -> usize {
48        self.categories.iter().map(|grown| grown.keys.len()).sum()
49    }
50
51    /// True when the baseline has no key that the base does not have.
52    #[must_use]
53    pub fn is_empty(&self) -> bool {
54        self.categories.is_empty()
55    }
56}
57
58/// Compare a baseline (`head`) with its version at the base ref (`base`).
59///
60/// Both values are the parsed JSON files. `kind` selects the categories that
61/// the format of the command writes:
62///
63/// - `dead-code`: the finding fields of a dead-code baseline. When both files carry the
64///   same `identity`, each extra occurrence of a key is growth. When the change
65///   rewrote a legacy baseline, each legacy key is translated to its canonical
66///   key and compared the same way. A category that holds a legacy key with no
67///   unambiguous translation (a key with a line, a bare package name, a key
68///   that lacks a part of the canonical key) is compared by its entry count.
69///   Two legacy files compare as key sets.
70/// - `dupes`: the content fingerprints of the clone groups. A base file saved
71///   before fingerprints existed is compared by its `clone_groups` keys.
72/// - `health`: the legacy `findings` keys, the finding counts per file and
73///   category (a higher count is growth), the runtime-coverage finding IDs and
74///   the refactoring target keys. When both files carry per-function counts,
75///   those counts replace the per-file counts. On a save from legacy keys to
76///   counts, each bucket can use only the old findings that could match it.
77///   One function can account for both a complexity count and a CRAP count.
78#[must_use]
79pub fn baseline_growth(kind: BaselineKind, base: &Value, head: &Value) -> BaselineGrowth {
80    let empty = Map::new();
81    let base = base.as_object().unwrap_or(&empty);
82    let head = head.as_object().unwrap_or(&empty);
83    let mut grown: BTreeMap<String, Vec<String>> = BTreeMap::new();
84    match kind {
85        BaselineKind::DeadCode => {
86            let base_scheme = base.get(DEAD_CODE_IDENTITY);
87            let head_scheme = head.get(DEAD_CODE_IDENTITY);
88            for &category in BaselineData::FINDING_FIELDS {
89                if !head.contains_key(category) {
90                    continue;
91                }
92                if base_scheme.is_none() && head_scheme.is_some() {
93                    add_grown_after_upgrade(&mut grown, category, base, head);
94                } else if base_scheme != head_scheme {
95                    add_grown_entry_count(&mut grown, category, base, head);
96                } else if head_scheme.is_some() {
97                    add_new_occurrences(&mut grown, category, base, head);
98                } else {
99                    add_new_keys(&mut grown, category, base, head);
100                }
101            }
102        }
103        BaselineKind::Dupes => {
104            let category = if base.contains_key(DUPES_FINGERPRINTS) {
105                DUPES_FINGERPRINTS
106            } else {
107                DUPES_LEGACY_GROUPS
108            };
109            add_new_keys(&mut grown, category, base, head);
110        }
111        BaselineKind::Health => {
112            for category in HEALTH_KEY_CATEGORIES {
113                add_new_keys(&mut grown, category, base, head);
114            }
115            let counts = if has_entries(base, HEALTH_IDENTITY_COUNTS)
116                && has_entries(head, HEALTH_IDENTITY_COUNTS)
117            {
118                HEALTH_IDENTITY_COUNTS
119            } else {
120                HEALTH_FILE_COUNTS
121            };
122            if let Some(migration) = legacy_health::Migration::from_maps(base, head) {
123                migration.compare(&mut grown);
124            } else {
125                add_grown_counts(&mut grown, counts, base, head);
126            }
127        }
128    }
129    BaselineGrowth {
130        categories: grown
131            .into_iter()
132            .filter(|(_, keys)| !keys.is_empty())
133            .map(|(category, keys)| GrownCategory { category, keys })
134            .collect(),
135    }
136}
137
138/// Explain how the growth gate matched a legacy health save to count buckets.
139#[must_use]
140pub fn baseline_growth_note(
141    kind: BaselineKind,
142    base: &Value,
143    head: &Value,
144) -> Option<&'static str> {
145    if kind != BaselineKind::Health {
146        return None;
147    }
148    legacy_health::Migration::from_maps(base.as_object()?, head.as_object()?)?;
149    Some(
150        "The old health baseline has no categories or severities. The gate reports count growth only where the new buckets require more findings than the old keys can cover.",
151    )
152}
153
154const DEAD_CODE_IDENTITY: &str = "identity";
155const DUPES_FINGERPRINTS: &str = "normalized_clone_fingerprints";
156const DUPES_LEGACY_GROUPS: &str = "clone_groups";
157const HEALTH_KEY_CATEGORIES: [&str; 3] = ["findings", "runtime_coverage_findings", "target_keys"];
158const HEALTH_FILE_COUNTS: &str = "finding_counts";
159const HEALTH_IDENTITY_COUNTS: &str = "identity_finding_counts";
160const HEALTH_FILE_LINES_MARKER: &str = "file_lines_categories";
161const HEALTH_FILE_LINES_PREFIX: &str = "file_lines_";
162const HEALTH_COMPLEXITY_PREFIX: &str = "complexity_";
163
164/// The string members of the array `category`, as a set.
165fn key_set<'a>(object: &'a Map<String, Value>, category: &str) -> BTreeSet<&'a str> {
166    object
167        .get(category)
168        .and_then(Value::as_array)
169        .map(|keys| keys.iter().filter_map(Value::as_str).collect())
170        .unwrap_or_default()
171}
172
173fn has_entries(object: &Map<String, Value>, category: &str) -> bool {
174    object
175        .get(category)
176        .and_then(Value::as_object)
177        .is_some_and(|buckets| !buckets.is_empty())
178}
179
180fn add_new_keys(
181    grown: &mut BTreeMap<String, Vec<String>>,
182    category: &str,
183    base: &Map<String, Value>,
184    head: &Map<String, Value>,
185) {
186    let known = key_set(base, category);
187    let added: Vec<String> = key_set(head, category)
188        .into_iter()
189        .filter(|key| !known.contains(key))
190        .map(display_key)
191        .collect();
192    if !added.is_empty() {
193        grown.entry(category.to_owned()).or_default().extend(added);
194    }
195}
196
197/// The string members of the array `category`, with the number of times each
198/// occurs.
199fn key_counts<'a>(object: &'a Map<String, Value>, category: &str) -> BTreeMap<&'a str, usize> {
200    let mut counts = BTreeMap::new();
201    for key in object
202        .get(category)
203        .and_then(Value::as_array)
204        .into_iter()
205        .flatten()
206        .filter_map(Value::as_str)
207    {
208        *counts.entry(key).or_insert(0) += 1;
209    }
210    counts
211}
212
213/// One entry for each occurrence of a key beyond its count at the base.
214fn add_new_occurrences(
215    grown: &mut BTreeMap<String, Vec<String>>,
216    category: &str,
217    base: &Map<String, Value>,
218    head: &Map<String, Value>,
219) {
220    let known: BTreeMap<String, usize> = key_counts(base, category)
221        .into_iter()
222        .map(|(key, count)| (key.to_owned(), count))
223        .collect();
224    push_new_occurrences(grown, category, &known, head);
225}
226
227/// Push one entry for each occurrence of a head key beyond its `known` count.
228fn push_new_occurrences(
229    grown: &mut BTreeMap<String, Vec<String>>,
230    category: &str,
231    known: &BTreeMap<String, usize>,
232    head: &Map<String, Value>,
233) {
234    let mut added = Vec::new();
235    for (key, now) in key_counts(head, category) {
236        let before = known.get(key).copied().unwrap_or(0);
237        added.extend(std::iter::repeat_n(
238            display_key(key),
239            now.saturating_sub(before),
240        ));
241    }
242    if !added.is_empty() {
243        grown.entry(category.to_owned()).or_default().extend(added);
244    }
245}
246
247/// Compare a legacy base category with a canonical head category. Every legacy
248/// key must translate, or the category falls back to its entry count.
249fn add_grown_after_upgrade(
250    grown: &mut BTreeMap<String, Vec<String>>,
251    category: &str,
252    base: &Map<String, Value>,
253    head: &Map<String, Value>,
254) {
255    let mut known: BTreeMap<String, usize> = BTreeMap::new();
256    for (key, count) in key_counts(base, category) {
257        let Some(canonical) = canonical_from_legacy(category, key) else {
258            add_grown_entry_count(grown, category, base, head);
259            return;
260        };
261        *known.entry(canonical).or_insert(0) += count;
262    }
263    push_new_occurrences(grown, category, &known, head);
264}
265
266/// The canonical key of a legacy dead-code baseline key, when the legacy form
267/// holds every part of the canonical key and no line.
268fn canonical_from_legacy(category: &str, key: &str) -> Option<String> {
269    let paths = IdentityPaths::new(Path::new(""));
270    let path = |value: &str| paths.key(Path::new(value));
271    let set = |values: &[&str]| paths.set(values.iter().map(Path::new));
272    let canonical = |rule: &str, parts: &[String]| {
273        let parts: Vec<&str> = parts.iter().map(String::as_str).collect();
274        Some(dead_code_canonical_key(rule, &parts))
275    };
276    let path_name = |rule: &str| {
277        let (file, name) = key.split_once(':')?;
278        canonical(rule, &[path(file), name.to_owned()])
279    };
280    let manifest_package = |rule: &str| {
281        let (manifest, package) = key.rsplit_once(':')?;
282        if !manifest.ends_with("package.json") {
283            return None;
284        }
285        canonical(rule, &[path(manifest), package.to_owned()])
286    };
287    let member = |rule: &str| {
288        let (file, member) = key.split_once(':')?;
289        let (parent, name) = member.split_once('.')?;
290        canonical(rule, &[path(file), parent.to_owned(), name.to_owned()])
291    };
292    match category {
293        "unused_files" => canonical("unused-file", &[path(key)]),
294        "unused_exports" => path_name("unused-export"),
295        "unused_types" => path_name("unused-type"),
296        "deprecated_exports_in_use" => path_name("deprecated-export-in-use"),
297        "invalid_client_exports" => path_name("invalid-client-export"),
298        "unresolved_imports" => path_name("unresolved-import"),
299        "unprovided_injects" => path_name("unprovided-inject"),
300        "unrendered_components" => path_name("unrendered-component"),
301        "unused_server_actions" => path_name("unused-server-action"),
302        "unused_load_data_keys" => path_name("unused-load-data-key"),
303        "route_collisions" => path_name("route-collision"),
304        "dynamic_segment_name_conflicts" => path_name("dynamic-segment-name-conflict"),
305        "boundary_call_violations" => path_name("boundary-call-violation"),
306        "boundary_coverage_violations" => canonical("boundary-coverage", &[path(key)]),
307        "unused_dependencies" => manifest_package("unused-dependency"),
308        "unused_dev_dependencies" => manifest_package("unused-dev-dependency"),
309        "unused_optional_dependencies" => manifest_package("unused-optional-dependency"),
310        "type_only_dependencies" => manifest_package("type-only-dependency"),
311        "test_only_dependencies" => manifest_package("test-only-dependency"),
312        "dev_dependencies_in_production" => manifest_package("dev-dependency-in-production"),
313        "unused_enum_members" => member("unused-enum-member"),
314        "unused_class_members" => member("unused-class-member"),
315        "unused_namespace_members" => member("unused-namespace-member"),
316        "unused_protected_class_members" => member("unused-protected-class-member"),
317        "unused_store_members" => member("unused-store-member"),
318        "unlisted_dependencies" => canonical("unlisted-dependency", &[key.to_owned()]),
319        "private_type_leaks" => {
320            let (file, rest) = key.split_once(':')?;
321            let (export, leaked) = rest.split_once("->")?;
322            canonical(
323                "private-type-leak",
324                &[path(file), export.to_owned(), leaked.to_owned()],
325            )
326        }
327        "duplicate_exports" => {
328            let mut parts = key.split('|');
329            let name = parts.next()?.to_owned();
330            let files: Vec<&str> = parts.collect();
331            if files.is_empty() {
332                return None;
333            }
334            canonical("duplicate-export", &[name, set(&files)])
335        }
336        "circular_dependencies" => {
337            let files: Vec<&str> = key.split("->").collect();
338            canonical("circular-dependency", &[set(&files)])
339        }
340        "re_export_cycles" => {
341            let (kind, rest) = key.split_once(':')?;
342            let files: Vec<&str> = rest.split("<->").collect();
343            canonical("re-export-cycle", &[kind.to_owned(), set(&files)])
344        }
345        "boundary_violations" => {
346            let (from, to) = key.split_once("->")?;
347            canonical("boundary-violation", &[path(from), path(to)])
348        }
349        "unused_dependency_overrides" => {
350            let (source, raw_key) = key.split_once(':')?;
351            canonical(
352                "unused-dependency-override",
353                &[source.to_owned(), raw_key.to_owned()],
354            )
355        }
356        "misconfigured_dependency_overrides" => {
357            let (source, raw_key) = key.split_once(':')?;
358            canonical(
359                "misconfigured-dependency-override",
360                &[source.to_owned(), raw_key.to_owned()],
361            )
362        }
363        // Keys with a line (stale suppressions, misplaced directives, catalog
364        // references), keys without the path or component name of the
365        // canonical key (catalog entries and groups, component contracts),
366        // keys whose parts cannot be split safely (policy violations) and
367        // keys whose canonical key has fewer parts (client and server barrels)
368        // have no translation.
369        _ => None,
370    }
371}
372
373/// One entry for each entry of `category` beyond its count at the base. Used
374/// when the two files write keys in different forms.
375fn add_grown_entry_count(
376    grown: &mut BTreeMap<String, Vec<String>>,
377    category: &str,
378    base: &Map<String, Value>,
379    head: &Map<String, Value>,
380) {
381    let entries = |object: &Map<String, Value>| {
382        object
383            .get(category)
384            .and_then(Value::as_array)
385            .map_or(0, Vec::len)
386    };
387    let (before, now) = (entries(base), entries(head));
388    let extra = now.saturating_sub(before);
389    let added = (1..=extra).map(|index| {
390        format!(
391            "new entry {index} of {extra}: the key format changed, so the gate compares entry counts ({before} -> {now})"
392        )
393    });
394    if extra > 0 {
395        grown.entry(category.to_owned()).or_default().extend(added);
396    }
397}
398
399/// Health count buckets: `path -> finding category -> { count }`. A bucket
400/// whose count is higher than at the base is growth, also when the base has no
401/// such bucket.
402fn add_grown_counts(
403    grown: &mut BTreeMap<String, Vec<String>>,
404    category: &str,
405    base: &Map<String, Value>,
406    head: &Map<String, Value>,
407) {
408    let Some(head_buckets) = head.get(category).and_then(Value::as_object) else {
409        return;
410    };
411    let base_buckets = base.get(category).and_then(Value::as_object);
412    let base_counts_file_lines_apart = base
413        .get(HEALTH_FILE_LINES_MARKER)
414        .and_then(Value::as_bool)
415        .unwrap_or(false);
416    let mut added = Vec::new();
417    for (path, finding_counts) in head_buckets {
418        let Some(finding_counts) = finding_counts.as_object() else {
419            continue;
420        };
421        let base_counts = base_buckets.and_then(|buckets| buckets.get(path));
422        for (finding, count) in finding_counts {
423            let now = bucket_count(Some(count));
424            let mut before = bucket_count(base_counts.and_then(|counts| counts.get(finding)));
425            if !base_counts_file_lines_apart
426                && is_file_lines_identity_bucket(path)
427                && let Some(severity) = finding.strip_prefix(HEALTH_FILE_LINES_PREFIX)
428            {
429                before += freed_complexity_slots(base_counts, finding_counts, severity);
430            }
431            if now > before {
432                let key = display_key(path);
433                added.push(if before == 0 {
434                    format!("{key} {finding} (count {now})")
435                } else {
436                    format!("{key} {finding} (count {before} -> {now})")
437                });
438            }
439        }
440    }
441    if !added.is_empty() {
442        grown.entry(category.to_owned()).or_default().extend(added);
443    }
444}
445
446/// `true` for an identity bucket `path\0<file>`, which holds only file-length
447/// findings.
448///
449/// A count bucket (`path`) also holds function findings, so a freed
450/// complexity slot there can be a fixed function. The growth check then counts
451/// a long file in that bucket as growth, also on the first save from a file
452/// without the marker.
453fn is_file_lines_identity_bucket(key: &str) -> bool {
454    key.split_once('\0')
455        .is_some_and(|(_, name)| name == fallow_output::FILE_LINES_FINDING_NAME)
456}
457
458/// The `complexity_<severity>` slots of a base bucket that the head bucket no
459/// longer uses.
460///
461/// A base file without the `file_lines_categories` marker counts a long file
462/// as complexity. The first save of a newer version moves that slot to
463/// `file_lines_<severity>`, and the move is not growth.
464fn freed_complexity_slots(
465    base_counts: Option<&Value>,
466    head_counts: &Map<String, Value>,
467    severity: &str,
468) -> u64 {
469    let complexity = format!("{HEALTH_COMPLEXITY_PREFIX}{severity}");
470    let base = bucket_count(base_counts.and_then(|counts| counts.get(&complexity)));
471    base.saturating_sub(bucket_count(head_counts.get(&complexity)))
472}
473
474fn bucket_count(bucket: Option<&Value>) -> u64 {
475    bucket
476        .and_then(|bucket| bucket.get("count"))
477        .and_then(Value::as_u64)
478        .unwrap_or(0)
479}
480
481/// Some formats join key parts with a NUL byte. Show it as `:`, so the
482/// message stays on one line and prints in every terminal.
483fn display_key(key: &str) -> String {
484    key.replace('\0', ":")
485}
486
487/// Why the baseline at the base ref could not be read.
488#[derive(Debug, Clone, PartialEq, Eq)]
489pub enum BaseBaselineError {
490    /// `git` could not be started.
491    GitMissing(String),
492    /// The baseline is not in a git work tree.
493    NotARepository,
494    /// Git cannot resolve the ref to a commit, typically because a shallow
495    /// clone did not fetch it.
496    RefUnavailable,
497    /// Git failed for another reason.
498    GitFailed(String),
499}
500
501/// Read the version of the file at `path` that the commit `git_ref` has.
502///
503/// `Ok(None)` when the commit has no file at that path, which is a baseline
504/// that the change adds. The path is resolved relative to the directory of the
505/// file, so a baseline in a nested directory or under `--root` reads correctly.
506pub fn read_baseline_at_ref(
507    path: &Path,
508    git_ref: &str,
509) -> Result<Option<String>, BaseBaselineError> {
510    let dir = match path.parent() {
511        Some(parent) if !parent.as_os_str().is_empty() => parent,
512        _ => Path::new("."),
513    };
514    let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
515        return Err(BaseBaselineError::GitFailed(format!(
516            "the baseline path {} has no file name",
517            path.display()
518        )));
519    };
520    let inside = run_git(dir, &["rev-parse", "--is-inside-work-tree"])?;
521    if !inside.status.success() {
522        return Err(BaseBaselineError::NotARepository);
523    }
524    let resolved = run_git(
525        dir,
526        &["rev-parse", "--verify", "--quiet", &peel_to_commit(git_ref)],
527    )?;
528    if !resolved.status.success() {
529        return Err(BaseBaselineError::RefUnavailable);
530    }
531    let object = format!("{git_ref}:./{name}");
532    let exists = run_git(dir, &["cat-file", "-e", &object])?;
533    if !exists.status.success() {
534        return Ok(None);
535    }
536    let shown = run_git(dir, &["show", &object])?;
537    if !shown.status.success() {
538        return Err(BaseBaselineError::GitFailed(
539            String::from_utf8_lossy(&shown.stderr).trim().to_owned(),
540        ));
541    }
542    Ok(Some(String::from_utf8_lossy(&shown.stdout).into_owned()))
543}
544
545/// True when `git_ref` names the commit that `HEAD` names in the repository
546/// at `dir`. A base that resolves to `HEAD` compares a committed baseline with
547/// itself, so only an uncommitted change can grow it.
548#[must_use]
549pub fn ref_is_head(dir: &Path, git_ref: &str) -> bool {
550    let resolve = |rev: &str| {
551        run_git(
552            dir,
553            &["rev-parse", "--verify", "--quiet", &peel_to_commit(rev)],
554        )
555        .ok()
556        .filter(|output| output.status.success())
557        .map(|output| String::from_utf8_lossy(&output.stdout).trim().to_owned())
558    };
559    match (resolve(git_ref), resolve("HEAD")) {
560        (Some(base), Some(head)) => base == head,
561        _ => false,
562    }
563}
564
565/// `rev^{commit}`: git resolves it only when `rev` names a commit.
566fn peel_to_commit(rev: &str) -> String {
567    format!("{rev}^{{commit}}")
568}
569
570fn run_git(dir: &Path, args: &[&str]) -> Result<std::process::Output, BaseBaselineError> {
571    crate::git_env::git_command(dir)
572        .args(args)
573        .current_dir(dir)
574        .output()
575        .map_err(|error| BaseBaselineError::GitMissing(error.to_string()))
576}
577
578#[cfg(test)]
579mod tests {
580    use super::*;
581    use serde_json::json;
582
583    fn keys(growth: &BaselineGrowth) -> Vec<(String, Vec<String>)> {
584        growth
585            .categories
586            .iter()
587            .map(|grown| (grown.category.clone(), grown.keys.clone()))
588            .collect()
589    }
590
591    #[test]
592    fn dead_code_growth_is_each_new_key_per_category() {
593        let base = json!({
594            "kind": "dead-code",
595            "unused_files": ["src/a.ts"],
596            "boundary_violations": ["src/ui/a.ts->src/core/x.ts"],
597        });
598        let head = json!({
599            "kind": "dead-code",
600            "scope_reasons": ["workspace"],
601            "unused_files": ["src/a.ts", "src/b.ts"],
602            "boundary_violations": [
603                "src/ui/a.ts->src/core/x.ts",
604                "src/ui/c.ts->src/core/z.ts"
605            ],
606            "unused_exports": ["src/c.ts:x"],
607        });
608        let growth = baseline_growth(BaselineKind::DeadCode, &base, &head);
609        assert_eq!(
610            keys(&growth),
611            vec![
612                (
613                    "boundary_violations".to_owned(),
614                    vec!["src/ui/c.ts->src/core/z.ts".to_owned()]
615                ),
616                ("unused_exports".to_owned(), vec!["src/c.ts:x".to_owned()]),
617                ("unused_files".to_owned(), vec!["src/b.ts".to_owned()]),
618            ]
619        );
620        assert_eq!(growth.added_entries(), 3);
621    }
622
623    #[test]
624    fn dead_code_growth_with_canonical_keys_counts_occurrences() {
625        let base = json!({
626            "identity": "dc1",
627            "unused_class_members": ["unused-class-member:src/a.ts:A:value"],
628        });
629        let head = json!({
630            "identity": "dc1",
631            "unused_class_members": [
632                "unused-class-member:src/a.ts:A:value",
633                "unused-class-member:src/a.ts:A:value"
634            ],
635        });
636
637        let growth = baseline_growth(BaselineKind::DeadCode, &base, &head);
638
639        assert_eq!(
640            keys(&growth),
641            vec![(
642                "unused_class_members".to_owned(),
643                vec!["unused-class-member:src/a.ts:A:value".to_owned()]
644            )]
645        );
646        assert!(baseline_growth(BaselineKind::DeadCode, &head, &base).is_empty());
647    }
648
649    #[test]
650    fn an_upgrade_that_swaps_a_finding_is_growth() {
651        let base = json!({
652            "unused_exports": ["src/a.ts:helperA", "src/b.ts:helperB"],
653        });
654        let head = json!({
655            "identity": "dc1",
656            "unused_exports": [
657                "unused-export:src/b.ts:helperB",
658                "unused-export:src/c.ts:helperC"
659            ],
660        });
661
662        let growth = baseline_growth(BaselineKind::DeadCode, &base, &head);
663
664        assert_eq!(
665            keys(&growth),
666            vec![(
667                "unused_exports".to_owned(),
668                vec!["unused-export:src/c.ts:helperC".to_owned()]
669            )]
670        );
671    }
672
673    #[test]
674    fn a_clean_upgrade_is_not_growth() {
675        let base = json!({
676            "unused_files": ["src/old.ts"],
677            "unused_exports": ["src/a.ts:helperA"],
678            "unused_dependencies": ["packages/app/package.json:lodash"],
679            "unused_class_members": ["src/s.ts:Service.run"],
680            "unlisted_dependencies": ["chalk"],
681            "duplicate_exports": ["Config|src/b.ts|src/a.ts"],
682            "circular_dependencies": ["src/a.ts->src/b.ts"],
683            "boundary_violations": ["src/ui/a.ts->src/db/q.ts"],
684            "stale_suppressions": ["stale-suppression:src/f.ts:3"],
685        });
686        let head = json!({
687            "identity": "dc1",
688            "unused_files": ["unused-file:src/old.ts"],
689            "unused_exports": ["unused-export:src/a.ts:helperA"],
690            "unused_dependencies": ["unused-dependency:packages/app/package.json:lodash"],
691            "unused_class_members": ["unused-class-member:src/s.ts:Service:run"],
692            "unlisted_dependencies": ["unlisted-dependency:chalk"],
693            "duplicate_exports": ["duplicate-export:Config:src/a.ts|src/b.ts"],
694            "circular_dependencies": ["circular-dependency:src/a.ts|src/b.ts"],
695            "boundary_violations": ["boundary-violation:src/ui/a.ts:src/db/q.ts"],
696            "stale_suppressions": ["stale-suppression:src/f.ts:comment:unused-export:line"],
697        });
698
699        assert!(baseline_growth(BaselineKind::DeadCode, &base, &head).is_empty());
700    }
701
702    #[test]
703    fn a_legacy_key_without_a_translation_falls_back_to_the_entry_count() {
704        let base = json!({ "unused_dependencies": ["lodash"] });
705        let head = json!({
706            "identity": "dc1",
707            "unused_dependencies": [
708                "unused-dependency:package.json:lodash",
709                "unused-dependency:package.json:chalk"
710            ],
711        });
712
713        assert_eq!(
714            baseline_growth(BaselineKind::DeadCode, &base, &head).added_entries(),
715            1
716        );
717    }
718
719    #[test]
720    fn a_rewritten_legacy_baseline_is_compared_by_entry_counts() {
721        let base = json!({ "unused_files": ["src/a.ts", "src/b.ts"] });
722        let same = json!({
723            "identity": "dc1",
724            "unused_files": ["unused-file:src/a.ts", "unused-file:src/b.ts"],
725        });
726        let grown = json!({
727            "identity": "dc1",
728            "unused_files": [
729                "unused-file:src/a.ts",
730                "unused-file:src/b.ts",
731                "unused-file:src/c.ts"
732            ],
733        });
734
735        assert!(baseline_growth(BaselineKind::DeadCode, &base, &same).is_empty());
736        assert_eq!(
737            baseline_growth(BaselineKind::DeadCode, &base, &grown).added_entries(),
738            1
739        );
740    }
741
742    #[test]
743    fn a_removed_or_kept_key_is_not_growth() {
744        let base = json!({ "unused_files": ["src/a.ts", "src/b.ts"] });
745        let head = json!({ "unused_files": ["src/b.ts"] });
746        assert!(baseline_growth(BaselineKind::DeadCode, &base, &head).is_empty());
747    }
748
749    #[test]
750    fn dupes_growth_counts_one_key_per_clone_group() {
751        let base = json!({
752            "clone_groups": ["a.ts:1-9|b.ts:1-9"],
753            "clone_fingerprints": ["f1"],
754            "normalized_clone_fingerprints": ["n1"],
755        });
756        let head = json!({
757            "clone_groups": ["a.ts:1-9|b.ts:1-9", "c.ts:1-9|d.ts:1-9"],
758            "clone_fingerprints": ["f1", "f2"],
759            "normalized_clone_fingerprints": ["n1", "n2"],
760        });
761        let growth = baseline_growth(BaselineKind::Dupes, &base, &head);
762        assert_eq!(
763            keys(&growth),
764            vec![(DUPES_FINGERPRINTS.to_owned(), vec!["n2".to_owned()])]
765        );
766    }
767
768    #[test]
769    fn a_legacy_dupes_base_is_compared_by_clone_group_keys() {
770        let base = json!({ "clone_groups": ["a.ts:1-9|b.ts:1-9"] });
771        let head = json!({
772            "clone_groups": ["a.ts:1-9|b.ts:1-9"],
773            "normalized_clone_fingerprints": ["n1"],
774        });
775        assert!(baseline_growth(BaselineKind::Dupes, &base, &head).is_empty());
776    }
777
778    #[test]
779    fn legacy_health_findings_allow_only_the_known_file_counts_on_upgrade() {
780        let base = json!({"findings": ["src/a.ts:parse:42"]});
781        let head = json!({
782            "finding_counts": {
783                "src/a.ts": {"complexity_high": {"count": 1}, "crap_high": {"count": 1}},
784                "src/b.ts": {"complexity_high": {"count": 1}},
785            },
786            "target_keys": ["src/b.ts:split"]
787        });
788        assert_eq!(
789            keys(&baseline_growth(BaselineKind::Health, &base, &head)),
790            vec![
791                (
792                    "finding_counts".to_owned(),
793                    vec!["src/b.ts (at least 1 needed, 0 covered by old keys)".to_owned()]
794                ),
795                ("target_keys".to_owned(), vec!["src/b.ts:split".to_owned()]),
796            ]
797        );
798    }
799
800    #[test]
801    fn legacy_health_findings_allow_only_matching_names_in_identity_buckets() {
802        let base = json!({"findings": ["src/a.ts:parse:42", "src/a.ts:old:8"]});
803        let head = json!({
804            "finding_counts": {"src/a.ts": {"complexity_high": {"count": 2}}},
805            "identity_finding_counts": {
806                "src/a.ts\u{0}parse": {"complexity_high": {"count": 1}},
807                "src/a.ts\u{0}new": {"complexity_high": {"count": 1}},
808            }
809        });
810        assert_eq!(
811            keys(&baseline_growth(BaselineKind::Health, &base, &head)),
812            vec![(
813                "identity_finding_counts".to_owned(),
814                vec!["src/a.ts:new (at least 1 needed, 0 covered by old keys)".to_owned()]
815            )]
816        );
817    }
818
819    #[test]
820    fn a_higher_health_count_is_growth() {
821        let base = json!({
822            "finding_counts": { "src/a.ts": { "cyclomatic": { "count": 1 } } },
823        });
824        let head = json!({
825            "finding_counts": {
826                "src/a.ts": { "cyclomatic": { "count": 2 } },
827                "src/b.ts": { "cognitive": { "count": 1 } },
828            },
829            "target_keys": ["src/b.ts:split"],
830        });
831        let growth = baseline_growth(BaselineKind::Health, &base, &head);
832        assert_eq!(
833            keys(&growth),
834            vec![
835                (
836                    HEALTH_FILE_COUNTS.to_owned(),
837                    vec![
838                        "src/a.ts cyclomatic (count 1 -> 2)".to_owned(),
839                        "src/b.ts cognitive (count 1)".to_owned(),
840                    ]
841                ),
842                ("target_keys".to_owned(), vec!["src/b.ts:split".to_owned()]),
843            ]
844        );
845        assert_eq!(growth.added_entries(), 3);
846    }
847
848    #[test]
849    fn a_long_file_moved_out_of_a_complexity_slot_is_not_growth() {
850        let file = "src/a.ts\u{0}<file>";
851        let base = json!({
852            "finding_counts": { "src/a.ts": { "complexity_moderate": { "count": 1 } } },
853            "identity_finding_counts": { file: { "complexity_moderate": { "count": 1 } } },
854        });
855        let head = json!({
856            "file_lines_categories": true,
857            "finding_counts": { "src/a.ts": { "file_lines_moderate": { "count": 1 } } },
858            "identity_finding_counts": { file: { "file_lines_moderate": { "count": 1 } } },
859        });
860        assert!(baseline_growth(BaselineKind::Health, &base, &head).is_empty());
861
862        let marked_base = json!({
863            "file_lines_categories": true,
864            "identity_finding_counts": { file: { "complexity_moderate": { "count": 1 } } },
865        });
866        assert_eq!(
867            baseline_growth(BaselineKind::Health, &marked_base, &head).added_entries(),
868            1
869        );
870    }
871
872    #[test]
873    fn a_count_bucket_gives_a_long_file_no_freed_complexity_slot() {
874        // The base slot can be a function that was fixed, so the long file is new.
875        let base = json!({
876            "finding_counts": { "src/a.ts": { "complexity_moderate": { "count": 1 } } },
877        });
878        let head = json!({
879            "file_lines_categories": true,
880            "finding_counts": { "src/a.ts": { "file_lines_moderate": { "count": 1 } } },
881        });
882        let growth = baseline_growth(BaselineKind::Health, &base, &head);
883        assert_eq!(
884            keys(&growth),
885            vec![(
886                HEALTH_FILE_COUNTS.to_owned(),
887                vec!["src/a.ts file_lines_moderate (count 1)".to_owned()]
888            )]
889        );
890    }
891
892    #[test]
893    fn identity_counts_replace_file_counts_when_both_files_have_them() {
894        let base = json!({
895            "finding_counts": { "src/a.ts": { "cyclomatic": { "count": 1 } } },
896            "identity_finding_counts": { "src/a.ts\u{0}old": { "cyclomatic": { "count": 1 } } },
897        });
898        let head = json!({
899            "finding_counts": { "src/a.ts": { "cyclomatic": { "count": 1 } } },
900            "identity_finding_counts": { "src/a.ts\u{0}new": { "cyclomatic": { "count": 1 } } },
901        });
902        let growth = baseline_growth(BaselineKind::Health, &base, &head);
903        assert_eq!(
904            keys(&growth),
905            vec![(
906                HEALTH_IDENTITY_COUNTS.to_owned(),
907                vec!["src/a.ts:new cyclomatic (count 1)".to_owned()]
908            )]
909        );
910    }
911}