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