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";
135
136/// The string members of the array `category`, as a set.
137fn key_set<'a>(object: &'a Map<String, Value>, category: &str) -> BTreeSet<&'a str> {
138    object
139        .get(category)
140        .and_then(Value::as_array)
141        .map(|keys| keys.iter().filter_map(Value::as_str).collect())
142        .unwrap_or_default()
143}
144
145fn has_entries(object: &Map<String, Value>, category: &str) -> bool {
146    object
147        .get(category)
148        .and_then(Value::as_object)
149        .is_some_and(|buckets| !buckets.is_empty())
150}
151
152fn add_new_keys(
153    grown: &mut BTreeMap<String, Vec<String>>,
154    category: &str,
155    base: &Map<String, Value>,
156    head: &Map<String, Value>,
157) {
158    let known = key_set(base, category);
159    let added: Vec<String> = key_set(head, category)
160        .into_iter()
161        .filter(|key| !known.contains(key))
162        .map(display_key)
163        .collect();
164    if !added.is_empty() {
165        grown.entry(category.to_owned()).or_default().extend(added);
166    }
167}
168
169/// The string members of the array `category`, with the number of times each
170/// occurs.
171fn key_counts<'a>(object: &'a Map<String, Value>, category: &str) -> BTreeMap<&'a str, usize> {
172    let mut counts = BTreeMap::new();
173    for key in object
174        .get(category)
175        .and_then(Value::as_array)
176        .into_iter()
177        .flatten()
178        .filter_map(Value::as_str)
179    {
180        *counts.entry(key).or_insert(0) += 1;
181    }
182    counts
183}
184
185/// One entry for each occurrence of a key beyond its count at the base.
186fn add_new_occurrences(
187    grown: &mut BTreeMap<String, Vec<String>>,
188    category: &str,
189    base: &Map<String, Value>,
190    head: &Map<String, Value>,
191) {
192    let known: BTreeMap<String, usize> = key_counts(base, category)
193        .into_iter()
194        .map(|(key, count)| (key.to_owned(), count))
195        .collect();
196    push_new_occurrences(grown, category, &known, head);
197}
198
199/// Push one entry for each occurrence of a head key beyond its `known` count.
200fn push_new_occurrences(
201    grown: &mut BTreeMap<String, Vec<String>>,
202    category: &str,
203    known: &BTreeMap<String, usize>,
204    head: &Map<String, Value>,
205) {
206    let mut added = Vec::new();
207    for (key, now) in key_counts(head, category) {
208        let before = known.get(key).copied().unwrap_or(0);
209        added.extend(std::iter::repeat_n(
210            display_key(key),
211            now.saturating_sub(before),
212        ));
213    }
214    if !added.is_empty() {
215        grown.entry(category.to_owned()).or_default().extend(added);
216    }
217}
218
219/// Compare a legacy base category with a canonical head category. Every legacy
220/// key must translate, or the category falls back to its entry count.
221fn add_grown_after_upgrade(
222    grown: &mut BTreeMap<String, Vec<String>>,
223    category: &str,
224    base: &Map<String, Value>,
225    head: &Map<String, Value>,
226) {
227    let mut known: BTreeMap<String, usize> = BTreeMap::new();
228    for (key, count) in key_counts(base, category) {
229        let Some(canonical) = canonical_from_legacy(category, key) else {
230            add_grown_entry_count(grown, category, base, head);
231            return;
232        };
233        *known.entry(canonical).or_insert(0) += count;
234    }
235    push_new_occurrences(grown, category, &known, head);
236}
237
238/// The canonical key of a legacy dead-code baseline key, when the legacy form
239/// holds every part of the canonical key and no line.
240fn canonical_from_legacy(category: &str, key: &str) -> Option<String> {
241    let paths = IdentityPaths::new(Path::new(""));
242    let path = |value: &str| paths.key(Path::new(value));
243    let set = |values: &[&str]| paths.set(values.iter().map(Path::new));
244    let canonical = |rule: &str, parts: &[String]| {
245        let parts: Vec<&str> = parts.iter().map(String::as_str).collect();
246        Some(dead_code_canonical_key(rule, &parts))
247    };
248    let path_name = |rule: &str| {
249        let (file, name) = key.split_once(':')?;
250        canonical(rule, &[path(file), name.to_owned()])
251    };
252    let manifest_package = |rule: &str| {
253        let (manifest, package) = key.rsplit_once(':')?;
254        if !manifest.ends_with("package.json") {
255            return None;
256        }
257        canonical(rule, &[path(manifest), package.to_owned()])
258    };
259    let member = |rule: &str| {
260        let (file, member) = key.split_once(':')?;
261        let (parent, name) = member.split_once('.')?;
262        canonical(rule, &[path(file), parent.to_owned(), name.to_owned()])
263    };
264    match category {
265        "unused_files" => canonical("unused-file", &[path(key)]),
266        "unused_exports" => path_name("unused-export"),
267        "unused_types" => path_name("unused-type"),
268        "deprecated_exports_in_use" => path_name("deprecated-export-in-use"),
269        "invalid_client_exports" => path_name("invalid-client-export"),
270        "unresolved_imports" => path_name("unresolved-import"),
271        "unprovided_injects" => path_name("unprovided-inject"),
272        "unrendered_components" => path_name("unrendered-component"),
273        "unused_server_actions" => path_name("unused-server-action"),
274        "unused_load_data_keys" => path_name("unused-load-data-key"),
275        "route_collisions" => path_name("route-collision"),
276        "dynamic_segment_name_conflicts" => path_name("dynamic-segment-name-conflict"),
277        "boundary_call_violations" => path_name("boundary-call-violation"),
278        "boundary_coverage_violations" => canonical("boundary-coverage", &[path(key)]),
279        "unused_dependencies" => manifest_package("unused-dependency"),
280        "unused_dev_dependencies" => manifest_package("unused-dev-dependency"),
281        "unused_optional_dependencies" => manifest_package("unused-optional-dependency"),
282        "type_only_dependencies" => manifest_package("type-only-dependency"),
283        "test_only_dependencies" => manifest_package("test-only-dependency"),
284        "dev_dependencies_in_production" => manifest_package("dev-dependency-in-production"),
285        "unused_enum_members" => member("unused-enum-member"),
286        "unused_class_members" => member("unused-class-member"),
287        "unused_namespace_members" => member("unused-namespace-member"),
288        "unused_protected_class_members" => member("unused-protected-class-member"),
289        "unused_store_members" => member("unused-store-member"),
290        "unlisted_dependencies" => canonical("unlisted-dependency", &[key.to_owned()]),
291        "private_type_leaks" => {
292            let (file, rest) = key.split_once(':')?;
293            let (export, leaked) = rest.split_once("->")?;
294            canonical(
295                "private-type-leak",
296                &[path(file), export.to_owned(), leaked.to_owned()],
297            )
298        }
299        "duplicate_exports" => {
300            let mut parts = key.split('|');
301            let name = parts.next()?.to_owned();
302            let files: Vec<&str> = parts.collect();
303            if files.is_empty() {
304                return None;
305            }
306            canonical("duplicate-export", &[name, set(&files)])
307        }
308        "circular_dependencies" => {
309            let files: Vec<&str> = key.split("->").collect();
310            canonical("circular-dependency", &[set(&files)])
311        }
312        "re_export_cycles" => {
313            let (kind, rest) = key.split_once(':')?;
314            let files: Vec<&str> = rest.split("<->").collect();
315            canonical("re-export-cycle", &[kind.to_owned(), set(&files)])
316        }
317        "boundary_violations" => {
318            let (from, to) = key.split_once("->")?;
319            canonical("boundary-violation", &[path(from), path(to)])
320        }
321        "unused_dependency_overrides" => {
322            let (source, raw_key) = key.split_once(':')?;
323            canonical(
324                "unused-dependency-override",
325                &[source.to_owned(), raw_key.to_owned()],
326            )
327        }
328        "misconfigured_dependency_overrides" => {
329            let (source, raw_key) = key.split_once(':')?;
330            canonical(
331                "misconfigured-dependency-override",
332                &[source.to_owned(), raw_key.to_owned()],
333            )
334        }
335        // Keys with a line (stale suppressions, misplaced directives, catalog
336        // references), keys without the path or component name of the
337        // canonical key (catalog entries and groups, component contracts),
338        // keys whose parts cannot be split safely (policy violations) and
339        // keys whose canonical key has fewer parts (client and server barrels)
340        // have no translation.
341        _ => None,
342    }
343}
344
345/// One entry for each entry of `category` beyond its count at the base. Used
346/// when the two files write keys in different forms.
347fn add_grown_entry_count(
348    grown: &mut BTreeMap<String, Vec<String>>,
349    category: &str,
350    base: &Map<String, Value>,
351    head: &Map<String, Value>,
352) {
353    let entries = |object: &Map<String, Value>| {
354        object
355            .get(category)
356            .and_then(Value::as_array)
357            .map_or(0, Vec::len)
358    };
359    let (before, now) = (entries(base), entries(head));
360    let extra = now.saturating_sub(before);
361    let added = (1..=extra).map(|index| {
362        format!(
363            "new entry {index} of {extra}: the key format changed, so the gate compares entry counts ({before} -> {now})"
364        )
365    });
366    if extra > 0 {
367        grown.entry(category.to_owned()).or_default().extend(added);
368    }
369}
370
371/// Health count buckets: `path -> finding category -> { count }`. A bucket
372/// whose count is higher than at the base is growth, also when the base has no
373/// such bucket.
374fn add_grown_counts(
375    grown: &mut BTreeMap<String, Vec<String>>,
376    category: &str,
377    base: &Map<String, Value>,
378    head: &Map<String, Value>,
379) {
380    let Some(head_buckets) = head.get(category).and_then(Value::as_object) else {
381        return;
382    };
383    let base_buckets = base.get(category).and_then(Value::as_object);
384    let mut added = Vec::new();
385    for (path, finding_counts) in head_buckets {
386        let Some(finding_counts) = finding_counts.as_object() else {
387            continue;
388        };
389        for (finding, count) in finding_counts {
390            let now = bucket_count(Some(count));
391            let before = bucket_count(
392                base_buckets
393                    .and_then(|buckets| buckets.get(path))
394                    .and_then(|counts| counts.get(finding)),
395            );
396            if now > before {
397                let key = display_key(path);
398                added.push(if before == 0 {
399                    format!("{key} {finding} (count {now})")
400                } else {
401                    format!("{key} {finding} (count {before} -> {now})")
402                });
403            }
404        }
405    }
406    if !added.is_empty() {
407        grown.entry(category.to_owned()).or_default().extend(added);
408    }
409}
410
411fn bucket_count(bucket: Option<&Value>) -> u64 {
412    bucket
413        .and_then(|bucket| bucket.get("count"))
414        .and_then(Value::as_u64)
415        .unwrap_or(0)
416}
417
418/// Some formats join key parts with a NUL byte. Show it as `:`, so the
419/// message stays on one line and prints in every terminal.
420fn display_key(key: &str) -> String {
421    key.replace('\0', ":")
422}
423
424/// Why the baseline at the base ref could not be read.
425#[derive(Debug, Clone, PartialEq, Eq)]
426pub enum BaseBaselineError {
427    /// `git` could not be started.
428    GitMissing(String),
429    /// The baseline is not in a git work tree.
430    NotARepository,
431    /// Git cannot resolve the ref to a commit, typically because a shallow
432    /// clone did not fetch it.
433    RefUnavailable,
434    /// Git failed for another reason.
435    GitFailed(String),
436}
437
438/// Read the version of the file at `path` that the commit `git_ref` has.
439///
440/// `Ok(None)` when the commit has no file at that path, which is a baseline
441/// that the change adds. The path is resolved relative to the directory of the
442/// file, so a baseline in a nested directory or under `--root` reads correctly.
443pub fn read_baseline_at_ref(
444    path: &Path,
445    git_ref: &str,
446) -> Result<Option<String>, BaseBaselineError> {
447    let dir = match path.parent() {
448        Some(parent) if !parent.as_os_str().is_empty() => parent,
449        _ => Path::new("."),
450    };
451    let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
452        return Err(BaseBaselineError::GitFailed(format!(
453            "the baseline path {} has no file name",
454            path.display()
455        )));
456    };
457    let inside = run_git(dir, &["rev-parse", "--is-inside-work-tree"])?;
458    if !inside.status.success() {
459        return Err(BaseBaselineError::NotARepository);
460    }
461    let resolved = run_git(
462        dir,
463        &["rev-parse", "--verify", "--quiet", &peel_to_commit(git_ref)],
464    )?;
465    if !resolved.status.success() {
466        return Err(BaseBaselineError::RefUnavailable);
467    }
468    let object = format!("{git_ref}:./{name}");
469    let exists = run_git(dir, &["cat-file", "-e", &object])?;
470    if !exists.status.success() {
471        return Ok(None);
472    }
473    let shown = run_git(dir, &["show", &object])?;
474    if !shown.status.success() {
475        return Err(BaseBaselineError::GitFailed(
476            String::from_utf8_lossy(&shown.stderr).trim().to_owned(),
477        ));
478    }
479    Ok(Some(String::from_utf8_lossy(&shown.stdout).into_owned()))
480}
481
482/// True when `git_ref` names the commit that `HEAD` names in the repository
483/// at `dir`. A base that resolves to `HEAD` compares a committed baseline with
484/// itself, so only an uncommitted change can grow it.
485#[must_use]
486pub fn ref_is_head(dir: &Path, git_ref: &str) -> bool {
487    let resolve = |rev: &str| {
488        run_git(
489            dir,
490            &["rev-parse", "--verify", "--quiet", &peel_to_commit(rev)],
491        )
492        .ok()
493        .filter(|output| output.status.success())
494        .map(|output| String::from_utf8_lossy(&output.stdout).trim().to_owned())
495    };
496    match (resolve(git_ref), resolve("HEAD")) {
497        (Some(base), Some(head)) => base == head,
498        _ => false,
499    }
500}
501
502/// `rev^{commit}`: git resolves it only when `rev` names a commit.
503fn peel_to_commit(rev: &str) -> String {
504    format!("{rev}^{{commit}}")
505}
506
507fn run_git(dir: &Path, args: &[&str]) -> Result<std::process::Output, BaseBaselineError> {
508    crate::git_env::git_command(dir)
509        .args(args)
510        .current_dir(dir)
511        .output()
512        .map_err(|error| BaseBaselineError::GitMissing(error.to_string()))
513}
514
515#[cfg(test)]
516mod tests {
517    use super::*;
518    use serde_json::json;
519
520    fn keys(growth: &BaselineGrowth) -> Vec<(String, Vec<String>)> {
521        growth
522            .categories
523            .iter()
524            .map(|grown| (grown.category.clone(), grown.keys.clone()))
525            .collect()
526    }
527
528    #[test]
529    fn dead_code_growth_is_each_new_key_per_category() {
530        let base = json!({
531            "kind": "dead-code",
532            "unused_files": ["src/a.ts"],
533            "boundary_violations": ["src/ui/a.ts->src/core/x.ts"],
534        });
535        let head = json!({
536            "kind": "dead-code",
537            "unused_files": ["src/a.ts", "src/b.ts"],
538            "boundary_violations": [
539                "src/ui/a.ts->src/core/x.ts",
540                "src/ui/c.ts->src/core/z.ts"
541            ],
542            "unused_exports": ["src/c.ts:x"],
543        });
544        let growth = baseline_growth(BaselineKind::DeadCode, &base, &head);
545        assert_eq!(
546            keys(&growth),
547            vec![
548                (
549                    "boundary_violations".to_owned(),
550                    vec!["src/ui/c.ts->src/core/z.ts".to_owned()]
551                ),
552                ("unused_exports".to_owned(), vec!["src/c.ts:x".to_owned()]),
553                ("unused_files".to_owned(), vec!["src/b.ts".to_owned()]),
554            ]
555        );
556        assert_eq!(growth.added_entries(), 3);
557    }
558
559    #[test]
560    fn dead_code_growth_with_canonical_keys_counts_occurrences() {
561        let base = json!({
562            "identity": "dc1",
563            "unused_class_members": ["unused-class-member:src/a.ts:A:value"],
564        });
565        let head = json!({
566            "identity": "dc1",
567            "unused_class_members": [
568                "unused-class-member:src/a.ts:A:value",
569                "unused-class-member:src/a.ts:A:value"
570            ],
571        });
572
573        let growth = baseline_growth(BaselineKind::DeadCode, &base, &head);
574
575        assert_eq!(
576            keys(&growth),
577            vec![(
578                "unused_class_members".to_owned(),
579                vec!["unused-class-member:src/a.ts:A:value".to_owned()]
580            )]
581        );
582        assert!(baseline_growth(BaselineKind::DeadCode, &head, &base).is_empty());
583    }
584
585    #[test]
586    fn an_upgrade_that_swaps_a_finding_is_growth() {
587        let base = json!({
588            "unused_exports": ["src/a.ts:helperA", "src/b.ts:helperB"],
589        });
590        let head = json!({
591            "identity": "dc1",
592            "unused_exports": [
593                "unused-export:src/b.ts:helperB",
594                "unused-export:src/c.ts:helperC"
595            ],
596        });
597
598        let growth = baseline_growth(BaselineKind::DeadCode, &base, &head);
599
600        assert_eq!(
601            keys(&growth),
602            vec![(
603                "unused_exports".to_owned(),
604                vec!["unused-export:src/c.ts:helperC".to_owned()]
605            )]
606        );
607    }
608
609    #[test]
610    fn a_clean_upgrade_is_not_growth() {
611        let base = json!({
612            "unused_files": ["src/old.ts"],
613            "unused_exports": ["src/a.ts:helperA"],
614            "unused_dependencies": ["packages/app/package.json:lodash"],
615            "unused_class_members": ["src/s.ts:Service.run"],
616            "unlisted_dependencies": ["chalk"],
617            "duplicate_exports": ["Config|src/b.ts|src/a.ts"],
618            "circular_dependencies": ["src/a.ts->src/b.ts"],
619            "boundary_violations": ["src/ui/a.ts->src/db/q.ts"],
620            "stale_suppressions": ["stale-suppression:src/f.ts:3"],
621        });
622        let head = json!({
623            "identity": "dc1",
624            "unused_files": ["unused-file:src/old.ts"],
625            "unused_exports": ["unused-export:src/a.ts:helperA"],
626            "unused_dependencies": ["unused-dependency:packages/app/package.json:lodash"],
627            "unused_class_members": ["unused-class-member:src/s.ts:Service:run"],
628            "unlisted_dependencies": ["unlisted-dependency:chalk"],
629            "duplicate_exports": ["duplicate-export:Config:src/a.ts|src/b.ts"],
630            "circular_dependencies": ["circular-dependency:src/a.ts|src/b.ts"],
631            "boundary_violations": ["boundary-violation:src/ui/a.ts:src/db/q.ts"],
632            "stale_suppressions": ["stale-suppression:src/f.ts:comment:unused-export:line"],
633        });
634
635        assert!(baseline_growth(BaselineKind::DeadCode, &base, &head).is_empty());
636    }
637
638    #[test]
639    fn a_legacy_key_without_a_translation_falls_back_to_the_entry_count() {
640        let base = json!({ "unused_dependencies": ["lodash"] });
641        let head = json!({
642            "identity": "dc1",
643            "unused_dependencies": [
644                "unused-dependency:package.json:lodash",
645                "unused-dependency:package.json:chalk"
646            ],
647        });
648
649        assert_eq!(
650            baseline_growth(BaselineKind::DeadCode, &base, &head).added_entries(),
651            1
652        );
653    }
654
655    #[test]
656    fn a_rewritten_legacy_baseline_is_compared_by_entry_counts() {
657        let base = json!({ "unused_files": ["src/a.ts", "src/b.ts"] });
658        let same = json!({
659            "identity": "dc1",
660            "unused_files": ["unused-file:src/a.ts", "unused-file:src/b.ts"],
661        });
662        let grown = json!({
663            "identity": "dc1",
664            "unused_files": [
665                "unused-file:src/a.ts",
666                "unused-file:src/b.ts",
667                "unused-file:src/c.ts"
668            ],
669        });
670
671        assert!(baseline_growth(BaselineKind::DeadCode, &base, &same).is_empty());
672        assert_eq!(
673            baseline_growth(BaselineKind::DeadCode, &base, &grown).added_entries(),
674            1
675        );
676    }
677
678    #[test]
679    fn a_removed_or_kept_key_is_not_growth() {
680        let base = json!({ "unused_files": ["src/a.ts", "src/b.ts"] });
681        let head = json!({ "unused_files": ["src/b.ts"] });
682        assert!(baseline_growth(BaselineKind::DeadCode, &base, &head).is_empty());
683    }
684
685    #[test]
686    fn dupes_growth_counts_one_key_per_clone_group() {
687        let base = json!({
688            "clone_groups": ["a.ts:1-9|b.ts:1-9"],
689            "clone_fingerprints": ["f1"],
690            "normalized_clone_fingerprints": ["n1"],
691        });
692        let head = json!({
693            "clone_groups": ["a.ts:1-9|b.ts:1-9", "c.ts:1-9|d.ts:1-9"],
694            "clone_fingerprints": ["f1", "f2"],
695            "normalized_clone_fingerprints": ["n1", "n2"],
696        });
697        let growth = baseline_growth(BaselineKind::Dupes, &base, &head);
698        assert_eq!(
699            keys(&growth),
700            vec![(DUPES_FINGERPRINTS.to_owned(), vec!["n2".to_owned()])]
701        );
702    }
703
704    #[test]
705    fn a_legacy_dupes_base_is_compared_by_clone_group_keys() {
706        let base = json!({ "clone_groups": ["a.ts:1-9|b.ts:1-9"] });
707        let head = json!({
708            "clone_groups": ["a.ts:1-9|b.ts:1-9"],
709            "normalized_clone_fingerprints": ["n1"],
710        });
711        assert!(baseline_growth(BaselineKind::Dupes, &base, &head).is_empty());
712    }
713
714    #[test]
715    fn a_higher_health_count_is_growth() {
716        let base = json!({
717            "finding_counts": { "src/a.ts": { "cyclomatic": { "count": 1 } } },
718        });
719        let head = json!({
720            "finding_counts": {
721                "src/a.ts": { "cyclomatic": { "count": 2 } },
722                "src/b.ts": { "cognitive": { "count": 1 } },
723            },
724            "target_keys": ["src/b.ts:split"],
725        });
726        let growth = baseline_growth(BaselineKind::Health, &base, &head);
727        assert_eq!(
728            keys(&growth),
729            vec![
730                (
731                    HEALTH_FILE_COUNTS.to_owned(),
732                    vec![
733                        "src/a.ts cyclomatic (count 1 -> 2)".to_owned(),
734                        "src/b.ts cognitive (count 1)".to_owned(),
735                    ]
736                ),
737                ("target_keys".to_owned(), vec!["src/b.ts:split".to_owned()]),
738            ]
739        );
740        assert_eq!(growth.added_entries(), 3);
741    }
742
743    #[test]
744    fn identity_counts_replace_file_counts_when_both_files_have_them() {
745        let base = json!({
746            "finding_counts": { "src/a.ts": { "cyclomatic": { "count": 1 } } },
747            "identity_finding_counts": { "src/a.ts\u{0}old": { "cyclomatic": { "count": 1 } } },
748        });
749        let head = json!({
750            "finding_counts": { "src/a.ts": { "cyclomatic": { "count": 1 } } },
751            "identity_finding_counts": { "src/a.ts\u{0}new": { "cyclomatic": { "count": 1 } } },
752        });
753        let growth = baseline_growth(BaselineKind::Health, &base, &head);
754        assert_eq!(
755            keys(&growth),
756            vec![(
757                HEALTH_IDENTITY_COUNTS.to_owned(),
758                vec!["src/a.ts:new cyclomatic (count 1)".to_owned()]
759            )]
760        );
761    }
762}